accelint-security-best-practices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Security Best Practices

安全最佳实践

Systematic security auditing and vulnerability detection for JavaScript/TypeScript applications. Combines audit workflow with OWASP Top 10 security patterns for production-ready code.
Framework-Agnostic Guidance: This skill provides security principles applicable across frameworks (Express, Fastify, Nest.js, Next.js, etc.). Code examples illustrate concepts using common patterns—adapt them to your project's specific framework and package manager (npm, yarn, pnpm, bun).
为JavaScript/TypeScript应用提供系统化的安全审计与漏洞检测服务,结合审计工作流与OWASP Top 10安全模式,助力打造生产就绪的安全代码。
框架无关指导:本技能提供适用于各类框架(Express、Fastify、Nest.js、Next.js等)的安全原则。代码示例采用通用模式阐释概念,可根据项目的特定框架与包管理器(npm、yarn、pnpm、bun)进行适配。

NEVER Do When Implementing Security

实现安全时绝对禁止的行为

Note: For general best practices (type safety, code quality, documentation), use the respective accelint skills. This section focuses exclusively on security-specific anti-patterns.
  • NEVER hardcode secrets - API keys, tokens, passwords, or credentials in source code are immediately compromised when pushed to version control. Even private repositories leak secrets through employee turnover, third-party access, and git history. In 2024 breach analysis, 47% of exposed credentials came from
    .env
    files accidentally committed then 'deleted' (but preserved in git history). Attackers scan public GitHub commits within minutes of push. Use environment variables exclusively.
  • NEVER trust user input - Validate with schemas (Zod, Joi) covering type, format, size, and content.
  • NEVER concatenate user input into queries - Use parameterized queries, ORMs, or prepared statements exclusively. String concatenation in SQL, NoSQL, or shell commands enables injection attacks.
  • NEVER store sensitive data in localStorage - localStorage is vulnerable to XSS attacks where malicious scripts steal tokens. JWT tokens, session IDs, or credentials in localStorage persist across sessions and are accessible to any JavaScript code. Use httpOnly cookies for auth tokens.
  • NEVER skip authorization checks - Authentication verifies identity; authorization verifies permission. Attackers will manipulate IDs, skip authentication, or guess URLs. Every endpoint accessing resources must verify the requesting user owns that resource or has appropriate role.
  • NEVER expose detailed errors to users - Log server-side, return generic messages. Stack traces leak architecture for reconnaissance.
  • NEVER use Array.includes() for permission checks - Permission arrays with 100+ roles suffer O(n) lookup time and type safety issues. Use
    Set.has()
    for O(1) lookup or role-based access control (RBAC) with proper type checking.
  • NEVER skip rate limiting on APIs - Unlimited API requests enable brute force attacks (1000 password attempts/second), denial of service (exhaust server resources), or data scraping (enumerate all users/resources). Apply rate limits to all endpoints, with stricter limits on authentication and expensive operations.
  • NEVER log sensitive data - Passwords, tokens, credit cards, or personal information in logs persist in log aggregation systems, backups, and third-party services. Logs are accessible to more people than the application itself. Redact sensitive fields before logging.
  • NEVER use default configurations in production - Default secrets, disabled security headers, permissive CORS, or development modes in production create known vulnerabilities. Attackers scan for defaults. Harden all configurations for production environments.
