{"slug": "6-silent-security-bugs-ai-coding-agents-keep-shipping-and-a-zero-dep-cli-to-them", "title": "6 Silent Security Bugs AI Coding Agents Keep Shipping (and a Zero-Dep CLI to Catch Them)", "summary": "A developer published an audit of dozens of AI-assisted TypeScript, Next.js and Node.js repositories finding the same six security bugs recurring in pull requests from coding agents such as Claude Code, Cursor, Codex and Copilot, including hardcoded JWT secret fallbacks, jwt.decode() used in place of jwt.verify(), server secrets exposed via NEXT_PUBLIC_/VITE_ prefixes, wildcard CORS with credentials, and empty catch blocks that swallow auth errors. The writeup pairs each flaw with a fail-closed fix and releases a free, zero-dependency open-source CLI plus two agent skills, ai-code-audit-lite, to catch the patterns before merge.", "body_md": "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.\n\nEvery single line compiles. TypeScript is happy. ESLint passes with zero warnings.\n\nAnd 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.\"*\n\nHere 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.\n\n`|| \"dev-secret\"`)\nTo make sure generated code doesn't crash on your laptop when `.env` is incomplete, LLMs love adding a fallback string:\n\n```\n// ❌ Vulnerable: if JWT_SECRET is missing in prod, anyone can forge tokens\nconst JWT_SECRET = process.env.JWT_SECRET || \"dev-secret-do-not-use\";\n```\n\nIf a deployment pipeline drops or misnames `JWT_SECRET` in staging or production, your app silently boots using a string visible in your Git repository.\n\n``` js\n// ✅ Fix: fail closed at startup\nconst JWT_SECRET = process.env.JWT_SECRET;\nif (!JWT_SECRET || JWT_SECRET.length < 32) {\n  throw new Error(\"Missing or weak JWT_SECRET environment variable\");\n}\n```\n\n`jwt.decode()` Instead of `jwt.verify()`\nWhen 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**:\n\n```\n// ❌ Vulnerable: accepts any self-signed or tampered JWT payload\nexport function getUserFromHeader(authHeader: string) {\n  const token = authHeader.replace(\"Bearer \", \"\");\n  return jwt.decode(token);\n}\n```\n\nAn attacker can take any JWT, change `\"role\": \"admin\"` or `\"sub\": \"victim-id\"`, re-encode it in Base64, and walk straight in.\n\n```\n// ✅ Fix: verify signature, pin allowed algorithms, issuer & audience\nexport function getUserFromHeader(authHeader: string) {\n  const token = authHeader.replace(/^Bearer\\s+/i, \"\");\n  return jwt.verify(token, JWT_PUBLIC_KEY, {\n    algorithms: [\"RS256\"],\n    issuer: \"https://auth.example.com\",\n    audience: \"api.example.com\",\n  });\n}\n```\n\n`NEXT_PUBLIC_` / `VITE_` Prefixed Server Secrets\nIn 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:\n\n``` js\n// ❌ Vulnerable: shipped to every visitor's browser DevTools\nexport const config = {\n  supabaseKey: process.env.NEXT_PUBLIC_SUPABASE_SERVICE_ROLE_KEY,\n  stripeSecret: process.env.NEXT_PUBLIC_STRIPE_SECRET_KEY,\n};\n```\n\nExposing a Supabase `service_role` key completely bypasses Row-Level Security (RLS) across your entire database.\n\n**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.\n\n`catch {}` Blocks\nTwo classic \"make the error go away\" patches generated under time pressure:\n\n```\n// ❌ Vulnerable: lets any malicious origin send authenticated requests\napp.use(cors({ origin: \"*\", credentials: true }));\n\n// ❌ Vulnerable: silently swallows auth/webhook verification errors\ntry {\n  verifyWebhookSignature(req);\n} catch (e) {}\njs\n// ✅ Fix: explicit origin allowlist + fail-closed error handling\nconst ALLOWED_ORIGINS = new Set([\"https://app.example.com\"]);\n\napp.use(\n  cors({\n    origin: (origin, cb) =>\n      cb(null, !origin || ALLOWED_ORIGINS.has(origin)),\n    credentials: true,\n  })\n);\n```\n\nAlways return `401`/` 403` (or rethrow) when verification throws—never swallow security exceptions in an empty `catch`.\n\nORMs 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:\n\n```\n// ❌ Vulnerable: SQL injection via $queryRawUnsafe\nreturn prisma.$queryRawUnsafe(\n  `SELECT * FROM users WHERE email = '${email}'`\n);\n\n// ❌ Vulnerable: OS command injection via shell interpolation\nexec(`wkhtmltopdf ${filename} out.pdf`);\n// ✅ Fix: tagged-template parameterized SQL + shell-free execFile\nreturn prisma.$queryRaw`SELECT * FROM users WHERE email = ${email}`;\n\n// Validate filename strictly and pass args as an array (shell: false)\nexecFile(\"wkhtmltopdf\", [safeFilename, \"out.pdf\"], { shell: false });\n```\n\n`Dockerfile` Secret Layers & GitHub Actions `pull_request_target` RCE\nSecurity bugs don't stop in `src/`. AI-generated DevOps files routinely introduce two critical infrastructure flaws:\n\n```\n# ❌ Vulnerable: ARG values & COPY .env remain embedded in image layers\nFROM node:22-alpine\nARG DATABASE_URL\nCOPY .env .env\n```\n\nAnd in `.github/workflows/`:\n\n```\n# ❌ Vulnerable: executes untrusted fork PR code with repo write secrets\non:\n  pull_request_target:\njobs:\n  triage:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n        with:\n          ref: ${{ github.event.pull_request.head.sha }}\n      - run: echo \"Auditing ${{ github.event.pull_request.title }}\"\n```\n\n**Fixes:**\n\n`ARG` or `COPY .env`—add `.env*` to `.dockerignore`, inject secrets at runtime, or use BuildKit `--mount=type=secret`.` on: pull_request` for running PR code, and pass untrusted metadata (`github.event.pull_request.title`) through an `env:` variable instead of interpolating `${{ ... }}` directly inside `run:`.` npx ai-code-audit-lite`)\nTo make pre-merge checks effortless, I open-sourced **`ai-code-audit-lite`** (Apache-2.0, **zero npm dependencies**, Node.js 20+).\n\nRun a full scan or scan only your current `git diff`:\n\n```\n# Scan the whole repo\nnpx ai-code-audit-lite scan .\n\n# Scan only changed files and fail CI on High/Critical findings\nnpx ai-code-audit-lite scan . --diff --fail-on high\n\n# Output SARIF 2.1.0 for GitHub Code Scanning\nnpx ai-code-audit-lite scan . --sarif > ai-audit.sarif\n```\n\nHere's what it outputs on the intentionally vulnerable demo included in the repo:\n\n```\nai-code-audit-lite — Fast Pre-Ship Security Scan\nTarget: .../examples/vulnerable-demo | Scanned: 4 file(s) | Rules: 18\n\n[CRITICAL] ACA-017 (CWE-829) GitHub Actions pull_request_target Checkout (Pwn Request RCE)\n  Location : .github/workflows/pr-triage.yml:12\n[CRITICAL] ACA-001 (CWE-798) Hardcoded Fallback Secret in Auth/Signing Expression\n  Location : api.ts:6\n[CRITICAL] ACA-006 (CWE-347) JWT Decoded Without Signature Verification\n  Location : api.ts:14\n[CRITICAL] ACA-009 (CWE-89) Unsafe Raw SQL Sink (Potential SQL Injection)\n  Location : api.ts:23\n[CRITICAL] ACA-010 (CWE-78) OS Command Injection Sink (Shell Execution with Dynamic Input)\n  Location : api.ts:27\n[CRITICAL] ACA-014 (CWE-798) Secret Baked into Dockerfile Image Layer (ARG / COPY .env)\n  Location : Dockerfile:2\n\nSummary: 7 Critical | 6 High | 2 Medium | 0 Low\n```\n\nStatic 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.\n\nYou can install the **2 free Apache-2.0 Agent Skills** (`security-audit-orchestrator` + `ai-generated-code-audit`) directly into your repo with one command:\n\n```\nnpx ai-code-audit-lite init --target claude   # or: cursor | codex | gemini | agents | all\n```\n\n**GitHub repo (source, 18 built-in rules, GitHub Actions SARIF example & demo):**\n\n👉 [https://github.com/aymenkani/ai-code-audit-lite](https://github.com/aymenkani/ai-code-audit-lite)\n\n**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`.", "url": "https://wpnews.pro/news/6-silent-security-bugs-ai-coding-agents-keep-shipping-and-a-zero-dep-cli-to-them", "canonical_source": "https://dev.to/ayka_code/6-silent-security-bugs-ai-coding-agents-keep-shipping-and-a-zero-dep-cli-to-catch-them-3j6k", "published_at": "2026-12-05 09:08:31+00:00", "updated_at": "2026-12-05 09:13:45.975767+00:00", "lang": "en", "topics": ["ai-agents", "ai-safety", "developer-tools", "ai-tools"], "entities": ["Claude Code", "Cursor", "Codex", "GitHub Copilot", "Next.js", "Vite", "Prisma", "Drizzle"], "also_reported_by": [], "takeaway": "Coding agents optimize for code that boots without setup errors, so audit their output for fallback secrets like process.env.JWT_SECRET || \"dev-secret\", jwt.decode() instead of jwt.verify(), NEXT_PUBLIC_/VITE_ prefixed server keys, wildcard CORS with credentials, and empty catch blocks around auth c", "recommendation": {"advice": "Scan agent-generated code for fallback secrets, jwt.decode() misuse, client-exposed env prefixes, wildcard CORS and empty catch blocks, and fail closed at startup instead.", "playbook": "agent-security", "playbook_url": "https://wpnews.pro/playbooks/agent-security"}, "alternates": {"html": "https://wpnews.pro/news/6-silent-security-bugs-ai-coding-agents-keep-shipping-and-a-zero-dep-cli-to-them", "markdown": "https://wpnews.pro/news/6-silent-security-bugs-ai-coding-agents-keep-shipping-and-a-zero-dep-cli-to-them.md", "text": "https://wpnews.pro/news/6-silent-security-bugs-ai-coding-agents-keep-shipping-and-a-zero-dep-cli-to-them.txt", "jsonld": "https://wpnews.pro/news/6-silent-security-bugs-ai-coding-agents-keep-shipping-and-a-zero-dep-cli-to-them.jsonld"}}