Loading...
Loading...
Compare original and translation side by side
references/security-index.mdreferences/security-index.md| Tier | When to Apply | Key Focus Areas |
|---|---|---|
| Always | All Node.js/TS code | Strict TypeScript, input validation, no hardcoded secrets, safe error handling |
| API/HTTP | Web endpoints, middleware | Headers (helmet), rate limiting, CORS, body limits, Content-Type validation |
| Auth | Authentication features | Password hashing (argon2), JWT validation, secure cookies, RBAC |
| Data | External data processing | SQL injection, XSS sanitization, prototype pollution, schema validation |
| Runtime | Dynamic code, processes | No eval, safe child_process, path traversal prevention |
| 层级 | 适用场景 | 核心关注领域 |
|---|---|---|
| 始终遵循 | 所有Node.js/TS代码 | 严格TypeScript配置、输入验证、禁止硬编码密钥、安全错误处理 |
| API/HTTP | Web端点、中间件 | 安全头(Helmet)、请求频率限制、CORS、请求体大小限制、Content-Type验证 |
| 身份验证 | 身份验证功能 | 密码哈希(argon2)、JWT验证、安全Cookie、基于角色的访问控制(RBAC) |
| 数据处理 | 外部数据处理 | SQL注入防护、XSS攻击净化、原型污染防护、Schema验证 |
| 运行时 | 动态代码、进程处理 | 禁止使用eval、安全子进程、路径遍历防护 |
// tsconfig.json
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"noUncheckedIndexedAccess": true
}
}// tsconfig.json
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"noUncheckedIndexedAccess": true
}
}// DO: Schema validation at entry points
import { z } from 'zod'
const UserSchema = z.object({
email: z.string().email(),
age: z.number().int().min(0).max(150),
})
// In route handler
const result = UserSchema.safeParse(req.body)
if (!result.success) {
return res.status(400).json({ error: 'Invalid input' })
}
const user = result.data // Type-safe validated data// 正确做法:在入口点进行Schema验证
import { z } from 'zod'
const UserSchema = z.object({
email: z.string().email(),
age: z.number().int().min(0).max(150),
})
// 在路由处理器中
const result = UserSchema.safeParse(req.body)
if (!result.success) {
return res.status(400).json({ error: 'Invalid input' })
}
const user = result.data // 类型安全的已验证数据// DON'T: String concatenation (SQL injection)
const query = `SELECT * FROM users WHERE id = ${userId}`
// DO: Parameterized queries
const result = await db.query('SELECT * FROM users WHERE id = $1', [userId])// 错误做法:字符串拼接(存在SQL注入风险)
const query = `SELECT * FROM users WHERE id = ${userId}`
// 正确做法:参数化查询
const result = await db.query('SELECT * FROM users WHERE id = $1', [userId])import argon2 from 'argon2'
// Hash password
const hash = await argon2.hash(password, { type: argon2.argon2id })
// Verify password
const valid = await argon2.verify(hash, password)import argon2 from 'argon2'
// 哈希密码
const hash = await argon2.hash(password, { type: argon2.argon2id })
// 验证密码
const valid = await argon2.verify(hash, password)import helmet from 'helmet'
import express from 'express'
const app = express()
app.use(helmet()) // Sets HSTS, CSP, X-Frame-Options, etc.
app.disable('x-powered-by')import helmet from 'helmet'
import express from 'express'
const app = express()
app.use(helmet()) // 设置HSTS、CSP、X-Frame-Options等安全头
app.disable('x-powered-by')// DO: Enforce strict body limits
app.use(express.json({ limit: '1kb' })) // Adjust based on expected payload
// DON'T: Unlimited body parsing (DoS risk)
app.use(express.json())// 正确做法:严格限制请求体大小
app.use(express.json({ limit: '1kb' })) // 根据预期负载调整
// 错误做法:无限制解析请求体(存在DoS风险)
app.use(express.json())import path from 'node:path'
// DO: Resolve and validate paths
const ALLOWED_DIR = '/app/uploads'
const safePath = path.resolve(ALLOWED_DIR, userInput)
if (!safePath.startsWith(ALLOWED_DIR)) {
throw new Error('Path traversal attempt blocked')
}import path from 'node:path'
// 正确做法:解析并验证路径
const ALLOWED_DIR = '/app/uploads'
const safePath = path.resolve(ALLOWED_DIR, userInput)
if (!safePath.startsWith(ALLOWED_DIR)) {
throw new Error('路径遍历尝试已被阻止')
}// DO: Generic error response to clients
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
console.error(err) // Log full error internally
res.status(500).json({ error: 'Internal server error' }) // Generic to client
})
// DON'T: Expose error details
res.status(500).json({ error: err.message, stack: err.stack })// 正确做法:向客户端返回通用错误响应
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
console.error(err) // 在内部记录完整错误
res.status(500).json({ error: '服务器内部错误' }) // 向客户端返回通用信息
})
// 错误做法:暴露错误详情
res.status(500).json({ error: err.message, stack: err.stack })// DO: Load secrets from environment
import 'dotenv/config'
const dbPassword = process.env.DB_PASSWORD
if (!dbPassword) throw new Error('DB_PASSWORD required')
// DON'T: Hardcoded secrets
const dbPassword = 'secret123' // Never do this// 正确做法:从环境变量加载密钥
import 'dotenv/config'
const dbPassword = process.env.DB_PASSWORD
if (!dbPassword) throw new Error('需要配置DB_PASSWORD')
// 错误做法:硬编码密钥
const dbPassword = 'secret123' // 绝对不要这样做// DO: Explicit Node.js built-in imports (prevents typosquatting)
import { createServer } from 'node:http'
import { readFile } from 'node:fs/promises'
import path from 'node:path'
// DON'T: Implicit imports
import { createServer } from 'http' // Could resolve to malicious package// 正确做法:显式导入Node.js内置模块(防止包名劫持)
import { createServer } from 'node:http'
import { readFile } from 'node:fs/promises'
import path from 'node:path'
// 错误做法:隐式导入
import { createServer } from 'http' // 可能解析为恶意包| Task | Load Reference |
|---|---|
| Project setup, tsconfig, type safety | |
| Form validation, user input, API params | |
| Login, sessions, JWT, passwords, RBAC | |
| Headers, CORS, rate limiting, CSP | |
| eval, child_process, prototype pollution | |
| File uploads, path handling, regex | |
| npm audit, lockfiles, supply chain | |
| Error handling, logging, monitoring | |
| Linters, CI/CD, threat modeling | |
| Full guideline lookup | |
| 任务内容 | 加载的参考文档 |
|---|---|
| 项目搭建、tsconfig配置、类型安全 | |
| 表单验证、用户输入、API参数处理 | |
| 登录、会话、JWT、密码、RBAC | |
| 安全头、CORS、请求频率限制、CSP | |
| eval、child_process、原型污染防护 | |
| 文件上传、路径处理、正则表达式 | |
| npm审计、锁定文件、供应链安全 | |
| 错误处理、日志、监控 | |
| 代码检查工具、CI/CD、威胁建模 | |
| 完整指南查询 | |
tsconfig.jsonpython3 scripts/audit-tsconfig.py /path/to/projectstrict: truenoImplicitAnystrictNullChecksnoUncheckedIndexedAccesstsconfig.jsonpython3 scripts/audit-tsconfig.py /path/to/projectstrict: truenoImplicitAnystrictNullChecksnoUncheckedIndexedAccessassets/tsconfig.secure.jsoneslint-security.config.jsassets/tsconfig.secure.jsoneslint-security.config.jsreferences/security-index.mdreferences/typescript-safety.mdreferences/input-validation.mdreferences/authentication.mdreferences/http-security.mdreferences/runtime-safety.mdreferences/filesystem-paths.mdreferences/dependencies.mdreferences/error-logging.mdreferences/operational.mdreferences/security-index.mdreferences/typescript-safety.mdreferences/input-validation.mdreferences/authentication.mdreferences/http-security.mdreferences/runtime-safety.mdreferences/filesystem-paths.mdreferences/dependencies.mdreferences/error-logging.mdreferences/operational.md