--- name: code-inspector description: Senior Full-Stack Code Auditor - Especialista em Arquitetura, Segurança, Performance, Observabilidade e Qualidade de Software. Focado em Node.js/Express/MongoDB com expertise em sistemas multi-tenant SaaS. Use para auditorias profundas, análise de débito técnico, code review, troubleshooting avançado, refatoração estratégica ou otimização de sistemas. allowed-tools: Read, Grep, LS, Bash, Edit --- # Code Inspector Skill (Senior Full-Stack Edition) ## 🎯 Missão Garantir excelência técnica através de auditorias sistemáticas com visão holística: segurança, performance, manutenibilidade, observabilidade e resiliência. --- ## 1. 🔬 Framework de Auditoria (SPARC) ### S - Security (Segurança) ### P - Performance (Desempenho) ### A - Architecture (Arquitetura) ### R - Reliability (Confiabilidade) ### C - Code Quality (Qualidade) Toda auditoria deve cobrir essas 5 dimensões com scores de 1-5. --- ## 2. 🛡️ Security Deep Dive ### 2.1 OWASP Top 10 Checklist (Node.js/Express) | # | Vulnerabilidade | Regex/Busca | Severidade | Mitigação | |---|-----------------|-------------|------------|-----------| | A01 | Broken Access Control | Rotas sem middleware auth | 🔴 CRÍTICO | verificarAdmin, verificarParticipante | | A02 | Cryptographic Failures | md5, sha1 para senhas | 🔴 CRÍTICO | bcrypt com salt rounds >= 10 | | A03 | Injection | \$where, eval(), new Function | 🔴 CRÍTICO | Sanitização, prepared statements | | A04 | Insecure Design | Sem rate limiting em auth | 🟡 ALTO | express-rate-limit | | A05 | Security Misconfiguration | origin: '*', debug em prod | 🟡 ALTO | Helmet, CORS restrito | | A06 | Vulnerable Components | npm audit --json | 🟡 ALTO | Dependabot, audits regulares | | A07 | Auth Failures | Sessão sem httpOnly/secure | 🔴 CRÍTICO | Cookie flags corretas | | A08 | Data Integrity | Sem validação de schema | 🟡 MÉDIO | Joi, Zod, express-validator | | A09 | Logging Failures | Dados sensíveis em logs | 🟡 MÉDIO | Sanitizar PII | | A10 | SSRF | fetch com URL user-controlled | 🔴 CRÍTICO | Whitelist de URLs | ### 2.2 Análise de Autenticação/Autorização ```bash # Rotas POST/PUT/DELETE sem middleware de auth grep -rn "router\.\(post\|put\|delete\|patch\)" routes/ | grep -v "verificar" # Sessões sem flags de segurança grep -rn "cookie:" config/ | grep -v "httpOnly\|secure\|sameSite" # Secrets expostos grep -rn "password\s*[:=]\s*['\"][^'\"]*['\"]" --include="*.js" | grep -v "process\.env\|\.example" # JWT sem expiração grep -rn "jwt\.sign" --include="*.js" | grep -v "expiresIn" ``` ### 2.3 MongoDB Injection Patterns ```javascript // 🔴 VULNERÁVEL: Query operator injection const user = await User.findOne({ email: req.body.email }); // Se email = {"$gt": ""} // 🟢 SEGURO: Sanitização const email = String(req.body.email).toLowerCase().trim(); const user = await User.findOne({ email }); // 🔴 VULNERÁVEL: $where (executa JS no servidor) db.collection.find({ $where: "this.name == '" + userInput + "'" }); // 🟢 SEGURO: Usar operadores nativos db.collection.find({ name: sanitizedInput }); // 🔴 VULNERÁVEL: RegEx injection const regex = new RegExp(req.query.search); // Se search = ".*" // 🟢 SEGURO: Escape especial characters const escaped = req.query.search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); const regex = new RegExp(escaped, 'i'); ``` ### 2.4 Checklist de Segurança - Super Cartola | Item | Status | Arquivo de Referência | Script Validação | |------|--------|----------------------|------------------| | Rate limiting em login | ✓ | routes/admin-auth-routes.js | `grep -rn "rateLimit" routes/*auth*` | | CSRF protection | ✓ | index.js (csurf) | `grep -rn "csurf\|csrf" index.js` | | Helmet headers | ✓ | index.js | `grep -rn "helmet" index.js` | | Session segura | ✓ | config/replit-auth.js | `grep -rn "httpOnly.*secure" config/` | | Sanitização de inputs | ? | Controllers | `./scripts/audit_input_sanitization.sh` | | Multi-tenant isolation | 🔴 | Todas queries com liga_id | `./scripts/audit_multitenant.sh` | | Google OAuth tokens | ✓ | config/google-auth.js | `grep -rn "GOOGLE_CLIENT" config/` | | Admin vs Participante | ✓ | middleware/auth.js | `grep -rn "verificarAdmin\|verificarParticipante" middleware/` | ### 2.5 Scripts de Auditoria Automática Crie `/scripts/audit_security.sh`: ```bash #!/bin/bash echo "🔐 AUDITORIA DE SEGURANÇA - Super Cartola" echo "==========================================" echo "" # Rotas desprotegidas echo "🔴 ROTAS POST/PUT/DELETE SEM AUTH:" find routes/ -name "*.js" -exec grep -l "router\.\(post\|put\|delete\)" {} \; | while read file; do if ! grep -q "verificar" "$file"; then echo " ⚠️ $file" fi done echo "" # Queries sem liga_id echo "🔴 QUERIES SEM MULTI-TENANT ISOLATION:" grep -rn "\.find({" controllers/ routes/ | grep -v "liga_id\|ligaId" | head -10 echo "" # Console.logs em produção echo "🟡 CONSOLE.LOGS (remover em produção):" find controllers/ routes/ services/ -name "*.js" -exec grep -Hn "console\.log" {} \; | wc -l echo "" # Secrets hardcoded echo "🔴 SECRETS HARDCODED:" grep -rn "password\s*[:=]\s*['\"][^'\"]*['\"]" --include="*.js" | grep -v "process\.env\|\.example\|\.sample" | wc -l echo "" # npm audit echo "🟡 VULNERABILIDADES NPM:" npm audit --json 2>/dev/null | jq '.metadata | {vulnerabilities, totalDependencies}' ``` --- ## 3. ⚡ Performance Engineering ### 3.1 Database Performance #### N+1 Query Detection ```bash # Encontrar loops com queries grep -rn "for.*await\|forEach.*await\|\.map.*await" controllers/ --include="*.js" # Queries sem .lean() grep -rn "find\|findOne" controllers/ | grep -v "\.lean()" # Agregações complexas sem índices grep -rn "\.aggregate\|\.pipeline" controllers/ services/ ``` #### Otimizações MongoDB | Anti-Pattern | Impacto | Solução | Script Detecção | |--------------|---------|---------|-----------------| | N+1 Queries | 100x mais lento | \$in, \$lookup, bulk | `grep -rn "for.*await.*find"` | | Sem .lean() | 5x mais memória | Adicionar .lean() em reads | `grep "find.*{" \| grep -v "lean"` | | Sem índices | Scan completo | createIndex em campos filtrados | `mongo --eval "db.collection.getIndexes()"` | | Select * | I/O desnecessário | .select('campo1 campo2') | `grep "find.*{" \| grep -v "select"` | | Sort sem índice | In-memory sort | Índice composto incluindo sort | Ver explain plan | | Skip grande | Lento em paginação | Cursor-based pagination | `grep "skip.*[0-9]{3,}"` | | $where | Execução JS | Operadores nativos | `grep "\$where"` | | Regex sem âncora | Full scan | /^prefixo/ com índice | `grep "RegExp.*\$" \| grep -v "\\^"` | #### Query Analysis (Super Cartola Specific) ```javascript // Habilitar profiling temporário db.setProfilingLevel(1, { slowms: 100 }); // Ver queries lentas db.system.profile.find({ ns: /^super_cartola\./ }).sort({ ts: -1 }).limit(10); // Explain de query suspeita db.participantes.find({ liga_id: "684cb1c8af923da7c7df51de" }) .sort({ pontos_acumulados: -1 }) .explain("executionStats"); // Verificar uso de índices db.participantes.getIndexes(); db.rodadas.getIndexes(); db.financeiro.getIndexes(); ``` ### 3.2 Node.js Performance #### Event Loop Blocking ```bash # Operações síncronas que bloqueiam grep -rn "readFileSync\|writeFileSync\|execSync" --include="*.js" | grep -v "node_modules" # JSON.parse em payloads grandes sem stream grep -rn "JSON\.parse" controllers/ services/ # Loops síncronos pesados grep -rn "for.*length\|while.*true" --include="*.js" | grep -v "node_modules" ``` #### Memory Leaks Patterns ```javascript // 🔴 LEAK: Listeners acumulando emitter.on('event', handler); // Sem removeListener // 🔴 LEAK: Closures retendo referências const cache = {}; function process(data) { cache[data.id] = data; // Cresce infinitamente } // 🔴 LEAK: Timers não limpos setInterval(() => {}, 1000); // Sem clearInterval // 🔴 LEAK: Arrays crescendo indefinidamente global.requestLog = []; app.use((req, res, next) => { global.requestLog.push({ url: req.url, time: Date.now() }); next(); }); // 🟢 SOLUÇÃO: WeakMap para cache const cache = new WeakMap(); // 🟢 SOLUÇÃO: LRU Cache com limite const LRU = require('lru-cache'); const cache = new LRU({ max: 500 }); // 🟢 SOLUÇÃO: Circular buffer const requestLog = new CircularBuffer(1000); ``` ### 3.3 Frontend Performance (Super Cartola Mobile) | Métrica | Target | Como Medir | Arquivo Referência | |---------|--------|------------|-------------------| | FCP (First Contentful Paint) | < 1.8s | Lighthouse | participante-navigation.js | | LCP (Largest Contentful Paint) | < 2.5s | Lighthouse | index.html (splash screen) | | CLS (Cumulative Layout Shift) | < 0.1 | Lighthouse | Evitar height/width dinâmicos | | TTI (Time to Interactive) | < 3.8s | Lighthouse | Lazy load modules | | IndexedDB Read | < 50ms | Performance API | cache-manager.js | | API Response | < 200ms | Network tab | Todas routes | #### Checklist Frontend ```bash # Bundles grandes (>100KB) find public/js -name "*.js" -size +100k -exec ls -lh {} \; # Imagens não otimizadas (>200KB) find public/img -type f \( -name "*.png" -o -name "*.jpg" \) -size +200k # Scripts sem defer/async grep -rn "1KB) find public/ -name "*.html" -exec grep -l "style>" {} \; | while read f; do size=$(sed -n '/