Node.js Security Audit
Structured security audit for Node.js HTTP servers and web applications.
Audit Checklist
Critical (Must Fix Before Deploy)
Hardcoded Secrets
- - Search for: API keys, passwords, tokens in source code
- Pattern: INLINECODE0
- Fix: Move to env vars, fail if missing: INLINECODE1
XSS in Dynamic Content
- - Search for:
innerHTML, template literals injected into DOM, unsanitized user input in responses - Fix: Use
textContent, or escape: INLINECODE4
SQL/NoSQL Injection
- - Search for: String concatenation in queries,
eval(), Function() with user input - Fix: Parameterized queries, input validation
High (Should Fix)
CORS Misconfiguration
- - Search for: INLINECODE7
- Fix: Allowlist specific origins: INLINECODE8
Auth Bypass
- - Check: Every route that should require auth actually checks it
- Common miss: Static file routes, agent/webhook endpoints, health checks that expose data
Path Traversal
- - Check:
path.normalize() + startsWith(allowedDir) on all file-serving routes - Extra: Resolve symlinks with
fs.realpathSync() and re-check
Medium (Recommended)
Security Headers
CODEBLOCK0
Rate Limiting
CODEBLOCK1
Input Validation
- - Body size limits: INLINECODE12
- JSON parse in try/catch
- Type checking on expected fields
Low (Consider)
Dependency Audit: npm audit
Error Leakage: Don't send stack traces to clients in production
Cookie Security: INLINECODE14
Report Format
CODEBLOCK2
技能名称: nodejs-security-audit
详细描述:
Node.js 安全审计
针对Node.js HTTP服务器和Web应用程序的结构化安全审计。
审计清单
严重(部署前必须修复)
硬编码密钥
- - 搜索:源代码中的API密钥、密码、令牌
- 模式:grep -rn password\|secret\|token\|apikey\|apikey --include=.js --include=.ts | grep -v nodemodules | grep -v process.env\|\.env
- 修复:移至环境变量,缺失时终止运行:if (!process.env.SECRET) process.exit(1);
动态内容中的XSS
- - 搜索:innerHTML、注入DOM的模板字面量、响应中未净化的用户输入
- 修复:使用textContent,或进行转义:str.replace(/[&<>]/g, c => ({&:&,<:<,>:>,:",:'}[c]))
SQL/NoSQL注入
- - 搜索:查询中的字符串拼接、eval()、包含用户输入的Function()
- 修复:参数化查询、输入验证
高(应修复)
CORS配置错误
- - 搜索:Access-Control-Allow-Origin: *
- 修复:白名单特定来源:const origin = ALLOWED.has(req.headers.origin) ? req.headers.origin : ALLOWED.values().next().value
认证绕过
- - 检查:每个需要认证的路由是否确实进行了检查
- 常见遗漏:静态文件路由、代理/Webhook端点、暴露数据的健康检查
路径遍历
- - 检查:所有文件服务路由上的path.normalize() + startsWith(allowedDir)
- 额外:使用fs.realpathSync()解析符号链接并重新检查
中(推荐)
安全头
javascript
const HEADERS = {
X-Frame-Options: SAMEORIGIN,
X-Content-Type-Options: nosniff,
Referrer-Policy: strict-origin-when-cross-origin,
Permissions-Policy: camera=(), microphone=(), geolocation=(),
};
// 应用于所有响应
速率限制
javascript
const attempts = new Map(); // ip -> { count, resetAt }
const LIMIT = 5, WINDOW = 60000;
function isLimited(ip) {
const now = Date.now(), e = attempts.get(ip);
if (!e || now > e.resetAt) { attempts.set(ip, {count:1, resetAt:now+WINDOW}); return false; }
return ++e.count > LIMIT;
}
输入验证
- - 请求体大小限制:if (bodySize > 1048576) { req.destroy(); return; }
- 在try/catch中解析JSON
- 对预期字段进行类型检查
低(考虑)
依赖审计: npm audit
错误泄露: 生产环境中不要向客户端发送堆栈跟踪
Cookie安全: HttpOnly; Secure; SameSite=Strict
报告格式
安全审计:[文件名]
严重
- 1. [类别] 描述 — 文件:行号 — 修复:...
高
...
中
...
低
...
总结
X个严重,X个高,X个中,X个低