注意:关于类型安全、代码质量、文档等通用最佳实践,请使用对应的accelint技能。本节仅聚焦于安全相关的反模式。
  • 绝对不要硬编码密钥 - 源代码中的API密钥、令牌、密码或凭证在推送到版本控制后会立即泄露。即使是私有仓库,也会因员工流动、第三方访问和Git历史记录导致密钥泄露。2024年漏洞分析显示,47%的暴露凭证来自意外提交后被“删除”但仍保留在Git历史中的
    .env
    文件。攻击者会在代码推送后的几分钟内扫描公开的GitHub提交。请完全使用环境变量存储密钥。
  • 绝对不要信任用户输入 - 使用模式验证工具(Zod、Joi)对输入的类型、格式、大小和内容进行验证。
  • 绝对不要将用户输入直接拼接进查询语句 - 完全使用参数化查询、ORM或预编译语句。SQL、NoSQL或Shell命令中的字符串拼接会导致注入攻击。
  • 绝对不要在localStorage中存储敏感数据 - localStorage易受XSS攻击,恶意脚本可窃取其中的令牌。存储在localStorage中的JWT令牌、会话ID或凭证会跨会话持久化,且可被任何JavaScript代码访问。请使用httpOnly Cookie存储身份验证令牌。
  • 绝对不要跳过授权检查 - 身份验证用于验证身份,而授权用于验证权限。攻击者会篡改ID、跳过身份验证或猜测URL。所有访问资源的端点必须验证请求用户是否拥有该资源或具备相应角色。
  • 绝对不要向用户暴露详细错误信息 - 在服务器端记录错误,向用户返回通用消息。堆栈跟踪会泄露系统架构,被攻击者用于侦察。
  • 绝对不要使用Array.includes()进行权限检查 - 包含100+角色的权限数组会存在O(n)的查找时间和类型安全问题。使用
    Set.has()
    实现O(1)查找,或采用带类型检查的基于角色的访问控制(RBAC)。
  • 绝对不要跳过API的速率限制 - 无限制的API请求会导致暴力破解攻击(每秒1000次密码尝试)、拒绝服务(耗尽服务器资源)或数据爬取(枚举所有用户/资源)。为所有端点添加速率限制,对身份验证端点和高消耗操作设置更严格的限制。
  • 绝对不要记录敏感数据 - 日志中的密码、令牌、信用卡信息或个人数据会保留在日志聚合系统、备份和第三方服务中。日志的访问人员范围远大于应用本身。记录前请先脱敏敏感字段。
  • 绝对不要在生产环境中使用默认配置 - 生产环境中的默认密钥、禁用的安全头、宽松的CORS策略或开发模式会导致已知漏洞。攻击者会专门扫描默认配置。请针对生产环境强化所有配置。

Before Implementing Security, Ask

实现安全前需思考的问题

Apply these tests to ensure comprehensive security coverage:
应用以下测试确保全面的安全覆盖:

Threat Assessment

威胁评估

  • What's the attack surface? Identify all points where user input enters the system (forms, APIs, file uploads, URLs)
  • What's the worst-case scenario? Consider data breaches, unauthorized access, service disruption, or financial loss
  • Who are the attackers? Script kiddies exploit known vulnerabilities; sophisticated attackers chain multiple weaknesses
  • 攻击面是什么? 识别用户输入进入系统的所有入口(表单、API、文件上传、URL)
  • 最坏情况是什么? 考虑数据泄露、未授权访问、服务中断或财务损失
  • 攻击者是谁? 脚本小子会利用已知漏洞;高级攻击者会组合多个弱点发起攻击

Compliance Verification

合规性验证

  • Do I have authentication on all protected routes? Public APIs may be intentional, but verify each endpoint's access policy
  • Are authorization checks before operations? Verify ownership/permissions before reading, writing, or deleting resources
  • Is all user input validated? Check type, format, size, and content with schemas before processing
  • 所有受保护的路由都已添加身份验证吗? 公开API可能是有意设计,但需验证每个端点的访问策略
  • 操作前是否已进行授权检查? 在读取、写入或删除资源前,验证用户的所有权/权限
  • 所有用户输入都已验证吗? 在处理前使用模式验证工具检查输入的类型、格式、大小和内容

Defense in Depth

纵深防御

  • Is there a single point of failure? Layer defenses so one bypass doesn't compromise entire system
  • Are errors handled gracefully? Unhandled errors leak information; proper handling maintains security posture
  • Is logging sufficient for audit trails? Security events (login attempts, access denials, suspicious patterns) must be logged for incident response
  • 是否存在单点故障? 分层部署防御措施,确保单个防御被绕过不会导致整个系统被攻破
  • 错误是否被优雅处理? 未处理的错误会泄露信息;正确的错误处理可维持安全态势
  • 日志是否足以支持审计追踪? 安全事件(登录尝试、访问拒绝、可疑模式)必须被记录,以便进行事件响应

How to Use

使用方法

This skill uses progressive disclosure to minimize context usage:
本技能采用渐进式披露方式,最小化上下文使用:

1. Start with the Workflow (SKILL.md)

1. 从工作流开始(SKILL.md)

Follow the 4-phase audit workflow below for systematic security analysis.
遵循以下4阶段审计工作流,进行系统化的安全分析。

2. Reference Security Rules Overview (AGENTS.md)

2. 参考安全规则概述(AGENTS.md)

Load AGENTS.md to scan compressed security rule summaries organized by category.
加载AGENTS.md,查看按类别组织的压缩版安全规则摘要。

3. Load Specific Security Patterns as Needed

3. 根据需要加载特定安全模式

