node-typescript-security-pitfalls
Use when reviewing Node.js or TypeScript server code - Express/Fastify/Nest handlers, Next.js server actions and route handlers, child_process, ORM raw queries, prototype pollution, template engines, JWT and outbound HTTP clients
- License 许可
- Apache-2.0
- 最近更新
- 2026-11-15
- Stars
- ★ 122
- Forks
- 18
01 前言 Front Matter
- name
- node-typescript-security-pitfalls
- source
- original; informed by trailofbits/skills (CC BY-SA 4.0, ideas only, own wording) and anthropics/claude-code security-guidance plugin (ideas only); Node.js, Next.js and library security advisories cited, not reproduced
- category
- security
- tech_stack
- TypeScript & Node
- description
- Use when reviewing Node.js or TypeScript server code - Express/Fastify/Nest handlers, Next.js server actions and route handlers, child_process, ORM raw queries, prototype pollution, template engines, JWT and outbound HTTP clients
03 SKILL.md 正文
Node and TypeScript Security Pitfalls
Overview
TypeScript types vanish at runtime: req.query.id: string can arrive as an array or an object. Most Node findings come from that gap, from exec with a template string, from raw-query escape hatches in otherwise safe ORMs, and — in Next.js — from forgetting that a server action is a public endpoint.
1. Runtime Types Are Not Declared Types
// ❌ ?id[$ne]=x or ?id[]=a&id[]=b gives an object or array, not a string
const doc = await Orders.findOne({ id: req.query.id as string, owner: user.id });
// ✅ validate at the boundary (zod/valibot/class-validator) and coerce
const { id } = z.object({ id: z.string().uuid() }).parse(req.query);
Length, includes and equality checks on an unvalidated query value can be bypassed the same way.
2. child_process (CWE-78, CWE-88)
// ❌ shell
exec(`convert ${file} out.png`);
spawn("git", ["clone", url], { shell: true });
// ✅ no shell, end of options
execFile("git", ["clone", "--", url, dir]);
Also check the env option for request-controlled keys (NODE_OPTIONS=--require …).
3. Raw Queries in Safe ORMs (CWE-89)
| Library | Unsafe | Safe |
|---|---|---|
| Prisma | $queryRawUnsafe, $executeRawUnsafe, Prisma.raw() |
$queryRaw tagged template, model methods |
| TypeORM | query("… " + x), .where(\id = ${id}`)` |
.where("id = :id", { id }) |
| Sequelize | sequelize.query(\… ${x}`), literal(x)` |
replacements / bind |
| Knex | knex.raw(\… ${x}`)` |
knex.raw("… ?", [x]) |
| Drizzle | sql.raw(x) |
sql\… ${x}`` |
Mongo/Mongoose: operator injection from JSON bodies (section 1), $where.
4. Next.js Server Actions and Route Handlers
- Every exported async function in a
"use server"file is a callable POST endpoint, whether or not a page renders a form for it. Each must authenticate and authorize inside the action.
// ❌ the page is admin-only, the action is not
"use server";
export async function deleteUser(id: string) { await db.user.delete({ where: { id } }); }
// ✅
export async function deleteUser(id: string) {
const session = await auth();
if (session?.user.role !== "admin") throw new Error("forbidden");
await db.user.delete({ where: { id } });
}
- Authorization done only in
middleware.ts: middleware matchers miss paths, and Next.js < 15.2.3 / 14.2.25 / 13.5.9 / 12.3.5 let anx-middleware-subrequestheader skip middleware entirely (CVE-2025-29927). Check in the handler or data layer too. - Server components passing whole records to client components serialise every field into the page payload.
NEXT_PUBLIC_*variables are shipped to the browser.
5. Prototype Pollution (CWE-1321) — high confidence only
Report only with a gadget: a recursive merge/set of user JSON (lodash.merge, _.set with user paths, hand-written deep merge) where __proto__ or constructor.prototype reaches a property later read for an auth decision, a child_process option (shell, env), or a template option.
// ❌ deepMerge(defaults, req.body) with {"__proto__": {"isAdmin": true}}
// ✅ validate the body against a schema first; build lookups with Object.create(null) or Map
6. Templates and Rendering
- EJS
<%- user %>, Handlebars{{{ user }}}, Pug!= user→ XSS. res.render(view, req.query)or{ ...req.body }as locals: template options ride along (EJSoutputFunctionName/escapeFunction, CVE-2022-29078 class) → RCE.- User-controlled template source compiled with
Handlebars.compile,pug.compile,ejs.render.
7. Sandboxes and Code Loading
vm/vm.runInNewContextis not a security boundary;vm2is discontinued after sandbox escapes. Running user code in either is CRITICAL when reachable.eval,new Function,require(userPath), dynamicimport(userPath).js-yaml3.xload()instantiates JavaScript types (!!js/function) —safeLoador js-yaml 4'sload.node-serializeunserializeon input.
8. HTTP Clients and Tokens
- axios: an absolute URL passed where a path was expected overrides
baseURLand sends the configured auth headers to that host (CVE-2025-27152 class) — validate that user-supplied paths are relative. - Redirect following by default in axios/got/node-fetch on user URLs (ssrf-and-url-allowlists).
jsonwebtoken:jwt.decodedoes not verify;jwt.verifywithoutalgorithms.crypto.timingSafeEqualfor MACs (throws on length mismatch — compare lengths first);Math.randomfor tokens.
9. Express and Fastify Specifics
app.set("trust proxy", true)trusts every hop'sX-Forwarded-For.express.static(".")orexpress.static(__dirname)serves source and.env.res.sendFile(path.join(dir, name))instead ofres.sendFile(name, { root: dir }).- Multer
file.originalnameused as the stored path. - A route registered before
app.use(authMiddleware)runs without it.
Common Mistakes
- Reporting
$queryRawtagged templates, TypeORM parameters orexecFilearrays as injection. - Reporting prototype pollution with no gadget.
- Reporting
JSON.parseas unsafe deserialization. - Missing that a server action is reachable without the page that renders it.
Red Flags
- Template literals inside
exec(,query(,raw(,$queryRawUnsafe(. shell: true."use server"files with exported mutations and noauth()call inside them.as stringonreq.query/req.paramsvalues used in a query.merge(,defaultsDeep(,set(fed withreq.body.
References (names and links only)
Node.js security best practices · Next.js data security · CVE-2025-29927, CVE-2025-27152, CVE-2022-29078 · CWE-78, 89, 1321 · OWASP Top 10:2025
04 同仓库更多 Skills
visual-craft
暂无简介
ux-copy
Use when you write any words a user reads in a mockup or a hand-off - content language and voice, buttons, labels, errors, empty states, confirmations, numbers and dates, and the longest-string check
screen-mockup-html
Use when you draw screens as the design task's HTML mockup - ONE canvas document holding every screen and every variant side by side, the sanitizer-safe recipe, phone and wide frames, the states grid, static control states, and the loopback self-check with screenshots at 375, 768 and 1440 attached to the task
performance-awareness
How the performance score moves for your role. Use when the score context shows a declining trend, or before handing off work you have not self-checked against every criterion.
design-variants
Use when a screen design needs variants - how many, variants as side-by-side rows on the one canvas, what makes two variants genuinely different, recommending one, how the human's choice is read, and narrowing to the chosen one in revision
design-system-authoring
Use when you derive, change or extend a design system - where tokens live per stack, the DTCG token tree, role-based names for both themes, base vs layer vs drift, the DESIGN.md section order, the inventory format, the contrast check and the lint every proposal returns