TypeScript Security Review
Overview
This skill provides structured, comprehensive security review for TypeScript and Node.js applications. It evaluates code against OWASP Top 10, framework-specific security best practices, and production-readiness security criteria. The review produces actionable findings classified by severity (Critical, High, Medium, Low) with concrete remediation examples.
This skill delegates to the typescript-security-expert agent for deep security analysis when invoked through the agent system.
When to Use
- Performing security audits on TypeScript/Node.js codebases
- Reviewing authentication and authorization implementations (JWT, OAuth2, Passport.js)
- Checking for common vulnerabilities (XSS, injection, CSRF, path traversal)
- Validating input validation and sanitization logic
- Reviewing dependency security (npm audit, known CVEs)
- Checking secrets management and environment variable handling
- Assessing API security (rate limiting, CORS, security headers)
- Reviewing Express, NestJS, or Next.js security configurations
- Before deploying to production or after significant code changes
- Compliance checks (GDPR, HIPAA, SOC2 data handling requirements)
Instructions
Identify Scope: Determine which files and modules are under security review. Prioritize authentication, authorization, data handling, API endpoints, and configuration files. Use grep to find security-sensitive patterns (eval, exec, innerHTML, password handling, JWT operations).
Check Authentication & Authorization: Review JWT implementation (signing algorithm, expiration, refresh tokens), OAuth2/OIDC integration, session management, password hashing (bcrypt/argon2), and multi-factor authentication. Verify that all protected routes enforce authentication.
Scan for Injection Vulnerabilities: Check for SQL/NoSQL injection in database queries, command injection in exec/spawn, template injection, and LDAP injection. Verify that all user input is validated and parameterized queries are used.
Review Input Validation: Check that all API inputs are validated with Zod, Joi, or class-validator. Verify schema completeness — no missing fields, proper type constraints, length limits, and format validation. Check for validation bypass paths.
Assess XSS Prevention: Review React component output for dangerouslySetInnerHTML usage, check Content Security Policy headers, verify HTML sanitization for user-generated content, and check template rendering in server-side code.
Check Secrets Management: Scan for hardcoded credentials, API keys, and secrets in source code. Verify .env files are gitignored, environment variables are validated at startup, and secrets are accessed through proper management services.
Review Dependency Security: Run npm audit or check package-lock.json for known vulnerabilities. Identify outdated dependencies with known CVEs. Check for unnecessary dependencies that increase attack surface.
Evaluate Security Headers & Configuration: Check for helmet.js or manual security header configuration. Review CORS policy, rate limiting, HTTPS enforcement, cookie security flags (HttpOnly, Secure, SameSite), and CSP configuration.
Produce Security Report: Generate a structured report with severity-classified findings (Critical, High, Medium, Low), remediation guidance with code examples, and a security posture summary.
Examples
Example 1: JWT Security Review
// ❌ Critical: Weak JWT configuration
import jwt from 'jsonwebtoken';
const SECRET = 'mysecret123'; // Hardcoded weak secret
function generateToken(user: User) {
return jwt.sign({ id: user.id, role: user.role }, SECRET);
// Missing expiration, weak secret, no algorithm specification
}
function verifyToken(token: string) {
return jwt.verify(token, SECRET); // No algorithm restriction
}
// ✅ Secure: Proper JWT configuration
import jwt from 'jsonwebtoken';
import { randomBytes } from 'crypto';
const JWT_SECRET = process.env.JWT_SECRET;
if (!JWT_SECRET || JWT_SECRET.length < 32) {
throw new Error('JWT_SECRET must be set and at least 32 characters');
}
function generateToken(user: User): string {
return jwt.sign(
{ sub: user.id }, // Minimal claims, no sensitive data
JWT_SECRET,
{
algorithm: 'HS256',
expiresIn: '15m',
issuer: 'my-app',
audience: 'my-app-client',
}
);
}
function verifyToken(token: string): JwtPayload {
return jwt.verify(token, JWT_SECRET, {
algorithms: ['HS256'], // Restrict accepted algorithms
issuer: 'my-app',
audience: 'my-app-client',
}) as JwtPayload;
}
Example 2: SQL Injection Prevention
// ❌ Critical: SQL injection vulnerability
async function findUser(email: string) {
const result = await db.query(
`SELECT * FROM users WHERE email = '${email}'`
);
return result.rows[0];
}
// ✅ Secure: Parameterized query
async function findUser(email: string) {
const result = await db.query(
'SELECT id, name, email FROM users WHERE email = $1',
[email]
);
return result.rows[0];
}
// ✅ Secure: ORM with type-safe queries (Drizzle example)
async function findUser(email: string) {
return db.select({
id: users.id,
name: users.name,
email: users.email,
})
.from(users)
.where(eq(users.email, email))
.limit(1);
}
Example 3: Input Validation
// ❌ High: Missing input validation
app.post('/api/users', async (req, res) => {
const user = await createUser(req.body);
res.json(user);
});
// ✅ Secure: Comprehensive input validation with Zod
import { z } from 'zod';
const createUserSchema = z.object({
name: z.string().min(1).max(100).trim(),
email: z.string().email().max(254).toLowerCase(),
password: z.string()
.min(12, 'Password must be at least 12 characters')
.regex(/[A-Z]/, 'Must contain uppercase letter')
.regex(/[a-z]/, 'Must contain lowercase letter')
.regex(/[0-9]/, 'Must contain a number'),
role: z.enum(['user', 'editor']).default('user'),
});
app.post('/api/users', async (req, res) => {
const result = createUserSchema.safeParse(req.body);
if (!result.success) {
return res.status(400).json({ errors: result.error.flatten() });
}
const user = await createUser(result.data);
res.status(201).json(user);
});
Example 4: XSS Prevention
// ❌ High: XSS vulnerability through dangerouslySetInnerHTML
function Comment({ content }: { content: string }) {
return <div dangerouslySetInnerHTML={{ __html: content }} />;
}
// ✅ Secure: Sanitize HTML before rendering
import DOMPurify from 'isomorphic-dompurify';
function Comment({ content }: { content: string }) {
const sanitized = DOMPurify.sanitize(content, {
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p', 'br'],
ALLOWED_ATTR: ['href', 'target', 'rel'],
});
return <div dangerouslySetInnerHTML={{ __html: sanitized }} />;
}
// ✅ Better: Use a markdown renderer instead of raw HTML
import ReactMarkdown from 'react-markdown';
function Comment({ content }: { content: string }) {
return <ReactMarkdown>{content}</ReactMarkdown>;
}
Example 5: Security Headers and Configuration
// ❌ Medium: Missing security headers and permissive CORS
const app = express();
app.use(cors()); // Allows all origins
// ✅ Secure: Comprehensive security configuration
import helmet from 'helmet';
import cors from 'cors';
import rateLimit from 'express-rate-limit';
const app = express();
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", 'data:', 'https:'],
},
},
hsts: { maxAge: 31536000, includeSubDomains: true, preload: true },
}));
app.use(cors({
origin: process.env.ALLOWED_ORIGINS?.split(',') ?? [],
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE'],
}));
app.use(rateLimit({
windowMs: 15 * 60 * 1000,
max: 100,
standardHeaders: true,
legacyHeaders: false,
}));
Review Output Format
Structure all security review findings as follows:
1. Security Posture Summary
Overall security assessment score (1-10) with key observations and risk level.
2. Critical Vulnerabilities (Immediate Action)
Issues that can be exploited to compromise the system, steal data, or cause unauthorized access.
3. High Priority (Address Within 30 Days)
Security misconfigurations, missing protections, or vulnerabilities requiring near-term remediation.
4. Medium Priority (Address Within 90 Days)
Issues that reduce security posture but have mitigating factors or limited exploitability.
5. Low Priority (Next Cycle)
Security improvements, hardening recommendations, and defense-in-depth enhancements.
6. Positive Security Observations
Well-implemented security patterns and practices to acknowledge.
7. Remediation Roadmap
Prioritized action items with code examples for the most critical fixes.
Best Practices
- Validate all inputs at the API boundary — never trust client-side validation alone
- Use parameterized queries or ORMs — never concatenate user input into queries
- Store secrets in environment variables or secret managers — never in source code
- Apply the principle of least privilege for database accounts, API keys, and IAM roles
- Enable security headers (helmet.js) and restrict CORS to known origins
- Implement rate limiting on all public-facing endpoints
- Hash passwords with bcrypt or argon2 — never use MD5/SHA for passwords
- Set cookie flags:
HttpOnly, Secure, SameSite=Strict
- Use
npm audit in CI pipelines to catch dependency vulnerabilities
- Log security events (failed logins, permission denials) without logging sensitive data
Constraints and Warnings
- Security review is not a substitute for professional penetration testing
- Focus on code-level vulnerabilities — infrastructure security is out of scope
- Respect the project's framework — provide framework-specific remediation guidance
- Do not log, print, or expose discovered secrets — report their location only
- Dependency vulnerabilities should be assessed for actual exploitability, not just presence
- Security recommendations must be practical — consider implementation effort vs risk reduction
References
See the references/ directory for detailed security documentation:
references/owasp-typescript.md — OWASP Top 10 mapped to TypeScript/Node.js patterns
references/common-vulnerabilities.md — Common vulnerability patterns and remediation
references/dependency-security.md — Dependency scanning and supply chain security guide
1---2name: typescript-security-review3description: Provides comprehensive security review capability for TypeScript and Node.js applications, validates code against XSS, injection, CSRF, JWT/OAuth2 flaws, dependency CVEs, and secrets exposure. Use when performing security audits, before deployment, reviewing authentication/authorization implementations, or ensuring OWASP compliance for Express, NestJS, and Next.js. Triggers on "security review", "check for security issues", "TypeScript security audit".4allowed-tools: Read, Edit, Grep, Glob, Bash5metadata:6 source: https://skillmd.com/skills/levalencia/typescript-security-review7---89# TypeScript Security Review1011## Overview1213This skill provides structured, comprehensive security review for TypeScript and Node.js applications. It evaluates code against OWASP Top 10, framework-specific security best practices, and production-readiness security criteria. The review produces actionable findings classified by severity (Critical, High, Medium, Low) with concrete remediation examples.1415This skill delegates to the `typescript-security-expert` agent for deep security analysis when invoked through the agent system.1617## When to Use1819- Performing security audits on TypeScript/Node.js codebases20- Reviewing authentication and authorization implementations (JWT, OAuth2, Passport.js)21- Checking for common vulnerabilities (XSS, injection, CSRF, path traversal)22- Validating input validation and sanitization logic23- Reviewing dependency security (npm audit, known CVEs)24- Checking secrets management and environment variable handling25- Assessing API security (rate limiting, CORS, security headers)26- Reviewing Express, NestJS, or Next.js security configurations27- Before deploying to production or after significant code changes28- Compliance checks (GDPR, HIPAA, SOC2 data handling requirements)2930## Instructions31321. **Identify Scope**: Determine which files and modules are under security review. Prioritize authentication, authorization, data handling, API endpoints, and configuration files. Use `grep` to find security-sensitive patterns (`eval`, `exec`, `innerHTML`, password handling, JWT operations).33342. **Check Authentication & Authorization**: Review JWT implementation (signing algorithm, expiration, refresh tokens), OAuth2/OIDC integration, session management, password hashing (bcrypt/argon2), and multi-factor authentication. Verify that all protected routes enforce authentication.35363. **Scan for Injection Vulnerabilities**: Check for SQL/NoSQL injection in database queries, command injection in `exec`/`spawn`, template injection, and LDAP injection. Verify that all user input is validated and parameterized queries are used.37384. **Review Input Validation**: Check that all API inputs are validated with Zod, Joi, or class-validator. Verify schema completeness — no missing fields, proper type constraints, length limits, and format validation. Check for validation bypass paths.39405. **Assess XSS Prevention**: Review React component output for `dangerouslySetInnerHTML` usage, check Content Security Policy headers, verify HTML sanitization for user-generated content, and check template rendering in server-side code.41426. **Check Secrets Management**: Scan for hardcoded credentials, API keys, and secrets in source code. Verify `.env` files are gitignored, environment variables are validated at startup, and secrets are accessed through proper management services.43447. **Review Dependency Security**: Run `npm audit` or check `package-lock.json` for known vulnerabilities. Identify outdated dependencies with known CVEs. Check for unnecessary dependencies that increase attack surface.45468. **Evaluate Security Headers & Configuration**: Check for helmet.js or manual security header configuration. Review CORS policy, rate limiting, HTTPS enforcement, cookie security flags (HttpOnly, Secure, SameSite), and CSP configuration.47489. **Produce Security Report**: Generate a structured report with severity-classified findings (Critical, High, Medium, Low), remediation guidance with code examples, and a security posture summary.4950## Examples5152### Example 1: JWT Security Review5354```typescript55// ❌ Critical: Weak JWT configuration56import jwt from 'jsonwebtoken';5758const SECRET = 'mysecret123'; // Hardcoded weak secret5960function generateToken(user: User) {61 return jwt.sign({ id: user.id, role: user.role }, SECRET);62 // Missing expiration, weak secret, no algorithm specification63}6465function verifyToken(token: string) {66 return jwt.verify(token, SECRET); // No algorithm restriction67}6869// ✅ Secure: Proper JWT configuration70import jwt from 'jsonwebtoken';71import { randomBytes } from 'crypto';7273const JWT_SECRET = process.env.JWT_SECRET;74if (!JWT_SECRET || JWT_SECRET.length < 32) {75 throw new Error('JWT_SECRET must be set and at least 32 characters');76}7778function generateToken(user: User): string {79 return jwt.sign(80 { sub: user.id }, // Minimal claims, no sensitive data81 JWT_SECRET,82 {83 algorithm: 'HS256',84 expiresIn: '15m',85 issuer: 'my-app',86 audience: 'my-app-client',87 }88 );89}9091function verifyToken(token: string): JwtPayload {92 return jwt.verify(token, JWT_SECRET, {93 algorithms: ['HS256'], // Restrict accepted algorithms94 issuer: 'my-app',95 audience: 'my-app-client',96 }) as JwtPayload;97}98```99100### Example 2: SQL Injection Prevention101102```typescript103// ❌ Critical: SQL injection vulnerability104async function findUser(email: string) {105 const result = await db.query(106 `SELECT * FROM users WHERE email = '${email}'`107 );108 return result.rows[0];109}110111// ✅ Secure: Parameterized query112async function findUser(email: string) {113 const result = await db.query(114 'SELECT id, name, email FROM users WHERE email = $1',115 [email]116 );117 return result.rows[0];118}119120// ✅ Secure: ORM with type-safe queries (Drizzle example)121async function findUser(email: string) {122 return db.select({123 id: users.id,124 name: users.name,125 email: users.email,126 })127 .from(users)128 .where(eq(users.email, email))129 .limit(1);130}131```132133### Example 3: Input Validation134135```typescript136// ❌ High: Missing input validation137app.post('/api/users', async (req, res) => {138 const user = await createUser(req.body);139 res.json(user);140});141142// ✅ Secure: Comprehensive input validation with Zod143import { z } from 'zod';144145const createUserSchema = z.object({146 name: z.string().min(1).max(100).trim(),147 email: z.string().email().max(254).toLowerCase(),148 password: z.string()149 .min(12, 'Password must be at least 12 characters')150 .regex(/[A-Z]/, 'Must contain uppercase letter')151 .regex(/[a-z]/, 'Must contain lowercase letter')152 .regex(/[0-9]/, 'Must contain a number'),153 role: z.enum(['user', 'editor']).default('user'),154});155156app.post('/api/users', async (req, res) => {157 const result = createUserSchema.safeParse(req.body);158 if (!result.success) {159 return res.status(400).json({ errors: result.error.flatten() });160 }161 const user = await createUser(result.data);162 res.status(201).json(user);163});164```165166### Example 4: XSS Prevention167168```tsx169// ❌ High: XSS vulnerability through dangerouslySetInnerHTML170function Comment({ content }: { content: string }) {171 return <div dangerouslySetInnerHTML={{ __html: content }} />;172}173174// ✅ Secure: Sanitize HTML before rendering175import DOMPurify from 'isomorphic-dompurify';176177function Comment({ content }: { content: string }) {178 const sanitized = DOMPurify.sanitize(content, {179 ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p', 'br'],180 ALLOWED_ATTR: ['href', 'target', 'rel'],181 });182 return <div dangerouslySetInnerHTML={{ __html: sanitized }} />;183}184185// ✅ Better: Use a markdown renderer instead of raw HTML186import ReactMarkdown from 'react-markdown';187188function Comment({ content }: { content: string }) {189 return <ReactMarkdown>{content}</ReactMarkdown>;190}191```192193### Example 5: Security Headers and Configuration194195```typescript196// ❌ Medium: Missing security headers and permissive CORS197const app = express();198app.use(cors()); // Allows all origins199200// ✅ Secure: Comprehensive security configuration201import helmet from 'helmet';202import cors from 'cors';203import rateLimit from 'express-rate-limit';204205const app = express();206207app.use(helmet({208 contentSecurityPolicy: {209 directives: {210 defaultSrc: ["'self'"],211 scriptSrc: ["'self'"],212 styleSrc: ["'self'", "'unsafe-inline'"],213 imgSrc: ["'self'", 'data:', 'https:'],214 },215 },216 hsts: { maxAge: 31536000, includeSubDomains: true, preload: true },217}));218219app.use(cors({220 origin: process.env.ALLOWED_ORIGINS?.split(',') ?? [],221 credentials: true,222 methods: ['GET', 'POST', 'PUT', 'DELETE'],223}));224225app.use(rateLimit({226 windowMs: 15 * 60 * 1000,227 max: 100,228 standardHeaders: true,229 legacyHeaders: false,230}));231```232233## Review Output Format234235Structure all security review findings as follows:236237### 1. Security Posture Summary238Overall security assessment score (1-10) with key observations and risk level.239240### 2. Critical Vulnerabilities (Immediate Action)241Issues that can be exploited to compromise the system, steal data, or cause unauthorized access.242243### 3. High Priority (Address Within 30 Days)244Security misconfigurations, missing protections, or vulnerabilities requiring near-term remediation.245246### 4. Medium Priority (Address Within 90 Days)247Issues that reduce security posture but have mitigating factors or limited exploitability.248249### 5. Low Priority (Next Cycle)250Security improvements, hardening recommendations, and defense-in-depth enhancements.251252### 6. Positive Security Observations253Well-implemented security patterns and practices to acknowledge.254255### 7. Remediation Roadmap256Prioritized action items with code examples for the most critical fixes.257258## Best Practices259260- Validate all inputs at the API boundary — never trust client-side validation alone261- Use parameterized queries or ORMs — never concatenate user input into queries262- Store secrets in environment variables or secret managers — never in source code263- Apply the principle of least privilege for database accounts, API keys, and IAM roles264- Enable security headers (helmet.js) and restrict CORS to known origins265- Implement rate limiting on all public-facing endpoints266- Hash passwords with bcrypt or argon2 — never use MD5/SHA for passwords267- Set cookie flags: `HttpOnly`, `Secure`, `SameSite=Strict`268- Use `npm audit` in CI pipelines to catch dependency vulnerabilities269- Log security events (failed logins, permission denials) without logging sensitive data270271## Constraints and Warnings272273- Security review is not a substitute for professional penetration testing274- Focus on code-level vulnerabilities — infrastructure security is out of scope275- Respect the project's framework — provide framework-specific remediation guidance276- Do not log, print, or expose discovered secrets — report their location only277- Dependency vulnerabilities should be assessed for actual exploitability, not just presence278- Security recommendations must be practical — consider implementation effort vs risk reduction279280## References281282See the `references/` directory for detailed security documentation:283- `references/owasp-typescript.md` — OWASP Top 10 mapped to TypeScript/Node.js patterns284- `references/common-vulnerabilities.md` — Common vulnerability patterns and remediation285- `references/dependency-security.md` — Dependency scanning and supply chain security guide