When you identify specific security issues, load corresponding reference files for detailed ❌/✅ examples.
当识别到特定安全问题时,加载对应的参考文件,查看详细的❌/✅示例。

4. Use the Report Template

4. 使用报告模板

When this skill is invoked, use the standardized report format:
Template:
assets/output-report-template.md
调用本技能时,请使用标准化报告格式:
模板
assets/output-report-template.md

Security Audit Workflow

安全审计工作流

Two modes of operation:
  1. Audit Mode - Skill invoked directly (
    /accelint-security-best-practices <path>
    ) or user explicitly requests security audit
    • Generate a structured audit report using the template (Phases 1-2 only)
    • Report findings for user review before implementation
    • User decides which security fixes to apply
  2. Implementation Mode - Skill triggers automatically during feature work
    • Identify and apply security fixes directly (all 4 phases)
    • No formal report needed
    • Focus on fixing vulnerabilities inline
Copy this checklist to track progress:
- [ ] Phase 1: Discover - Identify security vulnerabilities through systematic code analysis
- [ ] Phase 2: Categorize - Classify issues by OWASP category and severity
- [ ] Phase 3: Remediate - Apply security patterns from references/
- [ ] Phase 4: Verify - Validate fixes and confirm vulnerability closure
两种操作模式:
  1. 审计模式 - 直接调用技能(
    /accelint-security-best-practices <path>
    )或用户明确请求安全审计
    • 使用模板生成结构化审计报告(仅第1-2阶段)
    • 向用户报告审计结果,供其在实施前审阅
    • 由用户决定应用哪些安全修复
  2. 实现模式 - 在功能开发过程中自动触发技能
    • 直接识别并应用安全修复(全部4阶段)
    • 无需正式报告
    • 专注于内联修复漏洞
复制此清单跟踪进度:
- [ ] Phase 1: Discover - Identify security vulnerabilities through systematic code analysis
- [ ] Phase 2: Categorize - Classify issues by OWASP category and severity
- [ ] Phase 3: Remediate - Apply security patterns from references/
- [ ] Phase 4: Verify - Validate fixes and confirm vulnerability closure

Phase 1: Discover Security Vulnerabilities

阶段1:发现安全漏洞

CRITICAL: Audit ALL code for security vulnerabilities. Do not skip code based on assumptions about exposure. Internal utilities, helpers, and data transformations are frequently exposed through APIs, file uploads, or user interactions even if their implementation appears isolated.
Perform systematic static code analysis to identify ALL security anti-patterns:
  • Hardcoded secrets (API keys, passwords, tokens)
  • Missing input validation (user data, file uploads, API responses)
  • Injection vulnerabilities (SQL, NoSQL, Command, XSS)
  • Broken access control (missing auth, no ownership checks, IDOR)
  • Insecure authentication (tokens in localStorage, weak session management)
  • Missing rate limiting (auth endpoints, expensive operations)
  • Sensitive data exposure (logs, error messages, client responses)
  • Security misconfiguration (default configs, missing headers, permissive CORS)
  • Vulnerable dependencies (outdated packages, known CVEs)
  • Missing CSRF protection (state-changing operations)
  • SSRF vulnerabilities (unvalidated URL fetching)
Output: Complete list of ALL identified vulnerabilities with their locations, severity, and OWASP category. Do not filter based on "likelihood" - report everything found.
关键:审计所有代码中的安全漏洞。不要基于对暴露程度的假设跳过任何代码。内部工具、辅助函数和数据转换逻辑即使看起来是隔离的,也经常会通过API、文件上传或用户交互暴露出来。
执行系统化的静态代码分析,识别所有安全反模式:
  • 硬编码密钥(API密钥、密码、令牌)
  • 缺失输入验证(用户数据、文件上传、API响应)
  • 注入漏洞(SQL、NoSQL、命令注入、XSS)
  • 访问控制失效(缺失身份验证、无所有权检查、IDOR)
  • 不安全的身份验证(令牌存储在localStorage、弱会话管理)
  • 缺失速率限制(身份验证端点、高消耗操作)
  • 敏感数据泄露(日志、错误消息、客户端响应)
  • 安全配置错误(默认配置、缺失安全头、宽松的CORS)
  • 易受攻击的依赖项(过时包、已知CVE)
  • 缺失CSRF保护(状态变更操作)
  • SSRF漏洞(未验证的URL请求)
输出:所有已识别漏洞的完整列表,包含漏洞位置、严重程度和OWASP分类。不要基于“被利用可能性”进行过滤——报告所有发现的问题。

