HIGH-SEVERITY FIXES (Fase 2): 1. Rate Limiting (Vulnerabilidade 2.1) - express-rate-limit: 100 req/15min (prod), 1000 req/15min (dev) - Applied to all /api/* routes - Standard headers for retry-after 2. CORS Restrictions (Vulnerabilidade 2.2) - Whitelist: dashboard.descomplicar.pt, desk.descomplicar.pt - Localhost only in development - CORS blocking logs 3. Input Validation with Zod (Vulnerabilidade 2.4) - Generic validateRequest() middleware - Schemas: WordPress Monitor, server metrics, dashboard, financial - Applied to api/routes/wp-monitor.ts POST endpoint - Detailed field-level error messages 4. Backend Authentication OIDC (Vulnerabilidade 2.5 - OPTIONAL) - Enabled via OIDC_ENABLED=true - Bearer token validation on all APIs - Backward compatible (disabled by default) 5. SSH Key-Based Auth Migration (Vulnerabilidade 2.6) - Script: /media/ealmeida/Dados/Dev/ClaudeDev/migrate-ssh-keys.sh - Generates ed25519 key, copies to 6 servers - Instructions to remove passwords from .env - .env.example updated with SSH_PRIVATE_KEY_PATH 6. Improved Error Handling (Vulnerabilidade 2.5) - Unique error IDs (UUID) for tracking - Structured JSON logs in production - Stack traces blocked in production - Generic messages to client FILES CHANGED: - api/server.ts - Complete refactor with all security improvements - api/middleware/validation.ts - NEW: Zod middleware and schemas - api/routes/wp-monitor.ts - Added Zod validation on POST - .env.example - Complete security documentation - CHANGELOG.md - Full documentation of 9 fixes (3 critical + 6 high) - package.json + package-lock.json - New dependencies DEPENDENCIES ADDED: - express-rate-limit@7.x - zod@3.x - express-openid-connect@2.x AUDIT STATUS: - npm audit: 0 vulnerabilities - Hook Regra #47: PASSED PROGRESS: - Phase 1 (Critical): 3/3 ✅ COMPLETE - Phase 2 (High): 6/6 ✅ COMPLETE - Phase 3 (Medium): 0/6 - Next - Phase 4 (Low): 0/5 - Next Related: AUDIT-REPORT.md vulnerabilities 2.1, 2.2, 2.4, 2.5, 2.6 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
129 lines
3.3 KiB
TypeScript
129 lines
3.3 KiB
TypeScript
/**
|
|
* Input Validation Middleware with Zod
|
|
* Vulnerabilidade 2.4 - Adicionar validação de input
|
|
* @author Descomplicar® | @link descomplicar.pt | @copyright 2026
|
|
*/
|
|
import { z } from 'zod'
|
|
import type { Request, Response, NextFunction } from 'express'
|
|
|
|
/**
|
|
* Middleware genérico de validação Zod
|
|
*/
|
|
export function validateRequest(schema: {
|
|
body?: z.ZodSchema
|
|
params?: z.ZodSchema
|
|
query?: z.ZodSchema
|
|
}) {
|
|
return async (req: Request, res: Response, next: NextFunction) => {
|
|
try {
|
|
// Validar body
|
|
if (schema.body) {
|
|
req.body = await schema.body.parseAsync(req.body)
|
|
}
|
|
|
|
// Validar params
|
|
if (schema.params) {
|
|
req.params = await schema.params.parseAsync(req.params)
|
|
}
|
|
|
|
// Validar query
|
|
if (schema.query) {
|
|
req.query = await schema.query.parseAsync(req.query)
|
|
}
|
|
|
|
next()
|
|
} catch (error) {
|
|
if (error instanceof z.ZodError) {
|
|
return res.status(400).json({
|
|
error: 'Validation error',
|
|
details: error.errors.map(e => ({
|
|
field: e.path.join('.'),
|
|
message: e.message
|
|
}))
|
|
})
|
|
}
|
|
|
|
// Outros erros
|
|
return res.status(500).json({
|
|
error: 'Internal validation error'
|
|
})
|
|
}
|
|
}
|
|
}
|
|
|
|
// ============================================================================
|
|
// Schemas de validação para rotas comuns
|
|
// ============================================================================
|
|
|
|
/**
|
|
* Schema para WordPress Monitor POST
|
|
*/
|
|
export const wpMonitorSchema = {
|
|
body: z.object({
|
|
site_url: z.string().url('Invalid site_url format'),
|
|
site_name: z.string().optional(),
|
|
health: z.object({
|
|
status: z.enum(['good', 'recommended', 'critical']).optional()
|
|
}).optional(),
|
|
updates: z.object({
|
|
counts: z.object({
|
|
total: z.number().int().nonnegative()
|
|
}).optional(),
|
|
core: z.array(z.any()).optional()
|
|
}).optional(),
|
|
system: z.object({
|
|
debug_mode: z.boolean().optional()
|
|
}).optional(),
|
|
database: z.object({
|
|
size_mb: z.number().nonnegative().optional()
|
|
}).optional()
|
|
}).passthrough() // Permite campos adicionais
|
|
}
|
|
|
|
/**
|
|
* Schema para server metrics params
|
|
*/
|
|
export const serverMetricsParamsSchema = {
|
|
params: z.object({
|
|
server_id: z.string().regex(/^\d+$/, 'server_id must be numeric')
|
|
})
|
|
}
|
|
|
|
/**
|
|
* Schema para server metrics query
|
|
*/
|
|
export const serverMetricsQuerySchema = {
|
|
query: z.object({
|
|
hours: z.string().regex(/^\d+$/, 'hours must be numeric').optional().default('24')
|
|
})
|
|
}
|
|
|
|
/**
|
|
* Schema para dashboard query (semana)
|
|
*/
|
|
export const dashboardWeekSchema = {
|
|
query: z.object({
|
|
week: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'week must be YYYY-MM-DD format').optional()
|
|
})
|
|
}
|
|
|
|
/**
|
|
* Schema para Hetzner server ID
|
|
*/
|
|
export const hetznerServerIdSchema = {
|
|
params: z.object({
|
|
server_id: z.string().regex(/^\d+$/, 'server_id must be numeric')
|
|
})
|
|
}
|
|
|
|
/**
|
|
* Schema para financial query (intervalo de datas)
|
|
*/
|
|
export const financialDateRangeSchema = {
|
|
query: z.object({
|
|
start: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'start must be YYYY-MM-DD').optional(),
|
|
end: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'end must be YYYY-MM-DD').optional(),
|
|
month: z.string().regex(/^\d{4}-\d{2}$/, 'month must be YYYY-MM').optional()
|
|
})
|
|
}
|