A rich set of vulnerable × fixed patterns for JS/TS and Node.js (Express, Nest, front-end). Mapped to the OWASP Top 10:2025.
Jump to: Injection · XSS · Deserialization & prototypes · Crypto & secrets · Access control · SSRF & requests · Auth & sessions · Resources & errors · Mini-case
❌ Vulnerable:
const q = `SELECT * FROM users WHERE email = '${email}'`; // template string
await db.query("SELECT * FROM users WHERE email = '" + email + "'"); // concat✅ Fixed — parameterized:
await db.query("SELECT * FROM users WHERE email = $1", [email]); // pg
await db.execute("SELECT * FROM users WHERE email = ?", [email]); // mysql2❌ Vulnerable — raw object into the query:
User.findOne({ user: req.body.user, pw: req.body.pw });
// { "pw": { "$ne": null } } → auth bypass✅ Fixed — coerce types / cast to string:
User.findOne({ user: String(req.body.user), pw: String(req.body.pw) });❌ Vulnerable:
const { exec } = require("child_process");
exec(`convert ${filename} out.png`); // filename="x; rm -rf /"✅ Fixed — arg array, no shell:
const { execFile } = require("child_process");
execFile("convert", [filename, "out.png"], { timeout: 5000 });❌ Vulnerable:
const result = eval(req.query.expr);
const fn = new Function("return " + req.body.code);✅ Fixed — parse explicitly; never eval user input:
const result = JSON.parse(req.query.data); // data only❌ Vulnerable:
element.innerHTML = userComment; // parses HTML
document.write(location.hash);
element.insertAdjacentHTML("beforeend", userInput);✅ Fixed — text, not HTML; sanitize if HTML is required:
element.textContent = userComment;
import DOMPurify from "dompurify";
element.innerHTML = DOMPurify.sanitize(userComment);❌ Vulnerable:
<div dangerouslySetInnerHTML={{ __html: userComment }} />✅ Fixed — render as text (JSX auto-escapes) or sanitize:
<div>{userComment}</div>
// or: dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(userComment) }}❌ Vulnerable:
<a href={userUrl}>link</a> // userUrl = "javascript:alert(1)"✅ Fixed — allow only safe schemes:
const safe = /^https?:\/\//.test(userUrl) ? userUrl : "#";
<a href={safe}>link</a>❌ Vulnerable — deep-merge of untrusted input:
function merge(t, s) {
for (const k in s) {
if (typeof s[k] === "object") merge(t[k] ??= {}, s[k]);
else t[k] = s[k]; // __proto__ pollutes Object.prototype
}
}✅ Fixed — block dangerous keys (or Object.create(null) / Map):
const BLOCKED = new Set(["__proto__", "constructor", "prototype"]);
function merge(t, s) {
for (const k of Object.keys(s)) {
if (BLOCKED.has(k)) continue;
if (s[k] && typeof s[k] === "object") merge(t[k] ??= {}, s[k]);
else t[k] = s[k];
}
}❌ Vulnerable:
const obj = require("node-serialize").unserialize(req.body); // RCE✅ Fixed:
const obj = JSON.parse(req.body); // data only❌ Vulnerable:
const stripe = require("stripe")("sk_live_51H8...redacted");✅ Fixed:
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);Ensure
.envis git-ignored and secrets aren't inlined into client bundles.
❌ Vulnerable:
const hash = crypto.createHash("md5").update(pw).digest("hex");✅ Fixed — bcrypt/argon2:
const bcrypt = require("bcrypt");
const hash = await bcrypt.hash(pw, 12);
const ok = await bcrypt.compare(pw, hash);❌ Vulnerable:
const token = Math.random().toString(36).slice(2); // predictable✅ Fixed — CSPRNG:
const token = require("crypto").randomBytes(32).toString("hex");❌ Vulnerable:
if (provided === expected) { /* ... */ }✅ Fixed:
const crypto = require("crypto");
const a = Buffer.from(provided), b = Buffer.from(expected);
if (a.length === b.length && crypto.timingSafeEqual(a, b)) { /* ... */ }❌ Vulnerable:
app.get("/api/orders/:id", async (req, res) => {
res.json(await Order.findById(req.params.id)); // any user, any order
});✅ Fixed — verify ownership:
app.get("/api/orders/:id", requireAuth, async (req, res) => {
const o = await Order.findById(req.params.id);
if (!o || String(o.userId) !== req.user.id) return res.sendStatus(403);
res.json(o);
});❌ Vulnerable:
res.sendFile(path.join(BASE, req.query.name)); // ../../etc/passwd✅ Fixed — resolve and confine:
const full = path.resolve(BASE, req.query.name);
if (!full.startsWith(path.resolve(BASE) + path.sep)) return res.sendStatus(400);
res.sendFile(full);❌ Vulnerable:
const resp = await fetch(req.query.url); // user controls destination✅ Fixed — allowlist + block internal IPs:
import { lookup } from "node:dns/promises";
import ipaddr from "ipaddr.js";
const ALLOWED = new Set(["api.partner.com"]);
async function safeFetch(raw) {
const url = new URL(raw);
if (!ALLOWED.has(url.hostname)) throw new Error("host not allowed");
const { address } = await lookup(url.hostname);
if (ipaddr.parse(address).range() !== "unicast") throw new Error("internal blocked");
return fetch(url, { redirect: "manual", signal: AbortSignal.timeout(5000) });
}❌ Vulnerable:
res.redirect(req.query.next); // next=https://evil.tld✅ Fixed — relative paths only:
const next = req.query.next || "/";
res.redirect(next.startsWith("/") && !next.startsWith("//") ? next : "/");❌ Vulnerable:
const payload = jwt.decode(token); // no signature check✅ Fixed — verify with an explicit algorithm:
const payload = jwt.verify(token, PUBLIC_KEY, { algorithms: ["RS256"] });❌ Vulnerable:
res.cookie("session", id); // no flags✅ Fixed:
res.cookie("session", id, { httpOnly: true, secure: true, sameSite: "strict", maxAge: 3600_000 });❌ Vulnerable:
app.use(cors({ origin: "*", credentials: true })); // any site + credentials✅ Fixed — explicit allowlist:
app.use(cors({ origin: ["https://app.example.com"], credentials: true }));❌ Vulnerable:
if (/^(\w+\s?)*$/.test(userInput)) { /* ... */ } // hangs the event loop✅ Fixed — bounded, linear pattern + length cap:
if (userInput.length <= 256 && /^[\w ]+$/.test(userInput)) { /* ... */ }❌ Vulnerable:
try { await verifyWebhookSignature(req); } catch (e) { /* ignore */ }
processPayment(req.body); // forged webhooks pass through✅ Fixed — deny + log on failure:
try { await verifyWebhookSignature(req); }
catch (e) { logger.warn("bad webhook sig", { err: e.message }); return res.sendStatus(400); }
processPayment(req.body);❌ Vulnerable — no CSP/HSTS/etc.
✅ Fixed:
const helmet = require("helmet");
app.use(helmet()); // sane defaults; tune CSP per app❌ Vulnerable:
app.get("/files/:id", async (req, res) => {
const doc = await Doc.findById(req.params.id); // A01: IDOR
const html = `<h1>${doc.title}</h1>`; // A05: XSS
res.sendFile(path.join(BASE, req.query.name)); // A01: path traversal
console.log("served", doc.id, "key", API_KEY); // A09: secret in logs
});✅ Fixed:
app.get("/files/:id", requireAuth, async (req, res) => {
const doc = await Doc.findById(req.params.id);
if (!doc || String(doc.userId) !== req.user.id) return res.sendStatus(403); // A01
const full = path.resolve(BASE, req.query.name || "");
if (!full.startsWith(path.resolve(BASE) + path.sep)) return res.sendStatus(400); // A01
logger.info("served doc", { id: doc.id }); // A09: no secrets
res.render("doc", { title: doc.title }); // A05: template auto-escapes
});eval,new Function,child_process.exec,innerHTML,dangerouslySetInnerHTML,node-serialize→ justify or reject.jwt.decodeused for auth (must bejwt.verify);cors({origin:"*", credentials:true}).Math.random()for tokens/secrets →crypto.randomBytes;===on tokens →timingSafeEqual.npm auditclean; lockfile committed;helmet()on; body size limits set.
- OWASP: XSS Prevention · DOM XSS Prevention · Injection Prevention · Node.js Security · Content Security Policy · Session Management
- Tools: npm audit · eslint-plugin-security · Semgrep · DOMPurify