mcpField
P
production-code-audit

production-code-audit

github.com/davila7测试与质量33.0k351 次安装1 天前更新
代码仓库

关于 production-code-audit

这项代码审计 Skill 会扫描代码库中的架构、安全、性能、质量、测试和生产就绪问题,并尝试修复与验证。它面向准备部署项目或检查代码库状况的开发者。

主要功能

  1. 01识别项目结构与技术栈
  2. 02检查安全和架构问题
  3. 03排查性能与代码质量
  4. 04发现测试及生产就绪缺口
  5. 05尝试修复并运行测试
  6. 06生成审计报告

适用场景

  1. 01为代码库准备生产部署
  2. 02检查安全与性能风险
  3. 03发现测试和基础设施缺口

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/davila7/claude-code-templates --skill production-code-audit

安装后在 Claude Code 中输入/production-code-audit确认已加载。

详细介绍

生产代码审计

概述

自主分析整个代码库,了解其架构、模式和用途,然后系统地将其改造为达到生产级、企业级专业标准的代码。本技能会逐行深入扫描,找出安全性、性能、架构和质量方面的所有问题,并提供全面的修复方案,以满足企业标准。

何时使用此技能

  • 用户说“让它达到生产就绪状态”时使用
  • 用户说“审计我的代码库”时使用
  • 用户说“让它更专业/达到企业级标准”时使用
  • 用户说“全面优化”时使用
  • 用户希望达到企业级质量时使用
  • 准备部署到生产环境时使用
  • 代码需要符合企业标准时使用

工作原理

步骤 1:自主发现代码库

自动扫描并了解整个代码库:

  1. 读取所有文件 - 递归扫描项目中的每个文件
  2. 识别技术栈 - 检测语言、框架、数据库和工具
  3. 了解架构 - 梳理结构、模式和依赖关系
  4. 识别用途 - 了解应用程序的功能
  5. 查找入口点 - 定位主文件、路由和控制器
  6. 梳理数据流 - 了解数据在系统中的流转方式

自动执行,无需询问用户。

步骤 2:全面检测问题

逐行扫描所有问题:

架构问题:

  • 循环依赖
  • 耦合过紧
  • 上帝类(超过 500 行或超过 20 个方法)
  • 缺少关注点分离
  • 模块边界不清晰
  • 违反设计模式

安全漏洞:

  • SQL 注入(在查询中拼接字符串)
  • XSS 漏洞(未转义输出)
  • 硬编码机密(代码中的 API 密钥、密码)
  • 缺少身份验证/授权
  • 密码哈希强度弱(MD5、SHA1)
  • 缺少输入验证
  • CSRF 漏洞
  • 不安全的依赖项

性能问题:

  • N+1 查询问题
  • 缺少数据库索引
  • 应采用异步执行的同步操作
  • 缺少缓存
  • 算法效率低(O(n²) 或更差)
  • 构建包体积过大
  • 图像未优化
  • 内存泄漏

代码质量问题:

  • 圈复杂度高(超过 10)
  • 代码重复
  • 魔法数字
  • 命名规范不佳
  • 缺少错误处理
  • 格式不一致
  • 死代码
  • TODO/FIXME 注释

测试缺口:

  • 关键路径缺少测试
  • 测试覆盖率低(低于 80%)
  • 未测试边界情况
  • 不稳定的测试
  • 缺少集成测试

生产就绪情况:

  • 缺少环境变量
  • 没有日志记录/监控
  • 没有错误追踪
  • 缺少健康检查
  • 文档不完整
  • 没有 CI/CD 流水线
步骤 3:自动修复和优化

自动修复所有问题:

  1. 重构架构 - 拆分上帝类,修复循环依赖
  2. 修复安全问题 - 使用参数化查询,移除机密,添加验证
  3. 优化性能 - 修复 N+1 查询,添加缓存,优化算法
  4. 改进代码质量 - 降低复杂度,消除重复,改进命名
  5. 补充缺失的测试 - 为尚未测试的关键路径编写测试
  6. 添加生产基础设施 - 日志记录、监控、健康检查
  7. 全面优化 - 构建包体积、图像、数据库查询
  8. 添加文档 - README、API 文档、架构文档
步骤 4:验证并报告

