--- name: security-check description: Comprehensive security audit for Node.js/PHP projects - dependency vulnerabilities, outdated packages, environment safety, type checking. Use before git commits. domain: Dev model: sonnet priority: high tags: - security - audit - vulnerabilities - npm - composer - mandatory --- # /security-check - Security Audit Pre-Commit Auditoria de segurança completa para projectos Node.js e PHP. **Obrigatória antes de commits** (Regra CLAUDE.md #47). --- ## Quando Usar ### OBRIGATÓRIO: - Antes de `git commit` - Antes de `git push` - Antes de criar Pull Request - Antes de deploy para produção ### RECOMENDADO: - Após `pnpm add ` (especialmente AI SDKs) - Semanalmente em projectos activos - Após actualizar dependências major --- ## Workflow Completo ### 1. Detectar Tipo de Projecto ```bash # Verificar package managers if [ -f "package.json" ]; then # Node.js detected MANAGER="pnpm" # ou npm/yarn elif [ -f "composer.json" ]; then # PHP detected MANAGER="composer" fi ``` ### 2. Dependency Security Audit **Node.js:** ```bash pnpm audit --json > ~/.claude-work/security-audit.json ``` **PHP:** ```bash composer audit --format=json > ~/.claude-work/security-audit.json ``` **Parse resultados:** - Contar: critical, high, moderate, low - Identificar se são directas ou transitivas - Listar pacotes afectados ### 3. Outdated Dependencies **Node.js:** ```bash pnpm outdated --json > ~/.claude-work/security-outdated.json ``` **Priorizar:** - AI SDKs: langchain, together-ai, @tavily/core, @langchain/core - Security packages: @auth/*, axios, form-data - Framework core: next, react, prisma ### 4. Environment Safety Check **Verificar ficheiros:** ```bash # Lista de ficheiros a verificar FILES=(.env .env.local .env.production .env.development) for file in "${FILES[@]}"; do if [ -f "$file" ]; then # Verificar se tem placeholders ou keys reais grep -E "(API_KEY|SECRET|TOKEN|PASSWORD)" "$file" fi done ``` **Validação:** - ✅ `API_KEY=placeholder` (safe) - ❌ `API_KEY=sk-proj-abc123...` (UNSAFE - real key) ### 5. Type Safety (se TypeScript) ```bash # Verificar se é TypeScript if [ -f "tsconfig.json" ]; then pnpm type # ou tsc --noEmit fi ``` ### 6. Análise de Risco AI SDKs **Padrões conhecidos:** | Pacote | Risco | Acção | |--------|-------|-------| | `langchain` | Alto | Verificar @langchain/core | | `together-ai` | Alto | form-data transitiva | | `@tavily/core` | Alto | axios transitiva | | `@platejs/ai` | Médio | lodash transitiva | **Workflow AI SDKs:** ```bash # 1. Verificar se @langchain/core está desactualizado pnpm list @langchain/core # 2. Se versão < 0.3.80 (vulnerável) pnpm add @langchain/core@latest # 3. Re-audit pnpm audit ``` ### 7. Gerar Relatório **Formato output:** ```markdown ## Security Audit Report **Status:** [✅ SAFE | ⚠️ ISSUES FOUND | ❌ CRITICAL] **Data:** YYYY-MM-DD HH:MM | Category | Status | |----------|--------| | Vulnerabilities | [N critical, M high, P moderate, Q low] | | Outdated Packages | N total (M major updates) | | Environment Safety | ✅ Placeholders only / ❌ Real keys found | | Type Safety | ✅ 0 errors / ❌ N errors | ### Vulnerabilities Detail #### Critical (N) - package@version (via path) - description - **Patched:** >=safe-version - **Action:** [Override | Update | Replace] #### High (M) [...] ### Outdated Packages (Priority) **AI SDKs:** - langchain: current → latest - @langchain/core: current → latest (SECURITY UPDATE) **Framework:** - next: current → latest ### Action Required **Priority 1 (Critical):** 1. [Acção específica] **Priority 2 (High):** 1. [Acção específica] **Priority 3 (Maintenance):** 1. [Acção específica] ### Safe to Commit? [✅ YES | ⚠️ YES (with documentation) | ❌ NO (fix critical first)] **If YES with documentation:** ``` git commit -m "feat: feature X Known vulnerabilities (will be resolved): - package@version (severity) - waiting for upstream update Mitigation: [explanation] " ``` **If NO:** Fix critical/high vulnerabilities first. See PROC-DEV-SEC-001 for guidance. ``` ### 8. Criar Flag ```bash touch ~/.claude-work/.last-security-audit ``` **Propósito:** Hook pre-git-commit verifica esta flag. Se existe e < 1h, permite commit. --- ## Recomendações Específicas ### Para Vulnerabilidades Transitivas **Exemplo: form-data via together-ai** ```json // package.json { "pnpm": { "overrides": { "form-data": ">=4.0.4" } } } ``` Depois: ```bash pnpm install pnpm audit # Verificar se resolveu ``` ### Para Dependências Incompatíveis **Exemplo: @langchain/core desactualizado** ```bash # langchain pina versão antiga # Solução: instalar como dependência explícita pnpm add @langchain/core@latest ``` ### Para Vulnerabilidades Críticas **Workflow:** 1. Verificar se há fix disponível 2. Se sim: actualizar 3. Se não: avaliar alternativas ao package 4. Se nenhuma: escalar para Security Compliance Specialist --- ## Output Examples ### Exemplo 1: Clean (0 vulnerabilities) ``` ## Security Audit Report **Status:** ✅ SAFE **Data:** 2026-02-14 03:00 | Category | Status | |----------|--------| | Vulnerabilities | 0 (all categories) ✅ | | Outdated Packages | 3 (1 major) | | Environment Safety | ✅ Placeholders only | | Type Safety | ✅ 0 errors | ### Outdated Packages **Framework:** - next: 16.1.6 → 16.2.0 (minor) **Action Required:** Optional - update at convenience ### Safe to Commit? ✅ **YES** - No security issues found Created flag: ~/.claude-work/.last-security-audit ``` ### Exemplo 2: Transitivas (precisa overrides) ``` ## Security Audit Report **Status:** ⚠️ ISSUES FOUND (transitivas) **Data:** 2026-02-14 03:00 | Category | Status | |----------|--------| | Vulnerabilities | 0 critical, 0 high, 2 moderate, 1 low | | Outdated Packages | 5 (2 major) | | Environment Safety | ✅ Placeholders only | | Type Safety | ✅ 0 errors | ### Vulnerabilities Detail #### Moderate (2) - lodash@4.17.21 (via @platejs/ai) - **Issue:** Prototype pollution - **Patched:** >=4.17.23 - **Action:** Override - undici@6.22.0 (via @platejs/juice → cheerio) - **Issue:** Resource exhaustion - **Patched:** >=6.23.0 - **Action:** Override #### Low (1) - cookie@0.6.0 (via @auth/core) - **Issue:** Out of bounds characters - **Patched:** >=0.7.0 - **Action:** Override ### Recommended Fix Add to package.json: ```json { "pnpm": { "overrides": { "lodash": ">=4.17.23", "undici": ">=6.23.0", "cookie": ">=0.7.0" } } } ``` Then run: `pnpm install && pnpm audit` ### Safe to Commit? ⚠️ **YES (with documentation)** Document in commit message: - 3 moderate/low vulnerabilities (all transitivas) - Fixed with pnpm.overrides ``` ### Exemplo 3: Critical (bloquear commit) ``` ## Security Audit Report **Status:** ❌ CRITICAL **Data:** 2026-02-14 03:00 | Category | Status | |----------|--------| | Vulnerabilities | 1 critical, 0 high, 0 moderate, 0 low | | Outdated Packages | 8 (3 major) | | Environment Safety | ✅ Placeholders only | | Type Safety | ✅ 0 errors | ### Vulnerabilities Detail #### Critical (1) - form-data@4.0.3 (via together-ai → @types/node-fetch) - **Issue:** Unsafe random function in boundary selection - **Patched:** >=4.0.4 - **Action:** Override OR replace together-ai ### Immediate Action Required **Option 1: Override (quick fix)** ```json { "pnpm": { "overrides": { "form-data": ">=4.0.4" } } } ``` **Option 2: Evaluate alternatives** - Check if together-ai is essential - Evaluate alternative AI SDKs - Contact Security Compliance Specialist ### Safe to Commit? ❌ **NO** - Fix critical vulnerability first DO NOT create flag. DO NOT commit. ``` --- ## Integration ### Com Hook pre-git-commit Hook verifica: ```bash ~/.claude-work/.last-security-audit ``` Se ficheiro existe e < 1h → permite commit Se não existe ou > 1h → **BLOQUEIA** commit ### Com /time ```bash # Workflow típico /time start 1446 # Tarefa Desk # ... fazer alterações ... /security-check # Antes de commit git commit /time stop ``` ### Com /worklog ```bash # No worklog, mencionar se audit foi executado /worklog # → Incluirá "Security audit: ✅ 0 vulnerabilities" ``` --- ## Escalação | Situação | Escalar Para | |----------|--------------| | Vulnerabilidades críticas não corrigíveis | Security Compliance Specialist | | Dúvidas sobre overrides | Development Lead | | Múltiplas vulnerabilidades altas | /security-check + manual review | | Alternativas a packages | Research Analyst | --- ## Referências - [CLAUDE.md Regra #47](/home/ealmeida/.claude/CLAUDE.md) - [PROC-DEV-SEC-001](/media/ealmeida/Dados/Hub/06-Operacoes/Procedimentos/D7-Tecnologia/Seguranca/PROC-DEV-SEC-001-Security-Audit.md) - [Agent dev-helper v2.1](/home/ealmeida/.claude/plugins/marketplaces/descomplicar-plugins/dev-tools/agents/dev-helper.md) - [NPM Audit](https://docs.npmjs.com/cli/v10/commands/npm-audit) - [PNPM Audit](https://pnpm.io/cli/audit) - [Composer Audit](https://getcomposer.org/doc/03-cli.md#audit) --- **Skill v1.0** | 2026-02-14 | Descomplicar® **Security First** - Zero vulnerabilities ou documentadas