SAASMENT

Security skill · Find and fix

Secure review: JavaScript and TypeScript.

Review JavaScript and TypeScript code (Node.js services, Next.js and other web frameworks, browser code) for language-specific security flaws such as prototype pollution, unsafe dynamic evaluation, command and path injection, DOM sinks, weak type assumptions on parsed input, regular-expression denial of service, and secrets in client bundles, then fix and verify with tests. Use when auditing or reviewing a JS or TS codebase or pull request.

Download .zipInstall via MCPFind and fixMIT
  • Code review

Facts

Category
Find and fix
License
MIT
Tags
  • Code review
Version
1.0.1
Last updated
2026-12-02
Folder
secure-review-javascript-typescript/
MCP resource
skill://secure-review-javascript-typescript/SKILL.md
Files
  • SKILL.md
  • LICENSE
  • references/js-ts-patterns.md
Standards

Original Saasment content. Saasment is in early access; this skill does not require joining it.

Install via MCP or as files

Connect your client to https://www.saasment.com/api/mcp (see client setup) and call get_skill:

{
  "name": "get_skill",
  "arguments": {
    "slug": "secure-review-javascript-typescript"
  }
}

Or download the .zip and unpack it into your agent's skills directory:

Terminal, from your project root (user-level: ~/.cursor/skills)

mkdir -p .cursor/skills
curl -fsSL https://www.saasment.com/ai-security/skills/secure-review-javascript-typescript/download.zip -o /tmp/secure-review-javascript-typescript.zip
unzip -o /tmp/secure-review-javascript-typescript.zip -d .cursor/skills
# result: .cursor/skills/secure-review-javascript-typescript/SKILL.md

Review SKILL.md before enabling a skill. Skills are instructions your agent will follow.

SKILL.md

---
name: secure-review-javascript-typescript
description: Review JavaScript and TypeScript code (Node.js services, Next.js and other web frameworks, browser code) for language-specific security flaws such as prototype pollution, unsafe dynamic evaluation, command and path injection, DOM sinks, weak type assumptions on parsed input, regular-expression denial of service, and secrets in client bundles, then fix and verify with tests. Use when auditing or reviewing a JS or TS codebase or pull request.
license: MIT
metadata:
  author: Saasment
  version: "1.0.1"
  category: both
  tags: "code-review"
---

# Secure review: JavaScript and TypeScript (find and fix)

License: MIT. Copyright (c) 2026 Saasment. Source: https://www.saasment.com/ai-security/skills/secure-review-javascript-typescript

JavaScript has a few traits that create their own bug classes: objects are open and inherit from a shared prototype, values change type silently, strings can be turned into code, and the same codebase often runs on a server and in a browser. TypeScript types disappear at runtime, so data from outside the program is unchecked unless you check it. This skill covers the language-specific pass; run it together with `secure-code-review-checklist`.

## When to use

- You audit a Node.js, Next.js, Express, Fastify, NestJS, React, or other JS or TS codebase.
- A pull request adds routes, parsing code, build config, or client-side rendering.
- A scanner flagged a JS or TS finding and you need to confirm it.

## Safe by default

- Review only code you own or are authorized to review. Run tests and probes only in a local or test environment with synthetic data.
- Do not run `npm install` scripts or untrusted package code on a machine with credentials. Prefer `npm ci --ignore-scripts` for a first look at an unfamiliar project.
- Keep probes harmless: use markers such as a unique harmless string, not payloads that change state, exfiltrate data, or run commands.
- Never paste real tokens or `.env` contents into prompts, tickets, or reports.

## Procedure