Phase 2: Categorize and Assess Risk

阶段2:分类与风险评估

For EVERY vulnerability identified in Phase 1, categorize by OWASP category and severity:
Categorize ALL vulnerabilities by OWASP Top 10 category:
OWASP CategoryCommon IssuesSeverity Range
A01: Broken Access ControlMissing auth, no ownership checks, IDORCritical-High
A02: Cryptographic FailuresHardcoded secrets, weak hashing, insecure storageCritical-Medium
A03: InjectionSQL, NoSQL, Command, XSS vulnerabilitiesCritical-High
A04: Insecure DesignMissing rate limiting, no input validationHigh-Medium
A05: Security MisconfigurationDefault configs, missing headers, dev mode in prodHigh-Low
A06: Vulnerable ComponentsOutdated dependencies, known CVEsCritical-Low
A07: Auth FailuresWeak session management, no MFA, credential stuffingCritical-High
A08: Data Integrity FailuresMissing CSRF, unsigned updatesHigh-Medium
A09: Logging FailuresNo security logging, insufficient monitoringMedium-Low
A10: SSRFUnvalidated URL fetching, internal network accessHigh-Medium
Severity Levels:
  • Critical: Direct path to data breach, remote code execution, or complete system compromise
    • Examples: SQL injection, hardcoded production secrets, no authentication on admin endpoints
  • High: Likely to enable unauthorized access, data theft, or service disruption
    • Examples: Missing authorization checks, XSS vulnerabilities, insecure session management
  • Medium: Could be exploited with specific conditions or chained with other vulnerabilities
    • Examples: Missing rate limiting, weak CORS policy, insufficient logging
  • Low: Defense-in-depth improvements, best practices, or edge case protections
    • Examples: Missing security headers, overly detailed error messages
Quick reference for mapping vulnerabilities:
Load references/quick-reference.md for detailed vulnerability-to-category mapping and anti-pattern detection.
Output: Categorized list of ALL vulnerabilities with their OWASP categories and severity levels. Do not filter or prioritize - list everything found in Phase 1.
针对阶段1中识别的每个漏洞,按OWASP分类和严重程度进行归类:
按OWASP Top 10分类对所有漏洞进行归类:
OWASP分类常见问题严重程度范围
A01: 访问控制失效缺失身份验证、无所有权检查、IDOR关键-高
A02: 加密失败硬编码密钥、弱哈希算法、不安全存储关键-中
A03: 注入SQL、NoSQL、命令注入、XSS漏洞关键-高
A04: 不安全设计缺失速率限制、无输入验证高-中
A05: 安全配置错误默认配置、缺失安全头、生产环境使用开发模式高-低
A06: 易受攻击的组件过时依赖项、已知CVE关键-低
A07: 身份验证失败弱会话管理、无MFA、凭证填充攻击关键-高
A08: 数据完整性失败缺失CSRF保护、未签名的更新高-中
A09: 日志记录失败无安全日志、监控不足中-低
A10: SSRF未验证的URL请求、内部网络访问高-中
严重程度等级:
  • 关键:直接导致数据泄露、远程代码执行或整个系统被攻破
    • 示例:SQL注入、硬编码生产环境密钥、管理端点缺失身份验证
  • :可能导致未授权访问、数据盗窃或服务中断
    • 示例:缺失授权检查、XSS漏洞、不安全的会话管理
  • :在特定条件下可被利用,或与其他漏洞组合发起攻击
    • 示例:缺失速率限制、弱CORS策略、日志记录不足
  • :纵深防御改进、最佳实践或边缘场景防护
    • 示例:缺失安全头、过于详细的错误消息
漏洞映射快速参考:
加载references/quick-reference.md查看详细的漏洞-分类映射和反模式检测方法。
输出:所有漏洞的分类列表,包含OWASP分类和严重程度等级。不要过滤或排序——列出阶段1中发现的所有问题。

Phase 3: Remediate Using Security Patterns

阶段3:使用安全模式修复漏洞

