typescript-security-review
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTypeScript Security Review
TypeScript安全审查
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 agent for deep security analysis when invoked through the agent system.
typescript-security-expert本Skill为TypeScript和Node.js应用提供结构化、全面的安全审查。它依据OWASP Top 10、框架特定安全最佳实践以及生产就绪安全标准评估代码。审查会生成可执行的发现结果,按严重程度(Critical、High、Medium、Low)分类,并附带具体的修复示例。
当通过代理系统调用时,本Skill会委托代理进行深度安全分析。
typescript-security-expertWhen 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)
- 对TypeScript/Node.js代码库执行安全审计
- 审核身份验证与授权实现(JWT、OAuth2、Passport.js)
- 检查常见漏洞(XSS、注入、CSRF、路径遍历)
- 验证输入验证与清理逻辑
- 审查依赖项安全性(npm audit、已知CVE)
- 检查密钥管理与环境变量处理
- 评估API安全性(速率限制、CORS、安全标头)
- 审查Express、NestJS或Next.js的安全配置
- 生产环境部署前或重大代码变更后
- 合规性检查(GDPR、HIPAA、SOC2数据处理要求)
Instructions
操作步骤
-
Identify Scope: Determine which files and modules are under security review. Prioritize authentication, authorization, data handling, API endpoints, and configuration files. Useto find security-sensitive patterns (
grep,eval,exec, password handling, JWT operations).innerHTML -
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, template injection, and LDAP injection. Verify that all user input is validated and parameterized queries are used.spawn -
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 forusage, check Content Security Policy headers, verify HTML sanitization for user-generated content, and check template rendering in server-side code.
dangerouslySetInnerHTML -
Check Secrets Management: Scan for hardcoded credentials, API keys, and secrets in source code. Verifyfiles are gitignored, environment variables are validated at startup, and secrets are accessed through proper management services.
.env -
Review Dependency Security: Runor check
npm auditfor known vulnerabilities. Identify outdated dependencies with known CVEs. Check for unnecessary dependencies that increase attack surface.package-lock.json -
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.
-
确定范围:明确安全审查覆盖的文件与模块。优先处理身份验证、授权、数据处理、API端点及配置文件。使用查找安全敏感模式(
grep、eval、exec、密码处理、JWT操作)。innerHTML -
检查身份验证与授权:审查JWT实现(签名算法、过期时间、刷新令牌)、OAuth2/OIDC集成、会话管理、密码哈希(bcrypt/argon2)及多因素认证。验证所有受保护路由均强制要求身份验证。
-
扫描注入漏洞:检查数据库查询中的SQL/NoSQL注入、/
exec中的命令注入、模板注入及LDAP注入。验证所有用户输入均经过验证,且使用参数化查询。spawn -
审查输入验证:检查所有API输入是否通过Zod、Joi或class-validator进行验证。验证架构完整性——无缺失字段、正确的类型约束、长度限制及格式验证。检查是否存在验证绕过路径。
-
评估XSS防护:审查React组件输出中的使用情况,检查内容安全策略标头,验证用户生成内容的HTML清理,以及服务器端代码中的模板渲染。
dangerouslySetInnerHTML -
检查密钥管理:扫描源代码中的硬编码凭据、API密钥及密钥。验证文件已被git忽略,环境变量在启动时已验证,且密钥通过正规管理服务访问。
.env -
审查依赖项安全:运行或检查
npm audit中的已知漏洞。识别存在已知CVE的过时依赖项。检查是否存在增加攻击面的不必要依赖项。package-lock.json -
评估安全标头与配置:检查是否使用helmet.js或手动配置安全标头。审查CORS策略、速率限制、HTTPS强制实施、Cookie安全标志(HttpOnly、Secure、SameSite)及CSP配置。
-
生成安全报告:生成结构化报告,包含按严重程度分类的发现结果(Critical、High、Medium、Low)、附带代码示例的修复指南,以及安全态势摘要。
Examples
示例
Example 1: JWT Security Review
示例1:JWT安全审查
typescript
// ❌ 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;
}typescript
// ❌ 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
示例2:SQL注入防护
typescript
// ❌ 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);
}typescript
// ❌ 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
示例3:输入验证
typescript
// ❌ 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);
});typescript
// ❌ 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
示例4:XSS防护
tsx
// ❌ 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>;
}tsx
// ❌ 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
示例5:安全标头与配置
typescript
// ❌ 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,
}));typescript
// ❌ 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
1. 安全态势摘要
Overall security assessment score (1-10) with key observations and risk level.
整体安全评估得分(1-10分),附带关键观察结果与风险等级。
2. Critical Vulnerabilities (Immediate Action)
2. 严重漏洞(立即处理)
Issues that can be exploited to compromise the system, steal data, or cause unauthorized access.
可被利用以攻陷系统、窃取数据或导致未授权访问的问题。
3. High Priority (Address Within 30 Days)
3. 高优先级(30天内处理)
Security misconfigurations, missing protections, or vulnerabilities requiring near-term remediation.
安全配置错误、缺失防护措施或需短期修复的漏洞。
4. Medium Priority (Address Within 90 Days)
4. 中优先级(90天内处理)
Issues that reduce security posture but have mitigating factors or limited exploitability.
降低安全态势但存在缓解因素或可利用性有限的问题。
5. Low Priority (Next Cycle)
5. 低优先级(下一周期处理)
Security improvements, hardening recommendations, and defense-in-depth enhancements.
安全改进建议、加固措施及纵深防御增强方案。
6. Positive Security Observations
6. 安全实践亮点
Well-implemented security patterns and practices to acknowledge.
值得肯定的已正确实现的安全模式与实践。
7. Remediation Roadmap
7. 修复路线图
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,SecureSameSite=Strict - Use in CI pipelines to catch dependency vulnerabilities
npm audit - Log security events (failed logins, permission denials) without logging sensitive data
- 在API边界验证所有输入——绝不单独信任客户端验证
- 使用参数化查询或ORM——绝不将用户输入拼接至查询语句
- 将密钥存储在环境变量或密钥管理器中——绝不要存于源代码
- 为数据库账户、API密钥及IAM角色应用最小权限原则
- 启用安全标头(helmet.js)并将CORS限制为可信来源
- 对所有公开端点实施速率限制
- 使用bcrypt或argon2哈希密码——绝不要对密码使用MD5/SHA
- 设置Cookie标志:、
HttpOnly、SecureSameSite=Strict - 在CI流水线中使用检测依赖项漏洞
npm audit - 记录安全事件(登录失败、权限拒绝),但不要记录敏感数据
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 directory for detailed security documentation:
references/- — OWASP Top 10 mapped to TypeScript/Node.js patterns
references/owasp-typescript.md - — Common vulnerability patterns and remediation
references/common-vulnerabilities.md - — Dependency scanning and supply chain security guide
references/dependency-security.md
请查看目录获取详细安全文档:
references/- —— 映射至TypeScript/Node.js模式的OWASP Top 10
references/owasp-typescript.md - —— 常见漏洞模式与修复方案
references/common-vulnerabilities.md - —— 依赖项扫描与供应链安全指南
references/dependency-security.md