1. **Inventory.** Identify runtime (Node version, edge runtime, browser), framework, package manager, server entry points, and which code ships to the client. Note `tsconfig` strictness and whether input is validated by a schema library.
2. **Find unchecked boundaries.** In TypeScript, every `as SomeType`, `any`, and `JSON.parse(...)` on external data is an unchecked boundary. Request bodies, query strings, cookies, headers, webhook payloads, and `process.env` need runtime validation (see `input-validation-deserialization-review`).
3. **Search the risky APIs** (patterns in `references/js-ts-patterns.md`):
   - Code from strings: `eval`, `new Function`, `vm` with untrusted code, `setTimeout` with a string, dynamic `import()` or `require()` with a user-influenced path.
   - Processes: `child_process.exec` or `spawn` with `shell: true` and interpolated input.
   - Paths and files: user input in `fs` paths, `path.join` without checking the result stays inside the base directory, archive extraction.
   - Prototype pollution: recursive merge, `Object.assign` or spread from parsed input into shared objects, `obj[key][key2] = value` with user keys (`__proto__`, `constructor`, `prototype`).
   - Browser sinks: `innerHTML`, `outerHTML`, `document.write`, `dangerouslySetInnerHTML`, `href` or `src` built from input, `postMessage` handlers without origin checks (see `xss-find-and-fix`).
   - Regular expressions: nested quantifiers on user input that can run for a very long time.
   - Randomness and comparison: `Math.random()` for tokens, `===` on secrets and signatures instead of a constant-time compare.
   - SSRF and redirects: `fetch` or `axios` with a user-influenced URL (see `ssrf-find-and-fix`).
4. **Check server and client boundaries.** In Next.js and similar frameworks, confirm server-only secrets are not imported by client components, that only intended variables carry the public prefix, and that server actions and route handlers authorize every call (see `authz-idor-review`).
5. **Check the supply chain.** Lockfile committed, install scripts reviewed for new packages, no wildcard versions on critical packages, and `npm audit` results triaged (see `dependency-cve-triage-and-patch`).
6. **Fix** with the smallest shared change: schema validation at the boundary, `Object.create(null)` or `Map` for key-value data from users, allowlisted keys when merging, `execFile` with an argument array, resolved-path prefix checks, `crypto.randomUUID()` or `crypto.randomBytes()` for tokens, `crypto.timingSafeEqual` for comparisons, and framework-default escaping instead of raw HTML.
7. **Add regression tests** for each fixed class, including the hostile input.

## Verification

- Confirm prototype pollution in a test: pass a harmless payload with a `__proto__` key through the code path and assert that `({}).polluted` is still `undefined` after the call. Before the fix the assertion fails; after the fix it passes.
- Confirm command or path injection with a harmless marker (for example a file name containing `;` or `..`) and assert the call rejects it or treats it as literal text.
- Confirm validation: send a wrong type (array, object, number as string, very long string) to each fixed boundary and assert a 4xx response, not a crash or silent coercion.
- Run `tsc --noEmit`, the linter (for example ESLint security rules), the test suite, and `npm audit` after the change and compare with the baseline.
- Build the client bundle and search it for secret names and server-only module names to confirm nothing leaked.

## Reporting

Table: id, file and line, bug class, reachable by whom, fix, regression test. List unchecked boundaries you could not convert in this pass.

## References

- OWASP Node.js Security Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Nodejs_Security_Cheat_Sheet.html
- OWASP Prototype Pollution Prevention Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Prototype_Pollution_Prevention_Cheat_Sheet.html
- Node.js security guide (official): https://nodejs.org/learn/getting-started/security-best-practices
- CWE-1321 (prototype pollution): https://cwe.mitre.org/data/definitions/1321.html
- Companion skills: `secure-code-review-checklist`, `xss-find-and-fix`, `input-validation-deserialization-review`.

Helper files

LICENSE
MIT License

Copyright (c) 2026 Saasment

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
references/js-ts-patterns.md
# JavaScript and TypeScript risky patterns

License: MIT. Copyright (c) 2026 Saasment.

These are search leads. Confirm each hit by reading the code and checking whether untrusted data can reach it.

## Search commands