完成所有更改后:

  1. 运行所有测试,确保没有引入问题
  2. 验证所有安全问题均已修复
  3. 衡量性能提升
  4. 生成全面报告
  5. 提供更改前后的指标

示例

示例 1:自主改造代码库
User: @production-code-audit make this production-ready

AI: I'll scan your entire codebase and transform it to production-grade quality.

**Phase 1: Discovering Codebase** (analyzing 247 files)
- Detected: Node.js + Express + PostgreSQL + React
- Architecture: MVC pattern with REST API
- Purpose: E-commerce platform
- Entry points: server.js, src/index.tsx

**Phase 2: Scanning for Issues** (line-by-line analysis)

Found 127 issues:
- 🔴 CRITICAL: 8 issues
- 🟠 HIGH: 23 issues  
- 🟡 MEDIUM: 41 issues
- 🔵 LOW: 55 issues

**Phase 3: Fixing Issues Automatically**

🔴 CRITICAL FIXES (8/8 completed):

1. ✅ Fixed SQL injection in UserRepository.findByEmail()
   - Before: String concatenation in query
   - After: Parameterized query with $1 placeholder

2. ✅ Removed hardcoded database password from config/database.ts
   - Before: password: 'SuperSecret123!'
   - After: password: process.env.DB_PASSWORD

3. ✅ Added authentication to admin routes
   - Before: No auth middleware
   - After: authenticateToken + requireRole('admin')

4. ✅ Fixed weak password hashing (MD5 → bcrypt)
   - Before: crypto.createHash('md5')
   - After: bcrypt.hash(password, 12)

5. ✅ Fixed circular dependency: OrderService ↔ PaymentService
   - Before: Direct imports causing cycle
   - After: Event-based decoupling with EventBus

6. ✅ Added input validation to all API endpoints
   - Before: No validation
   - After: Zod schemas validating all inputs

7. ✅ Fixed authentication bypass in auth middleware
   - Before: next() called on missing token
   - After: Returns 401 error

8. ✅ Fixed mass assignment vulnerability in UserController
   - Before: Accepts all fields from req.body
   - After: Whitelist of allowed fields only

🟠 HIGH PRIORITY FIXES (23/23 completed):

9. ✅ Fixed N+1 query in OrderService.getOrdersWithItems()
   - Before: Loop with individual queries (2.8s)
   - After: Single query with joins (45ms)
   - Performance: 98% improvement

10. ✅ Refactored UserService god class (850 lines → 4 focused services)
    - UserAuthenticationService (login, logout, password)
    - UserProfileService (CRUD operations)
    - UserNotificationService (email, SMS)
    - UserPermissionService (roles, permissions)

11. ✅ Added Redis caching for product queries
    - Before: Database query every request
    - After: Cache with 1-hour TTL
    - Performance: 95% faster

12. ✅ Optimized bundle size
    - Before: 850KB (gzipped: 280KB)
    - After: 380KB (gzipped: 120KB)
    - Improvement: 55% reduction

13. ✅ Added database indexes
    - orders(user_id, status, created_at)
    - products(category, price)
    - Query performance: 98% improvement

[... 11 more high-priority fixes ...]

🟡 MEDIUM PRIORITY FIXES (41/41 completed):
[... all medium fixes ...]

🔵 LOW PRIORITY IMPROVEMENTS (55/55 completed):
[... all low improvements ...]

**Phase 4: Adding Production Infrastructure**

✅ Added structured logging (Winston)
✅ Added error tracking (Sentry)
✅ Added health check endpoints (/health, /ready)
✅ Added monitoring (Prometheus metrics)
✅ Added rate limiting (Redis-based)
✅ Added API documentation (Swagger/OpenAPI)
✅ Added comprehensive README
✅ Added deployment guide
✅ Added CI/CD pipeline (.github/workflows)

**Phase 5: Verification**

✅ All tests passing (1,247 tests)
✅ Test coverage: 42% → 87%
✅ Security scan: 0 vulnerabilities
✅ Performance: API response time 3.2s → 180ms
✅ Bundle size: 850KB → 380KB
✅ Lighthouse score: 62 → 94

**TRANSFORMATION COMPLETE**

Your codebase is now production-ready with enterprise-grade quality:

📊 Metrics:
- Issues fixed: 127/127 (100%)
- Test coverage: 87% (target: 80%+)
- API performance: 94% improvement
- Security: OWASP Top 10 compliant
- Code quality: Grade A-

📁 Files changed: 89 files
📝 Lines changed: +3,247 / -1,892

🚀 Ready for production deployment!
示例 2:自动强化安全性
User: @production-code-audit secure this codebase

AI: Scanning for security vulnerabilities...

**Security Scan Complete**

Found 15 security issues:
- 🔴 CRITICAL: 5
- 🟠 HIGH: 7
- 🟡 MEDIUM: 3

**Fixing all security issues automatically...**

🔴 CRITICAL (5/5 fixed):

1. ✅ SQL Injection in UserRepository
\`\`\`typescript
// Before (VULNERABLE)
const query = \`SELECT * FROM users WHERE email = '\${email}'\`;

// After (SECURE)
const query = 'SELECT * FROM users WHERE email = $1';
await db.query(query, [email]);
\`\`\`

2. ✅ Hardcoded Secrets Removed
\`\`\`typescript
// Before (INSECURE)
const JWT_SECRET = 'my-secret-key-123';

// After (SECURE)
const JWT_SECRET = process.env.JWT_SECRET;
if (!JWT_SECRET) throw new Error('JWT_SECRET required');
\`\`\`

3. ✅ Authentication Added to Admin Routes
\`\`\`typescript
// Before (VULNERABLE)
router.delete('/api/admin/users/:id', deleteUser);

// After (SECURE)
router.delete('/api/admin/users/:id',
  authenticateToken,
  requireRole('admin'),
  deleteUser
);
\`\`\`

4. ✅ Password Hashing Upgraded
\`\`\`typescript
// Before (WEAK)
const hash = crypto.createHash('md5').update(password).digest('hex');

// After (STRONG)
const hash = await bcrypt.hash(password, 12);
\`\`\`

5. ✅ Input Validation Added
\`\`\`typescript
// Before (VULNERABLE)
const user = await db.user.create({ data: req.body });

// After (SECURE)
const schema = z.object({
  email: z.string().email(),
  password: z.string().min(12),
  name: z.string().min(2).max(100)
});
const validated = schema.parse(req.body);
const user = await db.user.create({ data: validated });
\`\`\`

**Security Status:**
- ✅ OWASP Top 10: Compliant
- ✅ SQL Injection: Protected
- ✅ XSS: Protected
- ✅ CSRF: Protected
- ✅ Authentication: Secure
- ✅ Secrets: Environment variables
- ✅ Dependencies: No vulnerabilities

🔒 Codebase is now secure and production-ready!
示例 3:性能优化
User: @production-code-audit optimize performance

AI: Analyzing performance bottlenecks...

**Performance Analysis Complete**

Current metrics:
- API response time: 3.2s (target: <200ms)
- Page load time: 8.5s (target: <2s)
- Bundle size: 850KB (target: <200KB)

**Optimizing automatically...**

✅ Fixed N+1 queries (3.2s → 180ms - 94% faster)
✅ Added Redis caching (95% cache hit rate)
✅ Optimized database indexes (98% faster queries)
✅ Reduced bundle size (850KB → 380KB - 55% smaller)
✅ Optimized images (28MB → 3.2MB - 89% smaller)
✅ Implemented code splitting
✅ Added lazy loading
✅ Parallelized async operations

**Performance Results:**

| Metric | Before | After | Improvement |
|--------|--------|-------|-------------|
| API Response | 3.2s | 180ms | 94% |
| Page Load | 8.5s | 1.8s | 79% |
| Bundle Size | 850KB | 380KB | 55% |
| Image Size | 28MB | 3.2MB | 89% |
| Lighthouse | 42 | 94 | +52 points |

🚀 Performance optimized to production standards!

最佳实践

✅ 应该这样做
  • 扫描所有内容 - 阅读所有文件,了解整个代码库
  • 自动修复 - 不要只报告问题,要实际修复
  • 优先处理关键问题 - 首先处理安全和数据丢失问题
  • 衡量影响 - 展示改进前后的指标
  • 验证更改 - 修改后运行测试
  • 全面检查 - 涵盖架构、安全、性能和测试
  • 全面优化 - 优化打包体积、查询、算法和图片
  • 完善基础设施 - 添加日志记录、监控和错误跟踪
  • 记录更改 - 说明修复了什么以及原因
❌ 不要这样做
  • 不要提问 - 自主了解代码库
  • 不要等待指示 - 自动扫描并修复
  • 不要只做报告 - 要实际修复问题
  • 不要漏掉文件 - 扫描项目中的每个文件
  • 不要忽略上下文 - 了解代码的作用
  • 不要破坏功能 - 验证测试通过后再完成更改
  • 不要只做一部分 - 修复所有问题,而不只是其中一些

自主扫描说明

调用此技能时,请自动执行以下操作:

  1. 发现代码库:

    • 使用 listDirectory 递归查找所有文件
    • 使用 readFile 阅读每个源文件
    • 根据 package.json、requirements.txt 等识别技术栈
    • 梳理架构和结构
  2. 逐行扫描问题:

    • 检查每一行是否存在安全漏洞
    • 找出性能瓶颈
    • 发现代码质量问题
    • 检测架构问题
    • 找出缺失的测试
  3. 自动修复所有问题:

    • 使用 strReplace 修复文件中的问题
    • 添加缺失的文件(测试、配置、文档)
    • 重构有问题的代码
    • 添加生产环境基础设施
    • 优化性能
  4. 验证并报告:

    • 运行测试,确保没有破坏任何功能
    • 衡量改进效果
    • 生成全面的报告
    • 展示改进前后的指标

所有这些都要在不向用户征求意见的情况下完成。

常见陷阱

问题:问题太多

表现: 团队被 200 多个问题压得无从下手
解决方案: 只关注关键和高优先级问题,并规划迭代

问题:误报

表现: 将并非问题的内容标记为问题
解决方案: 结合上下文理解、手动验证并询问开发人员

问题:没有后续跟进

表现: 审计报告被忽略
解决方案: 创建 GitHub issue、分配负责人,并在站会中跟踪

生产环境审计清单

安全
  • 不存在 SQL 注入漏洞
  • 不存在硬编码的密钥
  • 受保护的路由均已启用身份验证
  • 已实施授权检查
  • 所有端点均已进行输入验证
  • 使用 bcrypt 进行密码哈希(10 轮以上)
  • 强制使用 HTTPS
  • 依赖项不存在漏洞
性能
  • 不存在 N+1 查询问题
  • 外键均已建立数据库索引
  • 已实施缓存
  • API 响应时间 < 200ms
  • 打包体积 < 200KB(gzip 压缩后)
测试
  • 测试覆盖率 > 80%
  • 已测试关键路径
  • 已覆盖边界情况
  • 不存在不稳定的测试
  • 在 CI/CD 中运行测试
生产就绪情况
  • 已配置环境变量
  • 已设置错误跟踪(Sentry)
  • 已实施结构化日志记录
  • 已提供健康检查端点
  • 已配置监控和告警
  • 文档完整

审计报告模板

# Production Audit Report

**Project:** [Name]
**Date:** [Date]
**Overall Grade:** [A-F]

## Executive Summary
[2-3 sentences on overall status]

**Critical Issues:** [count]
**High Priority:** [count]
**Recommendation:** [Fix timeline]

## Findings by Category

### Architecture (Grade: [A-F])
- Issue 1: [Description]
- Issue 2: [Description]

### Security (Grade: [A-F])
- Issue 1: [Description + Fix]
- Issue 2: [Description + Fix]

### Performance (Grade: [A-F])
- Issue 1: [Description + Fix]

### Testing (Grade: [A-F])
- Coverage: [%]
- Issues: [List]

## Priority Actions
1. [Critical issue] - [Timeline]
2. [High priority] - [Timeline]
3. [High priority] - [Timeline]

## Timeline
- Critical fixes: [X weeks]
- High priority: [X weeks]
- Production ready: [X weeks]

相关技能

  • @code-review-checklist - 代码审查指南
  • @api-security-best-practices - API 安全模式
  • @web-performance-optimization - 性能优化
  • @systematic-debugging - 调试生产环境问题
  • @senior-architect - 架构模式

补充资源


专业提示: 定期安排审核(每季度一次),以保持代码质量。预防问题比修复生产环境中的 Bug 成本更低!

评论

支持 Markdown