import fs from 'node:fs'; import path from 'node:path'; import crypto from 'node:crypto'; const MIME_TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'application/javascript; charset=utf-8', '.json': 'application/json; charset=utf-8', '.css': 'text/css; charset=utf-8', '.zip': 'application/zip', '.apk': 'application/vnd.android.package-archive', '.ps1': 'text/plain; charset=utf-8', '.sh': 'text/plain; charset=utf-8', '.png': 'image/png', '.svg': 'image/svg+xml', '.ico': 'image/x-icon' }; function sendJson(res, statusCode, payload, extraHeaders = {}) { res.writeHead(statusCode, { 'Content-Type': 'application/json', 'Cache-Control': 'no-cache, no-store, must-revalidate', ...extraHeaders }); res.end(JSON.stringify(payload)); } function readJsonBody(req) { return new Promise((resolve, reject) => { let body = ''; req.on('data', chunk => { body += chunk; if (body.length > 1024 * 1024) { reject(new Error('Payload excedeu o limite permitido.')); } }); req.on('end', () => { if (!body.trim()) return resolve({}); try { resolve(JSON.parse(body)); } catch { reject(new Error('Payload JSON inválido')); } }); req.on('error', reject); }); } function escapeHtml(str) { return String(str || '') .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"') .replace(/'/g, '''); } function renderAuthCallbackHtml({ ok, token, user, mode = 'web', errorMessage }) { if (!ok) { return ` Erro de Autenticação — Maestri Remote

Falha no Login

${escapeHtml(errorMessage || 'Não foi possível concluir a autenticação.')}

Feche esta janela e tente novamente no aplicativo Maestri Remote.

`; } const safePayloadJson = JSON.stringify({ type: 'MAESTRI_AUTH_SUCCESS', token, user }).replace(/ Login Concluído — Maestri Remote

Login concluído!

Login concluído! Pode voltar para o aplicativo Maestri Remote.

`; } export function createRelayHttpHandler({ publicDir = path.resolve('public'), pushService, otaService, intentClassifier, telemetryService, authService, dbService } = {}) { return async (req, res) => { const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`); const pathname = url.pathname; // Headers de CORS para permitir acesso local e externo (incluindo WebView Android https://localhost) res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE, OPTIONS'); res.setHeader('Access-Control-Allow-Headers', '*'); if (req.method === 'OPTIONS') { res.writeHead(204); return res.end(); } // 1. Healthcheck if (pathname === '/api/health') { return sendJson(res, 200, { status: 'ok', timestamp: new Date().toISOString() }); } // 2. Autenticação OIDC (Keycloak + Google IdP) if (pathname === '/api/auth/start' && req.method === 'POST') { if (!authService || !authService.isConfigured()) { return sendJson(res, 503, { error: 'Autenticação OIDC não configurada no servidor.' }); } try { const body = await readJsonBody(req).catch(() => ({})); const result = authService.startFlow({ mode: body?.mode }); return sendJson(res, 200, result); } catch (err) { return sendJson(res, 500, { error: err.message }); } } if (pathname === '/api/auth/callback' && req.method === 'GET') { if (!authService) { res.writeHead(503, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end(renderAuthCallbackHtml({ ok: false, errorMessage: 'Serviço de autenticação indisponível.' })); } try { const code = url.searchParams.get('code'); const state = url.searchParams.get('state'); const error = url.searchParams.get('error_description') || url.searchParams.get('error'); const result = await authService.handleCallback({ code, state, error }); res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-cache, no-store, must-revalidate' }); return res.end(renderAuthCallbackHtml({ ok: true, token: result.token, user: result.user, mode: result.mode })); } catch (err) { res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-cache, no-store, must-revalidate' }); return res.end(renderAuthCallbackHtml({ ok: false, errorMessage: err.message })); } } if (pathname === '/api/auth/poll' && req.method === 'GET') { if (!authService) { return sendJson(res, 503, { error: 'Serviço de autenticação indisponível.' }); } const flowId = url.searchParams.get('flowId'); const result = authService.pollFlow(flowId); return sendJson(res, 200, result); } if (pathname === '/api/auth/me' && req.method === 'GET') { if (!authService) { return sendJson(res, 503, { error: 'Serviço de autenticação indisponível.' }); } const user = authService.requireAuth(req, res); if (!user) return; return sendJson(res, 200, { user }); } // 3. Estações sincronizadas por usuário autenticado if (pathname === '/api/stations' && req.method === 'GET') { const user = authService?.requireAuth(req, res); if (!user) return; if (!dbService || !dbService.isConfigured()) { return sendJson(res, 503, { error: 'Persistência de estações indisponível.' }); } try { const stations = await dbService.listStations(user.id); return sendJson(res, 200, { stations }); } catch (err) { return sendJson(res, 500, { error: err.message }); } } if (pathname === '/api/stations' && req.method === 'POST') { const user = authService?.requireAuth(req, res); if (!user) return; if (!dbService || !dbService.isConfigured()) { return sendJson(res, 503, { error: 'Persistência de estações indisponível.' }); } try { const body = await readJsonBody(req); const pin = String(body.pin || '').trim(); const name = String(body.name || '').trim() || `Estação ${pin}`; const machineName = body.machineName ? String(body.machineName).trim() : null; if (!pin) { return sendJson(res, 400, { error: 'PIN da estação é obrigatório.' }); } const result = await dbService.upsertStation(user.id, { pin, name, machineName }); return sendJson(res, 200, result); } catch (err) { return sendJson(res, 400, { error: err.message }); } } const stationMatch = pathname.match(/^\/api\/stations\/([^/]+)$/); if (stationMatch && req.method === 'PATCH') { const user = authService?.requireAuth(req, res); if (!user) return; if (!dbService || !dbService.isConfigured()) { return sendJson(res, 503, { error: 'Persistência de estações indisponível.' }); } try { const pin = decodeURIComponent(stationMatch[1]); const body = await readJsonBody(req); const name = String(body.name || '').trim(); if (!name) { return sendJson(res, 400, { error: 'Novo nome da estação é obrigatório.' }); } const result = await dbService.renameStation(user.id, pin, name); if (!result) { return sendJson(res, 404, { error: 'Estação não encontrada para este usuário.' }); } return sendJson(res, 200, result); } catch (err) { return sendJson(res, 400, { error: err.message }); } } if (stationMatch && req.method === 'DELETE') { const user = authService?.requireAuth(req, res); if (!user) return; if (!dbService || !dbService.isConfigured()) { return sendJson(res, 503, { error: 'Persistência de estações indisponível.' }); } try { const pin = decodeURIComponent(stationMatch[1]); const result = await dbService.deleteStation(user.id, pin); if (!result.deleted) { return sendJson(res, 404, { error: 'Estação não encontrada para este usuário.' }); } return sendJson(res, 200, { ok: true, stations: result.stations }); } catch (err) { return sendJson(res, 500, { error: err.message }); } } // 4. Versionamento OTA (para checagem de Live Updates sem USB) if (pathname === '/api/version') { const manifest = otaService.getManifest(); return sendJson(res, 200, manifest); } // 5. Manifesto OTA para download de bundles pelo APK Android if (pathname === '/api/updates/latest') { const manifest = otaService.getManifest(); return sendJson(res, 200, manifest); } // 5.1. Versão do Daemon para Auto-Atualização dos Agentes de Estação if (pathname === '/api/agent/version') { const agentZipPath = path.join(publicDir, 'maestri-agent.zip'); let sha256 = null; let sizeBytes = 0; let updatedAt = new Date().toISOString(); if (fs.existsSync(agentZipPath)) { const buf = fs.readFileSync(agentZipPath); sha256 = crypto.createHash('sha256').update(buf).digest('hex'); const stats = fs.statSync(agentZipPath); sizeBytes = stats.size; updatedAt = stats.mtime.toISOString(); } const manifest = otaService.getManifest(); return sendJson(res, 200, { version: manifest.version || '1.0.1', sha256, sizeBytes, downloadUrl: '/maestri-agent.zip', updatedAt }); } // 6. Chave pública VAPID para Web Push if (pathname === '/api/push/vapid-key') { return sendJson(res, 200, { publicKey: pushService.getPublicKey() }); } // 7. Inscrição de Web Push if (pathname === '/api/push/subscribe' && req.method === 'POST') { try { const { pin, subscription } = await readJsonBody(req); pushService.addSubscription(pin, subscription); return sendJson(res, 200, { success: true }); } catch { return sendJson(res, 400, { error: 'Payload JSON inválido' }); } } // 8. Classificação Semântica de Intenções via LiteLLM if (pathname === '/api/intent/classify' && req.method === 'POST') { try { const { text, agentName } = await readJsonBody(req); const result = await intentClassifier.classify(text, agentName); return sendJson(res, 200, result); } catch (err) { return sendJson(res, 500, { error: err.message }); } } // 9. Telemetria e Traces: Ingestão de Logs e Snapshots if (pathname === '/api/telemetry/log' && req.method === 'POST') { try { const payload = await readJsonBody(req); const result = Array.isArray(payload) ? telemetryService.logBatch(payload) : telemetryService.logEvent(payload); return sendJson(res, 200, { ok: true, count: Array.isArray(result) ? result.length : 1 }); } catch (err) { return sendJson(res, 400, { error: 'Payload JSON inválido: ' + err.message }); } } // 10. Telemetria e Traces: Consulta com Filtros if (pathname === '/api/telemetry/traces' && req.method === 'GET') { const filters = { pin: url.searchParams.get('pin'), agentName: url.searchParams.get('agent'), category: url.searchParams.get('category'), source: url.searchParams.get('source'), since: url.searchParams.get('since'), limit: url.searchParams.get('limit') }; const traces = telemetryService.getTraces(filters); return sendJson(res, 200, traces); } // 11. Telemetria e Traces: SSE em Tempo Real if (pathname === '/api/telemetry/stream' && req.method === 'GET') { res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache, no-transform', 'Connection': 'keep-alive' }); res.write(': connected\n\n'); telemetryService.addStreamListener(res); return; } // 12. Dashboard de Observabilidade (/traces) if (pathname === '/traces' || pathname === '/traces/') { const tracesHtmlPath = path.join(publicDir, 'traces.html'); if (fs.existsSync(tracesHtmlPath)) { res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-cache, no-store, must-revalidate' }); return fs.createReadStream(tracesHtmlPath).pipe(res); } } // 13. Servir arquivos estáticos do PWA / Bundles OTA let safePath = path.normalize(pathname).replace(/^(\.\.[\/\\])+/, ''); if (safePath === '/' || safePath === '\\') safePath = '/index.html'; const filePath = path.join(publicDir, safePath); if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) { const ext = path.extname(filePath).toLowerCase(); const contentType = MIME_TYPES[ext] || 'application/octet-stream'; const cacheControl = (ext === '.html' || ext === '.js' || ext === '.css' || ext === '.json' || ext === '.ps1' || ext === '.sh') ? 'no-cache, no-store, must-revalidate' : 'public, max-age=86400'; res.writeHead(200, { 'Content-Type': contentType, 'Cache-Control': cacheControl }); return fs.createReadStream(filePath).pipe(res); } // Fallback para SPA (Single Page App) const indexHtml = path.join(publicDir, 'index.html'); if (fs.existsSync(indexHtml)) { res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-cache, no-store, must-revalidate' }); return fs.createReadStream(indexHtml).pipe(res); } res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('Not Found'); }; }