Security: Corrigir 3 vulnerabilidades críticas + 1 moderada
[C-001] CRÍTICO - Implementar autenticação API key - Middleware Next.js protege todas as rotas /api/* (exceto /health) - Sistema auth com validação de header x-api-key - Template .env.example com API_SECRET_KEY [C-002] CRÍTICO - Validação de inputs com Zod - Schemas para siteId (int positivo) e period (1-365d) - Previne NaN, SQL injection, inputs maliciosos - Respostas 400 Bad Request com detalhes de erro [C-003] CRÍTICO - Corrigir TypeScript any type - chart-card.tsx: any → string | number | null - ESLint passa sem warnings [M-005] MODERADO - Corrigir .gitignore sobre-restritivo - Exceção !.env.example permite commit do template Verificações: ✅ pnpm run lint - 0 erros ✅ pnpm audit - 0 vulnerabilidades ✅ CVSS 7.5 → 0.0 Docs: AUDIT-REPORT.md, SECURITY-FIX.md, CHANGELOG.md Regra: #47 (Security Audit Pre-Commit) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
49
src/lib/auth.ts
Normal file
49
src/lib/auth.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
|
||||
/**
|
||||
* Authentication utilities for API routes
|
||||
* Implements API key-based authentication
|
||||
*/
|
||||
|
||||
const API_KEY_HEADER = 'x-api-key'
|
||||
|
||||
/**
|
||||
* Validates API key from request headers
|
||||
* @param request - Next.js request object
|
||||
* @returns true if valid, false otherwise
|
||||
*/
|
||||
export function validateApiKey(request: NextRequest): boolean {
|
||||
const apiKey = request.headers.get(API_KEY_HEADER)
|
||||
const validApiKey = process.env.API_SECRET_KEY
|
||||
|
||||
if (!validApiKey) {
|
||||
console.warn('API_SECRET_KEY not configured in environment variables')
|
||||
return false
|
||||
}
|
||||
|
||||
return apiKey === validApiKey
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns unauthorized response
|
||||
*/
|
||||
export function unauthorizedResponse(): NextResponse {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: 'Unauthorized',
|
||||
message: 'Valid API key required. Include x-api-key header.'
|
||||
},
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Middleware helper to protect API routes
|
||||
*/
|
||||
export function requireAuth(request: NextRequest): NextResponse | null {
|
||||
if (!validateApiKey(request)) {
|
||||
return unauthorizedResponse()
|
||||
}
|
||||
return null
|
||||
}
|
||||
Reference in New Issue
Block a user