Step 1: Identify your vulnerability category from Phase 2 analysis.
Step 2: Load MANDATORY references for your category. Read each file completely with no range limits.
CategoryMANDATORY FilesOptionalDo NOT Load
Secrets Managementsecrets-management.mdall others
Input Validationinput-validation.mdfile-uploads.md (for file upload features)secrets, auth
Injection Preventioninjection-prevention.mdinput validation, XSS
Authenticationauthentication.mdmfa.md (for multi-factor auth features)authorization, secrets
Authorizationauthorization.mdauthentication
XSS Preventionxss-prevention.mdinjection, CSRF
CSRF Protectioncsrf-protection.mdXSS, auth
Rate Limitingrate-limiting.mdauth, injection
Sensitive Datasensitive-data.mdsecrets, logging
Dependency Securitydependency-security.mdall others
Security Headerssecurity-headers.mdXSS, CSRF
SSRF Preventionssrf-prevention.mdinjection, input validation
Notes:
  • If vulnerability spans multiple categories, load references for all relevant categories
  • Security patterns are cumulative - apply defense in depth by addressing all categories
  • Load optional files when implementing specific features (file uploads, MFA, etc.)

Step 3: Scan for quick reference during remediation
Load AGENTS.md to see compressed security rule summaries organized by category. Use as a quick lookup while implementing patterns from the detailed reference files above.
Apply patterns systematically:
  1. Load the reference file for the identified vulnerability category
  2. Scan the ❌/✅ examples to find matching patterns
  3. Apply the security fix ensuring defense in depth
  4. Add comments explaining the security consideration and referencing the pattern
Example remediation:
typescript
// ❌ Before: SQL Injection vulnerability
const query = `SELECT * FROM users WHERE email = '${email}'`;
const user = await db.query(query);

// ✅ After: Parameterized query prevents injection
// Security: injection-prevention.md - parameterized queries
const user = await db.query(
  'SELECT * FROM users WHERE email = $1',
  [email]
);
步骤1:从阶段2的分析中确定漏洞类别
步骤2:加载对应类别的必填参考文件。完整阅读每个文件,不要限制阅读范围。
类别必填文件可选文件禁止加载
密钥管理secrets-management.md所有其他文件
输入验证input-validation.mdfile-uploads.md(针对文件上传功能)密钥管理、身份验证相关文件
注入防护injection-prevention.md输入验证、XSS防护相关文件
身份验证authentication.mdmfa.md(针对多因素身份验证功能)授权、密钥管理相关文件
授权authorization.md身份验证相关文件
XSS防护xss-prevention.md注入防护、CSRF防护相关文件
CSRF防护csrf-protection.mdXSS防护、身份验证相关文件
速率限制rate-limiting.md身份验证、注入防护相关文件
敏感数据保护sensitive-data.md密钥管理、日志记录相关文件
依赖项安全dependency-security.md所有其他文件
安全头配置security-headers.mdXSS防护、CSRF防护相关文件
SSRF防护ssrf-prevention.md注入防护、输入验证相关文件
注意
  • 如果漏洞跨多个类别,加载所有相关类别的参考文件
  • 安全模式是累积的——通过解决所有类别实现纵深防御
  • 当实现特定功能(文件上传、MFA等)时,加载可选文件

步骤3:修复过程中使用快速参考
加载AGENTS.md查看按类别组织的压缩版安全规则摘要。在实施上述详细参考文件中的模式时,将其用作快速查找工具。
系统化应用模式:
  1. 加载对应漏洞类别的参考文件
  2. 扫描❌/✅示例,找到匹配的模式
  3. 应用安全修复,确保纵深防御
  4. 添加注释,说明安全考虑因素并引用对应模式
修复示例:
typescript
// ❌ 修复前:存在SQL注入漏洞
const query = `SELECT * FROM users WHERE email = '${email}'`;
const user = await db.query(query);

// ✅ 修复后:参数化查询防止注入
// Security: injection-prevention.md - parameterized queries
const user = await db.query(
  'SELECT * FROM users WHERE email = $1',
  [email]
);

Phase 4: Verify Security Fixes

阶段4:验证安全修复

Validate vulnerability closure:
  1. Review code to confirm vulnerability is fully addressed
  2. Verify no new vulnerabilities introduced by the fix
  3. Check defense in depth - are multiple layers protecting critical resources?
Security testing:
  1. Run existing test suite - all tests must pass
  2. Add security-specific tests for the vulnerability
  3. Consider penetration testing for critical vulnerabilities
Document security fix:
typescript
// Security fix applied: 2026-02-01
// Vulnerability: SQL injection via email parameter (Critical)
// OWASP Category: A03 - Injection
// Pattern: injection-prevention.md - parameterized queries
// Verified: All tests pass, manual SQL injection attempts blocked
Deciding whether to deploy the fix:
  • Critical vulnerabilities: Deploy immediately with emergency process if needed
  • High vulnerabilities: Deploy in next release cycle (days, not weeks)
  • Medium vulnerabilities: Deploy with next scheduled release
  • Low vulnerabilities: Deploy when convenient or batch with other security improvements