```bash
# Code from strings and dynamic loading
rg -n '\beval\(|new Function\(|vm\.(runIn|Script)|require\(\s*[a-zA-Z_]' --glob '*.{js,ts,tsx,mjs}'

# Processes
rg -n 'child_process|execSync|exec\(|spawn\(.*shell' --glob '*.{js,ts,mjs}'

# Browser sinks
rg -n 'innerHTML|outerHTML|insertAdjacentHTML|document\.write|dangerouslySetInnerHTML' --glob '*.{js,ts,tsx}'

# Unchecked casts and parsed input
rg -n 'JSON\.parse\(|as any|: any\b| as [A-Z][A-Za-z]+' --glob '*.{ts,tsx}'

# Weak randomness near tokens
rg -n 'Math\.random' --glob '*.{js,ts,tsx}'

# Secrets reaching the client (Next.js style public prefix)
rg -n 'NEXT_PUBLIC_' --glob '*.{js,ts,tsx,env*}'
```

## Prototype pollution

```ts
// Risky: recursive merge copies keys such as "__proto__" from parsed input
function merge(target: any, source: any) {
  for (const key in source) {
    if (typeof source[key] === "object") merge((target[key] ??= {}), source[key]);
    else target[key] = source[key];
  }
}

// Safer: skip dangerous keys and write to objects without a prototype
const BLOCKED = new Set(["__proto__", "constructor", "prototype"]);
function safeMerge(target: Record<string, unknown>, source: Record<string, unknown>) {
  for (const key of Object.keys(source)) {
    if (BLOCKED.has(key)) continue;
    const value = source[key];
    if (value && typeof value === "object" && !Array.isArray(value)) {
      const child = (target[key] ??= Object.create(null)) as Record<string, unknown>;
      safeMerge(child, value as Record<string, unknown>);
    } else {
      target[key] = value;
    }
  }
}
```

## Commands and paths

```ts
// Risky: shell interprets the interpolated value
exec(`convert ${userFile} out.png`);

// Safer: no shell, arguments passed as an array, input validated first
execFile("convert", [validatedFile, "out.png"]);

// Risky: path escapes the base directory with ../
fs.readFile(path.join(BASE, req.query.name));

// Safer: resolve, then check the prefix
const full = path.resolve(BASE, name);
if (!full.startsWith(path.resolve(BASE) + path.sep)) throw new Error("bad path");
```

## Types are not validation

```ts
// Risky: the cast says nothing about the actual data
const body = (await req.json()) as { amount: number };

// Safer: validate at runtime (any schema library works), then use the parsed value
const parsed = schema.parse(await req.json());
```

## Tokens and comparisons

```ts
// Risky
const token = Math.random().toString(36).slice(2);
if (provided === expected) { /* ... */ }

// Safer
import { randomBytes, timingSafeEqual } from "node:crypto";
const token = randomBytes(32).toString("base64url");
const a = Buffer.from(provided);
const b = Buffer.from(expected);
const ok = a.length === b.length && timingSafeEqual(a, b);
```

## Regular expression denial of service

Look for patterns such as `(a+)+`, `(.*)*`, or alternations with overlapping branches applied to user input. Fixes: bound input length before matching, rewrite the pattern without nested quantifiers, or use a linear-time matching library.

Related

Companion skills

Questions

How do I install the Secure review: JavaScript and TypeScript skill?

Download https://www.saasment.com/ai-security/skills/secure-review-javascript-typescript/download.zip and unzip it into your agent's skills directory (for example .cursor/skills, .claude/skills, .agents/skills, or .github/skills) so that secure-review-javascript-typescript/SKILL.md exists. Or connect to https://www.saasment.com/api/mcp and call the get_skill tool with the slug secure-review-javascript-typescript.

What license is the Secure review: JavaScript and TypeScript skill under?

It is original Saasment content under the MIT license, stated in the SKILL.md frontmatter and in the LICENSE file in the skill folder.

Is it safe to run this skill?

A skill is a set of instructions your agent follows, so read SKILL.md first. It tells the agent to test only systems you own or are authorized to test, to use test environments and synthetic data, and to avoid destructive probes. Downloading it does not run any code on your machine.

← All security skills

Try the platform.

Open the demo workspace with mock data. No login. Register from the banner when you want early access. No security team. No call.

Try the platform