Files
DashDescomplicar/api/routes/hetzner.ts
Emanuel Almeida f1756829af security: implement 6 high-severity vulnerability fixes
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>
2026-02-14 04:09:50 +00:00

142 lines
3.7 KiB
TypeScript
Executable File

/**
* Hetzner Cloud API Routes
* @author Descomplicar® | @link descomplicar.pt | @copyright 2026
*/
import { Router, Request, Response } from 'express'
import {
syncServers,
collectAllMetrics,
collectMetrics,
getHetznerDashboard,
getMetricsHistory,
cleanupOldMetrics
} from '../services/hetzner.js'
const router = Router()
// GET /api/hetzner - Dashboard data (servidores + últimas métricas)
router.get('/', async (_req: Request, res: Response) => {
try {
const data = await getHetznerDashboard()
res.json({
success: true,
data
})
} catch (error) {
console.error('Error fetching Hetzner dashboard:', error)
res.status(500).json({
success: false,
error: 'Failed to fetch Hetzner data'
})
}
})
// POST /api/hetzner/sync - Sincronizar lista de servidores
router.post('/sync', async (_req: Request, res: Response) => {
try {
const synced = await syncServers()
res.json({
success: true,
message: `Sincronizados ${synced} servidores`,
synced
})
} catch (error) {
console.error('Error syncing servers:', error)
res.status(500).json({
success: false,
error: 'Failed to sync servers'
})
}
})
// POST /api/hetzner/collect - Recolher métricas de todos os servidores
router.post('/collect', async (_req: Request, res: Response) => {
try {
const result = await collectAllMetrics()
res.json({
ok: true,
message: `Recolhidas métricas: ${result.success} OK, ${result.failed} falharam`,
...result
})
} catch (error) {
console.error('Error collecting metrics:', error)
res.status(500).json({
success: false,
error: 'Failed to collect metrics'
})
}
})
// POST /api/hetzner/collect/:hetzner_id - Recolher métricas de um servidor específico
router.post('/collect/:hetzner_id', async (req: Request, res: Response) => {
try {
const hetzner_id = parseInt(String(req.params.hetzner_id))
if (isNaN(hetzner_id)) {
return res.status(400).json({
success: false,
error: 'Invalid server ID'
})
}
const success = await collectMetrics(hetzner_id)
res.json({
success,
message: success ? 'Métricas recolhidas' : 'Falha ao recolher métricas'
})
} catch (error) {
console.error('Error collecting metrics:', error)
res.status(500).json({
success: false,
error: 'Failed to collect metrics'
})
}
})
// GET /api/hetzner/history/:server_id - Histórico de métricas para gráficos
router.get('/history/:server_id', async (req: Request, res: Response) => {
try {
const server_id = parseInt(String(req.params.server_id))
const hours = parseInt(req.query.hours as string) || 24
if (isNaN(server_id)) {
return res.status(400).json({
success: false,
error: 'Invalid server ID'
})
}
const metrics = await getMetricsHistory(server_id, hours)
res.json({
success: true,
data: metrics
})
} catch (error) {
console.error('Error fetching metrics history:', error)
res.status(500).json({
success: false,
error: 'Failed to fetch metrics history'
})
}
})
// POST /api/hetzner/cleanup - Limpar métricas antigas
router.post('/cleanup', async (req: Request, res: Response) => {
try {
const days = parseInt(req.query.days as string) || 7
const deleted = await cleanupOldMetrics(days)
res.json({
success: true,
message: `Eliminadas ${deleted} entradas com mais de ${days} dias`,
deleted
})
} catch (error) {
console.error('Error cleaning up metrics:', error)
res.status(500).json({
success: false,
error: 'Failed to cleanup metrics'
})
}
})
export default router