If tests fail: Fix the security implementation or find alternative solution. Security fixes should not break functionality.
验证漏洞是否已修复:
  1. 审阅代码,确认漏洞已完全解决
  2. 验证修复未引入新的漏洞
  3. 检查纵深防御——关键资源是否有多层防护?
安全测试:
  1. 运行现有测试套件——所有测试必须通过
  2. 针对该漏洞添加安全专项测试
  3. 针对关键漏洞,考虑进行渗透测试
记录安全修复:
typescript
// Security fix applied: 2026-02-01
// Vulnerability: SQL injection via email parameter (Critical)
// OWASP Category: A03 - Injection
// Pattern: injection-prevention.md - parameterized queries
// Verified: All tests pass, manual SQL injection attempts blocked
决定是否部署修复:
  • 关键漏洞:立即部署,必要时使用紧急流程
  • 高风险漏洞:在下一个发布周期部署(数天内,而非数周)
  • 中风险漏洞:随下一个计划发布版本部署
  • 低风险漏洞:在方便时部署,或与其他安全改进批量部署
如果测试失败:修复安全实现或寻找替代方案。安全修复不应破坏现有功能。

Common Implementation Pitfalls

常见实现陷阱

Security fixes sometimes conflict with existing functionality. Here are expert solutions for common scenarios:
Issue❌ Wrong Approach✅ Correct Approach
Parameterized queries break dynamic column sortingAdd try-catch, fall back to concatenationUse column name whitelist:
const allowed = ['name', 'email', 'created_at']; if (!allowed.includes(column)) throw Error;
then safely concatenate
Rate limiting breaks load testsDisable rate limiting in test environmentUse separate rate limit config for tests based on environment detection
CSRF tokens break API integration testsSkip CSRF validation in testsGenerate valid CSRF tokens in test setup using your CSRF library's token generation function
Input validation rejects legitimate edge casesLoosen validation rulesInvestigate the edge case - is it legitimate? If yes, update schema. If no, reject it. Real users shouldn't hit validation errors.
Authorization checks break admin impersonationSkip auth checks for admin usersImplement proper impersonation: admin gets temporary token with target user's permissions, logged for audit
HTTPOnly cookies break mobile app authStore tokens in localStorage for mobileUse secure token storage: iOS Keychain, Android Keystore, or platform-specific secure storage APIs
安全修复有时会与现有功能冲突。以下是针对常见场景的专家解决方案:
问题❌ 错误做法✅ 正确做法
参数化查询破坏动态列排序添加try-catch,回退到字符串拼接使用列名白名单:
const allowed = ['name', 'email', 'created_at']; if (!allowed.includes(column)) throw Error;
然后安全地拼接列名
速率限制破坏负载测试在测试环境中禁用速率限制根据环境检测,为测试环境使用单独的速率限制配置
CSRF令牌破坏API集成测试在测试中跳过CSRF验证使用CSRF库的令牌生成函数在测试设置中生成有效的CSRF令牌
输入验证拒绝合法的边缘场景放宽验证规则调查边缘场景——是否合法?如果是,更新模式;如果否,拒绝该输入。真实用户不应触发验证错误。
授权检查破坏管理员模拟功能为管理员用户跳过授权检查实现正确的模拟机制:管理员获取具有目标用户权限的临时令牌,并记录该操作用于审计
HTTPOnly Cookie破坏移动应用身份验证为移动应用将令牌存储在localStorage中使用安全令牌存储:iOS Keychain、Android Keystore或平台特定的安全存储API

When Security and Functionality Conflict

当安全与功能冲突时

Priority order:
  1. Never compromise on Critical vulnerabilities (SQL injection, hardcoded secrets, missing auth) - find alternative architecture
  2. High vulnerabilities can have slight trade-offs if properly documented and compensated with other controls
  3. Medium/Low vulnerabilities may be deferred if business justification is strong and risk is accepted
