typescript-security-review by giuseppe-trisciuoglio/developer-kit
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill typescript-security-review此技能为 TypeScript 和 Node.js 应用程序提供结构化、全面的安全审查。它根据 OWASP Top 10、特定框架的安全最佳实践以及生产就绪安全标准来评估代码。审查会产生按严重性(严重、高、中、低)分类的可操作发现项,并附带具体的修复示例。
当通过代理系统调用时,此技能会委托给 typescript-security-expert 代理进行深度安全分析。
确定范围:确定哪些文件和模块需要进行安全审查。优先处理身份验证、授权、数据处理、API 端点和配置文件。使用 grep 查找安全敏感模式(eval、exec、innerHTML、密码处理、JWT 操作)。
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
检查身份验证与授权:审查 JWT 实现(签名算法、过期时间、刷新令牌)、OAuth2/OIDC 集成、会话管理、密码哈希(bcrypt/argon2)和多因素认证。验证所有受保护路由是否都强制执行身份验证。
扫描注入漏洞:检查数据库查询中的 SQL/NoSQL 注入、exec/spawn 中的命令注入、模板注入和 LDAP 注入。验证所有用户输入是否经过验证,以及是否使用了参数化查询。
审查输入验证:检查所有 API 输入是否使用 Zod、Joi 或 class-validator 进行了验证。验证模式的完整性——没有缺失字段、正确的类型约束、长度限制和格式验证。检查是否存在验证绕过路径。
评估 XSS 防护:审查 React 组件输出中 dangerouslySetInnerHTML 的使用情况,检查内容安全策略标头,验证用户生成内容的 HTML 清理,并检查服务器端代码中的模板渲染。
检查密钥管理:扫描源代码中硬编码的凭据、API 密钥和密钥。验证 .env 文件是否被 gitignore 忽略,环境变量是否在启动时得到验证,以及密钥是否通过适当的管理服务访问。
审查依赖项安全性:运行 npm audit 或检查 package-lock.json 中的已知漏洞。识别具有已知 CVE 的过时依赖项。检查是否存在增加攻击面的不必要依赖项。
评估安全标头与配置:检查 helmet.js 或手动安全标头配置。审查 CORS 策略、速率限制、HTTPS 强制执行、Cookie 安全标志(HttpOnly、Secure、SameSite)和 CSP 配置。
生成安全报告:生成一份结构化报告,包含按严重性分类的发现项(严重、高、中、低)、带有代码示例的修复指南以及安全态势摘要。
// ❌ 严重:JWT 配置薄弱
import jwt from 'jsonwebtoken';
const SECRET = 'mysecret123'; // 硬编码的弱密钥
function generateToken(user: User) {
return jwt.sign({ id: user.id, role: user.role }, SECRET);
// 缺少过期时间,弱密钥,未指定算法
}
function verifyToken(token: string) {
return jwt.verify(token, SECRET); // 无算法限制
}
// ✅ 安全:正确的 JWT 配置
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 }, // 最小化声明,无敏感数据
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'], // 限制接受的算法
issuer: 'my-app',
audience: 'my-app-client',
}) as JwtPayload;
}
// ❌ 严重:SQL 注入漏洞
async function findUser(email: string) {
const result = await db.query(
`SELECT * FROM users WHERE email = '${email}'`
);
return result.rows[0];
}
// ✅ 安全:参数化查询
async function findUser(email: string) {
const result = await db.query(
'SELECT id, name, email FROM users WHERE email = $1',
[email]
);
return result.rows[0];
}
// ✅ 安全:使用类型安全查询的 ORM(Drizzle 示例)
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);
}
// ❌ 高:缺少输入验证
app.post('/api/users', async (req, res) => {
const user = await createUser(req.body);
res.json(user);
});
// ✅ 安全:使用 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);
});
// ❌ 高:通过 dangerouslySetInnerHTML 导致的 XSS 漏洞
function Comment({ content }: { content: string }) {
return <div dangerouslySetInnerHTML={{ __html: content }} />;
}
// ✅ 安全:渲染前清理 HTML
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 }} />;
}
// ✅ 更好:使用 markdown 渲染器而非原始 HTML
import ReactMarkdown from 'react-markdown';
function Comment({ content }: { content: string }) {
return <ReactMarkdown>{content}</ReactMarkdown>;
}
// ❌ 中:缺少安全标头且 CORS 过于宽松
const app = express();
app.use(cors()); // 允许所有来源
// ✅ 安全:全面的安全配置
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,
}));
将所有安全审查发现项按以下结构组织:
总体安全评估分数(1-10),包含关键观察结果和风险等级。
可被利用以危害系统、窃取数据或导致未经授权访问的问题。
安全配置错误、缺少防护措施或需要近期修复的漏洞。
降低安全态势但存在缓解因素或可利用性有限的问题。
安全改进建议、强化建议和纵深防御增强措施。
需要肯定的、已良好实施的安全模式和做法。
针对最关键的修复,提供带有代码示例的优先行动项。
HttpOnly、Secure、SameSite=Strictnpm audit 来捕获依赖项漏洞有关详细的安全文档,请参阅 references/ 目录:
references/owasp-typescript.md — 映射到 TypeScript/Node.js 模式的 OWASP Top 10references/common-vulnerabilities.md — 常见漏洞模式及修复方法references/dependency-security.md — 依赖项扫描和供应链安全指南每周安装量
150
代码仓库
GitHub 星标数
173
首次出现
2026 年 2 月 28 日
安全审计
安装于
gemini-cli136
codex136
github-copilot133
amp131
cline131
kimi-cli131
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.
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.
// ❌ 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;
}
// ❌ 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);
}
// ❌ 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);
});
// ❌ 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>;
}
// ❌ 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,
}));
Structure all security review findings as follows:
Overall security assessment score (1-10) with key observations and risk level.
Issues that can be exploited to compromise the system, steal data, or cause unauthorized access.
Security misconfigurations, missing protections, or vulnerabilities requiring near-term remediation.
Issues that reduce security posture but have mitigating factors or limited exploitability.
Security improvements, hardening recommendations, and defense-in-depth enhancements.
Well-implemented security patterns and practices to acknowledge.
Prioritized action items with code examples for the most critical fixes.
HttpOnly, Secure, SameSite=Strictnpm audit in CI pipelines to catch dependency vulnerabilitiesSee the references/ directory for detailed security documentation:
references/owasp-typescript.md — OWASP Top 10 mapped to TypeScript/Node.js patternsreferences/common-vulnerabilities.md — Common vulnerability patterns and remediationreferences/dependency-security.md — Dependency scanning and supply chain security guideWeekly Installs
150
Repository
GitHub Stars
173
First Seen
Feb 28, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykWarn
Installed on
gemini-cli136
codex136
github-copilot133
amp131
cline131
kimi-cli131
Better Auth 最佳实践指南:集成、配置与安全设置完整教程
31,800 周安装