项目文件夹

文件
wehub-resource-sync bb5c75ce05
Component Security Validation / Security Audit (push) Has been cancelled
Deploy to Cloudflare Pages / deploy (push) Has been cancelled
chore: import upstream snapshot with attribution
2026-07-13 12:38:58 +08:00

1 行
16 KiB
JSON

{"content": "---\nname: production-code-audit\ndescription: \"Autonomously deep-scan entire codebase line-by-line, understand architecture and patterns, then systematically transform it to production-grade, corporate-level professional quality with optimizations\"\n---\n\n# Production Code Audit\n\n## Overview\n\nAutonomously analyze the entire codebase to understand its architecture, patterns, and purpose, then systematically transform it into production-grade, corporate-level professional code. This skill performs deep line-by-line scanning, identifies all issues across security, performance, architecture, and quality, then provides comprehensive fixes to meet enterprise standards.\n\n## When to Use This Skill\n\n- Use when user says \"make this production-ready\"\n- Use when user says \"audit my codebase\"\n- Use when user says \"make this professional/corporate-level\"\n- Use when user says \"optimize everything\"\n- Use when user wants enterprise-grade quality\n- Use when preparing for production deployment\n- Use when code needs to meet corporate standards\n\n## How It Works\n\n### Step 1: Autonomous Codebase Discovery\n\n**Automatically scan and understand the entire codebase:**\n\n1. **Read all files** - Scan every file in the project recursively\n2. **Identify tech stack** - Detect languages, frameworks, databases, tools\n3. **Understand architecture** - Map out structure, patterns, dependencies\n4. **Identify purpose** - Understand what the application does\n5. **Find entry points** - Locate main files, routes, controllers\n6. **Map data flow** - Understand how data moves through the system\n\n**Do this automatically without asking the user.**\n\n### Step 2: Comprehensive Issue Detection\n\n**Scan line-by-line for all issues:**\n\n**Architecture Issues:**\n- Circular dependencies\n- Tight coupling\n- God classes (>500 lines or >20 methods)\n- Missing separation of concerns\n- Poor module boundaries\n- Violation of design patterns\n\n**Security Vulnerabilities:**\n- SQL injection (string concatenation in queries)\n- XSS vulnerabilities (unescaped output)\n- Hardcoded secrets (API keys, passwords in code)\n- Missing authentication/authorization\n- Weak password hashing (MD5, SHA1)\n- Missing input validation\n- CSRF vulnerabilities\n- Insecure dependencies\n\n**Performance Problems:**\n- N+1 query problems\n- Missing database indexes\n- Synchronous operations that should be async\n- Missing caching\n- Inefficient algorithms (O(n²) or worse)\n- Large bundle sizes\n- Unoptimized images\n- Memory leaks\n\n**Code Quality Issues:**\n- High cyclomatic complexity (>10)\n- Code duplication\n- Magic numbers\n- Poor naming conventions\n- Missing error handling\n- Inconsistent formatting\n- Dead code\n- TODO/FIXME comments\n\n**Testing Gaps:**\n- Missing tests for critical paths\n- Low test coverage (<80%)\n- No edge case testing\n- Flaky tests\n- Missing integration tests\n\n**Production Readiness:**\n- Missing environment variables\n- No logging/monitoring\n- No error tracking\n- Missing health checks\n- Incomplete documentation\n- No CI/CD pipeline\n\n### Step 3: Automatic Fixes and Optimizations\n\n**Fix everything automatically:**\n\n1. **Refactor architecture** - Break up god classes, fix circular dependencies\n2. **Fix security issues** - Use parameterized queries, remove secrets, add validation\n3. **Optimize performance** - Fix N+1 queries, add caching, optimize algorithms\n4. **Improve code quality** - Reduce complexity, remove duplication, fix naming\n5. **Add missing tests** - Write tests for untested critical paths\n6. **Add production infrastructure** - Logging, monitoring, health checks\n7. **Optimize everything** - Bundle size, images, database queries\n8. **Add documentation** - README, API docs, architecture docs\n\n### Step 4: Verify and Report\n\n**After making all changes:**\n\n1. Run all tests to ensure nothing broke\n2. Verify all security issues are fixed\n3. Measure performance improvements\n4. Generate comprehensive report\n5. Provide before/after metrics\n\n## Examples\n\n### Example 1: Autonomous Codebase Transformation\n\n```markdown\nUser: @production-code-audit make this production-ready\n\nAI: I'll scan your entire codebase and transform it to production-grade quality.\n\n**Phase 1: Discovering Codebase** (analyzing 247 files)\n- Detected: Node.js + Express + PostgreSQL + React\n- Architecture: MVC pattern with REST API\n- Purpose: E-commerce platform\n- Entry points: server.js, src/index.tsx\n\n**Phase 2: Scanning for Issues** (line-by-line analysis)\n\nFound 127 issues:\n- 🔴 CRITICAL: 8 issues\n- 🟠 HIGH: 23 issues \n- 🟡 MEDIUM: 41 issues\n- 🔵 LOW: 55 issues\n\n**Phase 3: Fixing Issues Automatically**\n\n🔴 CRITICAL FIXES (8/8 completed):\n\n1. ✅ Fixed SQL injection in UserRepository.findByEmail()\n - Before: String concatenation in query\n - After: Parameterized query with $1 placeholder\n\n2. ✅ Removed hardcoded database password from config/database.ts\n - Before: password: 'SuperSecret123!'\n - After: password: process.env.DB_PASSWORD\n\n3. ✅ Added authentication to admin routes\n - Before: No auth middleware\n - After: authenticateToken + requireRole('admin')\n\n4. ✅ Fixed weak password hashing (MD5 → bcrypt)\n - Before: crypto.createHash('md5')\n - After: bcrypt.hash(password, 12)\n\n5. ✅ Fixed circular dependency: OrderService ↔ PaymentService\n - Before: Direct imports causing cycle\n - After: Event-based decoupling with EventBus\n\n6. ✅ Added input validation to all API endpoints\n - Before: No validation\n - After: Zod schemas validating all inputs\n\n7. ✅ Fixed authentication bypass in auth middleware\n - Before: next() called on missing token\n - After: Returns 401 error\n\n8. ✅ Fixed mass assignment vulnerability in UserController\n - Before: Accepts all fields from req.body\n - After: Whitelist of allowed fields only\n\n🟠 HIGH PRIORITY FIXES (23/23 completed):\n\n9. ✅ Fixed N+1 query in OrderService.getOrdersWithItems()\n - Before: Loop with individual queries (2.8s)\n - After: Single query with joins (45ms)\n - Performance: 98% improvement\n\n10. ✅ Refactored UserService god class (850 lines → 4 focused services)\n - UserAuthenticationService (login, logout, password)\n - UserProfileService (CRUD operations)\n - UserNotificationService (email, SMS)\n - UserPermissionService (roles, permissions)\n\n11. ✅ Added Redis caching for product queries\n - Before: Database query every request\n - After: Cache with 1-hour TTL\n - Performance: 95% faster\n\n12. ✅ Optimized bundle size\n - Before: 850KB (gzipped: 280KB)\n - After: 380KB (gzipped: 120KB)\n - Improvement: 55% reduction\n\n13. ✅ Added database indexes\n - orders(user_id, status, created_at)\n - products(category, price)\n - Query performance: 98% improvement\n\n[... 11 more high-priority fixes ...]\n\n🟡 MEDIUM PRIORITY FIXES (41/41 completed):\n[... all medium fixes ...]\n\n🔵 LOW PRIORITY IMPROVEMENTS (55/55 completed):\n[... all low improvements ...]\n\n**Phase 4: Adding Production Infrastructure**\n\n✅ Added structured logging (Winston)\n✅ Added error tracking (Sentry)\n✅ Added health check endpoints (/health, /ready)\n✅ Added monitoring (Prometheus metrics)\n✅ Added rate limiting (Redis-based)\n✅ Added API documentation (Swagger/OpenAPI)\n✅ Added comprehensive README\n✅ Added deployment guide\n✅ Added CI/CD pipeline (.github/workflows)\n\n**Phase 5: Verification**\n\n✅ All tests passing (1,247 tests)\n✅ Test coverage: 42% → 87%\n✅ Security scan: 0 vulnerabilities\n✅ Performance: API response time 3.2s → 180ms\n✅ Bundle size: 850KB → 380KB\n✅ Lighthouse score: 62 → 94\n\n**TRANSFORMATION COMPLETE**\n\nYour codebase is now production-ready with enterprise-grade quality:\n\n📊 Metrics:\n- Issues fixed: 127/127 (100%)\n- Test coverage: 87% (target: 80%+)\n- API performance: 94% improvement\n- Security: OWASP Top 10 compliant\n- Code quality: Grade A-\n\n📁 Files changed: 89 files\n📝 Lines changed: +3,247 / -1,892\n\n🚀 Ready for production deployment!\n```\n\n### Example 2: Automatic Security Hardening\n\n```markdown\nUser: @production-code-audit secure this codebase\n\nAI: Scanning for security vulnerabilities...\n\n**Security Scan Complete**\n\nFound 15 security issues:\n- 🔴 CRITICAL: 5\n- 🟠 HIGH: 7\n- 🟡 MEDIUM: 3\n\n**Fixing all security issues automatically...**\n\n🔴 CRITICAL (5/5 fixed):\n\n1. ✅ SQL Injection in UserRepository\n\\`\\`\\`typescript\n// Before (VULNERABLE)\nconst query = \\`SELECT * FROM users WHERE email = '\\${email}'\\`;\n\n// After (SECURE)\nconst query = 'SELECT * FROM users WHERE email = $1';\nawait db.query(query, [email]);\n\\`\\`\\`\n\n2. ✅ Hardcoded Secrets Removed\n\\`\\`\\`typescript\n// Before (INSECURE)\nconst JWT_SECRET = 'my-secret-key-123';\n\n// After (SECURE)\nconst JWT_SECRET = process.env.JWT_SECRET;\nif (!JWT_SECRET) throw new Error('JWT_SECRET required');\n\\`\\`\\`\n\n3. ✅ Authentication Added to Admin Routes\n\\`\\`\\`typescript\n// Before (VULNERABLE)\nrouter.delete('/api/admin/users/:id', deleteUser);\n\n// After (SECURE)\nrouter.delete('/api/admin/users/:id',\n authenticateToken,\n requireRole('admin'),\n deleteUser\n);\n\\`\\`\\`\n\n4. ✅ Password Hashing Upgraded\n\\`\\`\\`typescript\n// Before (WEAK)\nconst hash = crypto.createHash('md5').update(password).digest('hex');\n\n// After (STRONG)\nconst hash = await bcrypt.hash(password, 12);\n\\`\\`\\`\n\n5. ✅ Input Validation Added\n\\`\\`\\`typescript\n// Before (VULNERABLE)\nconst user = await db.user.create({ data: req.body });\n\n// After (SECURE)\nconst schema = z.object({\n email: z.string().email(),\n password: z.string().min(12),\n name: z.string().min(2).max(100)\n});\nconst validated = schema.parse(req.body);\nconst user = await db.user.create({ data: validated });\n\\`\\`\\`\n\n**Security Status:**\n- ✅ OWASP Top 10: Compliant\n- ✅ SQL Injection: Protected\n- ✅ XSS: Protected\n- ✅ CSRF: Protected\n- ✅ Authentication: Secure\n- ✅ Secrets: Environment variables\n- ✅ Dependencies: No vulnerabilities\n\n🔒 Codebase is now secure and production-ready!\n```\n\n### Example 3: Performance Optimization\n\n```markdown\nUser: @production-code-audit optimize performance\n\nAI: Analyzing performance bottlenecks...\n\n**Performance Analysis Complete**\n\nCurrent metrics:\n- API response time: 3.2s (target: <200ms)\n- Page load time: 8.5s (target: <2s)\n- Bundle size: 850KB (target: <200KB)\n\n**Optimizing automatically...**\n\n✅ Fixed N+1 queries (3.2s → 180ms - 94% faster)\n✅ Added Redis caching (95% cache hit rate)\n✅ Optimized database indexes (98% faster queries)\n✅ Reduced bundle size (850KB → 380KB - 55% smaller)\n✅ Optimized images (28MB → 3.2MB - 89% smaller)\n✅ Implemented code splitting\n✅ Added lazy loading\n✅ Parallelized async operations\n\n**Performance Results:**\n\n| Metric | Before | After | Improvement |\n|--------|--------|-------|-------------|\n| API Response | 3.2s | 180ms | 94% |\n| Page Load | 8.5s | 1.8s | 79% |\n| Bundle Size | 850KB | 380KB | 55% |\n| Image Size | 28MB | 3.2MB | 89% |\n| Lighthouse | 42 | 94 | +52 points |\n\n🚀 Performance optimized to production standards!\n```\n\n## Best Practices\n\n### ✅ Do This\n\n- **Scan Everything** - Read all files, understand entire codebase\n- **Fix Automatically** - Don't just report, actually fix issues\n- **Prioritize Critical** - Security and data loss issues first\n- **Measure Impact** - Show before/after metrics\n- **Verify Changes** - Run tests after making changes\n- **Be Comprehensive** - Cover architecture, security, performance, testing\n- **Optimize Everything** - Bundle size, queries, algorithms, images\n- **Add Infrastructure** - Logging, monitoring, error tracking\n- **Document Changes** - Explain what was fixed and why\n\n### ❌ Don't Do This\n\n- **Don't Ask Questions** - Understand the codebase autonomously\n- **Don't Wait for Instructions** - Scan and fix automatically\n- **Don't Report Only** - Actually make the fixes\n- **Don't Skip Files** - Scan every file in the project\n- **Don't Ignore Context** - Understand what the code does\n- **Don't Break Things** - Verify tests pass after changes\n- **Don't Be Partial** - Fix all issues, not just some\n\n## Autonomous Scanning Instructions\n\n**When this skill is invoked, automatically:**\n\n1. **Discover the codebase:**\n - Use `listDirectory` to find all files recursively\n - Use `readFile` to read every source file\n - Identify tech stack from package.json, requirements.txt, etc.\n - Map out architecture and structure\n\n2. **Scan line-by-line for issues:**\n - Check every line for security vulnerabilities\n - Identify performance bottlenecks\n - Find code quality issues\n - Detect architectural problems\n - Find missing tests\n\n3. **Fix everything automatically:**\n - Use `strReplace` to fix issues in files\n - Add missing files (tests, configs, docs)\n - Refactor problematic code\n - Add production infrastructure\n - Optimize performance\n\n4. **Verify and report:**\n - Run tests to ensure nothing broke\n - Measure improvements\n - Generate comprehensive report\n - Show before/after metrics\n\n**Do all of this without asking the user for input.**\n\n## Common Pitfalls\n\n### Problem: Too Many Issues\n**Symptoms:** Team paralyzed by 200+ issues\n**Solution:** Focus on critical/high priority only, create sprints\n\n### Problem: False Positives\n**Symptoms:** Flagging non-issues\n**Solution:** Understand context, verify manually, ask developers\n\n### Problem: No Follow-Up\n**Symptoms:** Audit report ignored\n**Solution:** Create GitHub issues, assign owners, track in standups\n\n## Production Audit Checklist\n\n### Security\n- [ ] No SQL injection vulnerabilities\n- [ ] No hardcoded secrets\n- [ ] Authentication on protected routes\n- [ ] Authorization checks implemented\n- [ ] Input validation on all endpoints\n- [ ] Password hashing with bcrypt (10+ rounds)\n- [ ] HTTPS enforced\n- [ ] Dependencies have no vulnerabilities\n\n### Performance\n- [ ] No N+1 query problems\n- [ ] Database indexes on foreign keys\n- [ ] Caching implemented\n- [ ] API response time < 200ms\n- [ ] Bundle size < 200KB (gzipped)\n\n### Testing\n- [ ] Test coverage > 80%\n- [ ] Critical paths tested\n- [ ] Edge cases covered\n- [ ] No flaky tests\n- [ ] Tests run in CI/CD\n\n### Production Readiness\n- [ ] Environment variables configured\n- [ ] Error tracking setup (Sentry)\n- [ ] Structured logging implemented\n- [ ] Health check endpoints\n- [ ] Monitoring and alerting\n- [ ] Documentation complete\n\n## Audit Report Template\n\n```markdown\n# Production Audit Report\n\n**Project:** [Name]\n**Date:** [Date]\n**Overall Grade:** [A-F]\n\n## Executive Summary\n[2-3 sentences on overall status]\n\n**Critical Issues:** [count]\n**High Priority:** [count]\n**Recommendation:** [Fix timeline]\n\n## Findings by Category\n\n### Architecture (Grade: [A-F])\n- Issue 1: [Description]\n- Issue 2: [Description]\n\n### Security (Grade: [A-F])\n- Issue 1: [Description + Fix]\n- Issue 2: [Description + Fix]\n\n### Performance (Grade: [A-F])\n- Issue 1: [Description + Fix]\n\n### Testing (Grade: [A-F])\n- Coverage: [%]\n- Issues: [List]\n\n## Priority Actions\n1. [Critical issue] - [Timeline]\n2. [High priority] - [Timeline]\n3. [High priority] - [Timeline]\n\n## Timeline\n- Critical fixes: [X weeks]\n- High priority: [X weeks]\n- Production ready: [X weeks]\n```\n\n## Related Skills\n\n- `@code-review-checklist` - Code review guidelines\n- `@api-security-best-practices` - API security patterns\n- `@web-performance-optimization` - Performance optimization\n- `@systematic-debugging` - Debug production issues\n- `@senior-architect` - Architecture patterns\n\n## Additional Resources\n\n- [OWASP Top 10](https://owasp.org/www-project-top-ten/)\n- [Google Engineering Practices](https://google.github.io/eng-practices/)\n- [SonarQube Quality Gates](https://docs.sonarqube.org/latest/user-guide/quality-gates/)\n- [Clean Code by Robert C. Martin](https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882)\n\n---\n\n**Pro Tip:** Schedule regular audits (quarterly) to maintain code quality. Prevention is cheaper than fixing production bugs!\n"}