Documentation requirement for trade-offs:
typescript
// SECURITY TRADE-OFF DOCUMENTED: 2026-02-01
// Issue: Rate limiting breaks webhook ingestion from trusted partner
// Decision: Exempt partner IP range from rate limiting
// Compensating controls:
//   - IP whitelist strictly maintained (only 2 partner IPs)
//   - Separate monitoring for partner traffic
//   - Manual review of partner traffic daily
//   - 30-day review scheduled to implement alternative solution
// Risk accepted by: [Name], [Title]
优先级顺序:
  1. 绝不妥协关键漏洞(SQL注入、硬编码密钥、缺失身份验证)——寻找替代架构
  2. 高风险漏洞可在适当记录并辅以其他控制措施的情况下进行轻微权衡
  3. 中/低风险漏洞如果有充分的业务理由且风险已被接受,可推迟修复
权衡决策的文档要求:
typescript
// SECURITY TRADE-OFF DOCUMENTED: 2026-02-01
// Issue: Rate limiting breaks webhook ingestion from trusted partner
// Decision: Exempt partner IP range from rate limiting
// Compensating controls:
//   - IP whitelist strictly maintained (only 2 partner IPs)
//   - Separate monitoring for partner traffic
//   - Manual review of partner traffic daily
//   - 30-day review scheduled to implement alternative solution
// Risk accepted by: [Name], [Title]

Freedom Calibration

自由度校准

Calibrate guidance specificity to vulnerability severity:
Vulnerability SeverityFreedom LevelGuidance FormatExample
Critical (data breach, RCE)Low freedomExact pattern from reference, no deviation"Use parameterized query:
db.query('SELECT * FROM users WHERE id = $1', [id])
"
High (unauthorized access)Medium freedomPattern with examples, verify coverage"Implement RBAC or ownership checks before resource access"
Medium (defense in depth)Medium freedomMultiple valid approaches, pick based on architecture"Use rate limiting with express-rate-limit or implement custom middleware"
Low (best practices)High freedomGeneral guidance, implementation varies"Consider adding security headers for defense in depth"
The test: "What's the severity and blast radius?"
  • Critical/High severity → Low freedom with exact patterns to prevent mistakes
  • Medium severity → Medium freedom with validated approaches
  • Low severity → High freedom with general best practices
根据漏洞严重程度调整指导的具体性:
漏洞严重程度自由度指导格式示例
关键(数据泄露、远程代码执行)低自由度参考文件中的精确模式,不允许偏离"使用参数化查询:
db.query('SELECT * FROM users WHERE id = $1', [id])
"
高风险(未授权访问)中等自由度带示例的模式,需验证覆盖范围"在访问资源前实现RBAC或所有权检查"
中风险(纵深防御)中等自由度多种有效方案,根据架构选择"使用express-rate-limit实现速率限制,或自定义中间件"
低风险(最佳实践)高自由度通用指导,实现方式灵活"考虑添加安全头以增强纵深防御"
测试标准: "严重程度和影响范围是什么?"
  • 关键/高严重程度 → 低自由度,使用精确模式避免错误
  • 中严重程度 → 中等自由度,使用经过验证的方案
  • 低严重程度 → 高自由度,使用通用最佳实践

Important Notes

重要说明

  • Audit everything philosophy - Audit ALL code for security vulnerabilities. Internal utilities, helpers, and data transformations are frequently exposed through APIs or user interactions even when they appear isolated. Do not make assumptions about security boundaries.
  • Report all findings - Perform systematic static analysis to identify and report ALL vulnerabilities with their severity and OWASP category. Do not filter based on "likelihood" of exploitation.
  • Reference files are authoritative - The patterns in references/ follow OWASP best practices. Follow them exactly unless security requirements dictate otherwise.
  • Defense in depth - Layer security controls so single vulnerability doesn't compromise entire system. Authentication + authorization + input validation + rate limiting.
  • Security testing - Security fixes require testing with malicious inputs and edge cases. Add tests for attack scenarios before deploying.
  • Incident response - Security logging and monitoring enable detection and response to attacks. Log all security events with sufficient detail for investigation.
  • 审计所有内容的理念 - 审计所有代码中的安全漏洞。内部工具、辅助函数和数据转换逻辑即使看起来是隔离的,也经常会通过API或用户交互暴露出来。不要对安全边界做假设。
  • 报告所有发现 - 执行系统化的静态分析,识别并报告所有漏洞及其严重程度和OWASP分类。不要基于“被利用可能性”进行过滤。
  • 参考文件具有权威性 - references/目录中的模式遵循OWASP最佳实践。除非安全要求另有规定,否则严格遵循这些模式。
  • 纵深防御 - 分层部署安全控制,确保单个漏洞不会导致整个系统被攻破。身份验证+授权+输入验证+速率限制。
  • 安全测试 - 安全修复需要使用恶意输入和边缘场景进行测试。部署前添加针对攻击场景的测试。
  • 事件响应 - 安全日志和监控可实现对攻击的检测和响应。记录所有安全事件,并保留足够的细节用于调查。

Quick Decision Tree

快速决策树

Use this table to rapidly identify which security category applies and appropriate severity.
Audit everything: Identify ALL security vulnerabilities in the code regardless of current exposure. Report all findings with severity and OWASP category.
If You See...Vulnerability TypeOWASP CategoryTypical Severity
API key, password, or token in source codeHardcoded secretsA02: Cryptographic FailuresCritical
User input directly in SQL/NoSQL queryInjection vulnerabilityA03: InjectionCritical
No
authenticate
middleware on protected route
Missing authenticationA01: Broken Access ControlCritical
No ownership/permission check before resource accessMissing authorizationA01: Broken Access ControlHigh
JWT token in
localStorage.setItem()
Insecure token storageA07: Auth FailuresHigh
User input without schema validationMissing input validationA04: Insecure DesignHigh
No rate limiting on
/api/login
or
/api/register
Missing rate limitingA04: Insecure DesignHigh
dangerouslySetInnerHTML
without sanitization
XSS vulnerabilityA03: InjectionHigh
State-changing operation without CSRF tokenMissing CSRF protectionA08: Data Integrity FailuresHigh
Password, token, or PII in
console.log()
Sensitive data in logsA09: Logging FailuresMedium
Stack trace or database error sent to userInformation leakageA05: Security MisconfigurationMedium
npm audit
shows vulnerabilities
Vulnerable dependenciesA06: Vulnerable ComponentsCritical-Low (varies)
fetch(userProvidedUrl)
without validation
SSRF vulnerabilityA10: SSRFHigh
No security headers (CSP, HSTS)Missing security headersA05: Security MisconfigurationMedium
Sequential user IDs without ownership checkIDOR vulnerabilityA01: Broken Access ControlHigh
CORS: *
in production
Permissive CORSA05: Security MisconfigurationMedium
process.env.NODE_ENV !== 'production'
check missing
Dev mode in productionA05: Security MisconfigurationMedium-Low
How to use this table:
  1. Identify the pattern from code review
  2. Find matching row in "If You See..." column
  3. Note the OWASP Category and Typical Severity
  4. Jump to corresponding Security Category in Phase 3
  5. Load MANDATORY reference files for that category
使用此表快速识别对应的安全类别和适当的严重程度。
审计所有内容:识别代码中的所有安全漏洞,无论当前是否暴露。报告所有发现的问题及其严重程度和OWASP分类。
如果发现...漏洞类型OWASP分类典型严重程度
源代码中的API密钥、密码或令牌硬编码密钥A02: 加密失败关键
用户输入直接嵌入SQL/NoSQL查询注入漏洞A03: 注入关键
受保护路由上缺失
authenticate
中间件
缺失身份验证A01: 访问控制失效关键
访问资源前缺失所有权/权限检查缺失授权A01: 访问控制失效
JWT令牌存储在
localStorage.setItem()
不安全的令牌存储A07: 身份验证失败
用户输入未经过模式验证缺失输入验证A04: 不安全设计
/api/login
/api/register
端点缺失速率限制
缺失速率限制A04: 不安全设计
dangerouslySetInnerHTML
未经过清理
XSS漏洞A03: 注入
状态变更操作缺失CSRF令牌缺失CSRF保护A08: 数据完整性失败
console.log()
中包含密码、令牌或PII
日志中的敏感数据A09: 日志记录失败
向用户返回堆栈跟踪或数据库错误信息泄露A05: 安全配置错误
npm audit
显示漏洞
易受攻击的依赖项A06: 易受攻击的组件关键-低(视情况而定)
fetch(userProvidedUrl)
未经过验证
SSRF漏洞A10: SSRF
缺失安全头(CSP、HSTS)缺失安全头A05: 安全配置错误
连续用户ID未经过所有权检查IDOR漏洞A01: 访问控制失效
生产环境中
CORS: *
宽松的CORS策略A05: 安全配置错误
缺失
process.env.NODE_ENV !== 'production'
检查
生产环境使用开发模式A05: 安全配置错误中-低
如何使用此表:
  1. 从代码审阅中识别模式
  2. 在“如果发现...”列中找到匹配的行
  3. 记录OWASP分类和典型严重程度
  4. 跳转到阶段3中对应的安全类别
  5. 加载该类别的必填参考文件