fix(agent): implement resilient bootloader, self-healing recovery, and dynamic packaging verification
This commit is contained in:
parent
bcbf6448d5
commit
69d77b7463
@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { GatewayDaemon } from '../src/gateway/daemon.js';
|
||||
import { AgentUpdater } from '../src/gateway/agent-updater.js';
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const command = args[0] || 'start';
|
||||
@ -13,6 +13,10 @@ if (command === 'start') {
|
||||
}
|
||||
const resetPin = args.includes('--reset-pin') || args.includes('--new-pin');
|
||||
|
||||
async function bootstrap() {
|
||||
try {
|
||||
// Dynamic import do Daemon para permitir que o bootloader trate erros de integridade/módulo
|
||||
const { GatewayDaemon } = await import('../src/gateway/daemon.js');
|
||||
const daemon = new GatewayDaemon({
|
||||
relayUrl: process.env.RELAY_URL,
|
||||
publicHost: process.env.PUBLIC_HOST,
|
||||
@ -30,6 +34,43 @@ if (command === 'start') {
|
||||
daemon.stop();
|
||||
process.exit(143);
|
||||
});
|
||||
} catch (bootErr) {
|
||||
console.error('\n[Maestri Remote Bootloader] Falha ao inicializar daemon:', bootErr.message);
|
||||
console.log('[Maestri Remote Bootloader] Iniciando protocolo de auto-recuperacao de integridade (Self-Healing)...');
|
||||
|
||||
try {
|
||||
const updater = new AgentUpdater({
|
||||
publicHost: process.env.PUBLIC_HOST || 'https://remote.winicomw.ddnsfree.com'
|
||||
});
|
||||
const remote = await updater.checkRemoteVersion();
|
||||
if (remote && remote.sha256) {
|
||||
console.log(`[Maestri Remote Bootloader] Baixando versao integra v${remote.version} do servidor...`);
|
||||
const success = await updater.performUpdate(remote);
|
||||
if (success) {
|
||||
console.log('[Maestri Remote Bootloader] Pacote reparado com sucesso! Reiniciando processo...');
|
||||
process.exit(42);
|
||||
}
|
||||
}
|
||||
} catch (repairErr) {
|
||||
console.error('[Maestri Remote Bootloader] Nao foi possivel auto-reparar:', repairErr.message);
|
||||
}
|
||||
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
bootstrap();
|
||||
} else if (command === '--verify') {
|
||||
// Modo de verificacao interna de integridade usado no build do pacote
|
||||
import('../src/gateway/daemon.js')
|
||||
.then(() => {
|
||||
console.log('OK: Integridade de modulos validada com sucesso.');
|
||||
process.exit(0);
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('ERRO: Falha na integridade de modulos:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
} else {
|
||||
console.log('Uso: maestri-remote [start] [--pin 123456] [--reset-pin]');
|
||||
console.log('Opções:');
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "maestri-remote-agent",
|
||||
"version": "1.0.23",
|
||||
"version": "1.0.24",
|
||||
"type": "module",
|
||||
"description": "Gateway Local do Maestri Remote para estações de trabalho",
|
||||
"bin": {
|
||||
|
||||
BIN
public/bundles/bundle-1.0.24.zip
Normal file
BIN
public/bundles/bundle-1.0.24.zip
Normal file
Binary file not shown.
Binary file not shown.
@ -1,9 +1,9 @@
|
||||
{
|
||||
"version": "1.0.23",
|
||||
"buildId": "8245c411",
|
||||
"releasedAt": "2026-11-21T14:51:00.432Z",
|
||||
"bundleUrl": "/bundles/bundle-1.0.23.zip",
|
||||
"version": "1.0.24",
|
||||
"buildId": "76f70c16",
|
||||
"releasedAt": "2026-11-21T15:03:06.574Z",
|
||||
"bundleUrl": "/bundles/bundle-1.0.24.zip",
|
||||
"latestUrl": "/bundles/bundle-latest.zip",
|
||||
"checksum": "55534ae518052d9808f9db369b92d1a42f829336b3bf1b65c19a46df55d168a1",
|
||||
"checksum": "83555f4be33cb2b490cf1bdd7105e9c53abe9696d41c3a202c2c818f99426aa7",
|
||||
"sizeBytes": 63298
|
||||
}
|
||||
Binary file not shown.
@ -15,28 +15,38 @@ if (fs.existsSync(STAGING_DIR)) {
|
||||
}
|
||||
fs.mkdirSync(STAGING_DIR, { recursive: true });
|
||||
|
||||
console.log('[BuildAgentPkg] Montando estrutura do pacote maestri-agent...');
|
||||
console.log('[BuildAgentPkg] Montando estrutura do pacote maestri-agent com cópia recursiva completa...');
|
||||
|
||||
// Copia bin/
|
||||
fs.mkdirSync(path.join(STAGING_DIR, 'bin'), { recursive: true });
|
||||
fs.copyFileSync(path.resolve('bin', 'maestri-remote.js'), path.join(STAGING_DIR, 'bin', 'maestri-remote.js'));
|
||||
function copyRecursiveSync(src, dest, filterExt = ['.js', '.json', '.txt']) {
|
||||
if (!fs.existsSync(src)) return;
|
||||
fs.mkdirSync(dest, { recursive: true });
|
||||
const entries = fs.readdirSync(src, { withFileTypes: true });
|
||||
|
||||
// Copia src/gateway/
|
||||
fs.mkdirSync(path.join(STAGING_DIR, 'src', 'gateway'), { recursive: true });
|
||||
fs.copyFileSync(path.resolve('src', 'gateway', 'daemon.js'), path.join(STAGING_DIR, 'src', 'gateway', 'daemon.js'));
|
||||
fs.copyFileSync(path.resolve('src', 'gateway', 'maestri-adapter.js'), path.join(STAGING_DIR, 'src', 'gateway', 'maestri-adapter.js'));
|
||||
fs.copyFileSync(path.resolve('src', 'gateway', 'agent-updater.js'), path.join(STAGING_DIR, 'src', 'gateway', 'agent-updater.js'));
|
||||
for (const entry of entries) {
|
||||
const srcPath = path.join(src, entry.name);
|
||||
const destPath = path.join(dest, entry.name);
|
||||
|
||||
// Copia src/utils/
|
||||
fs.mkdirSync(path.join(STAGING_DIR, 'src', 'utils'), { recursive: true });
|
||||
if (fs.existsSync(path.resolve('src', 'utils', 'text-sanitizer.js'))) {
|
||||
fs.copyFileSync(path.resolve('src', 'utils', 'text-sanitizer.js'), path.join(STAGING_DIR, 'src', 'utils', 'text-sanitizer.js'));
|
||||
if (entry.isDirectory()) {
|
||||
copyRecursiveSync(srcPath, destPath, filterExt);
|
||||
} else {
|
||||
const ext = path.extname(entry.name).toLowerCase();
|
||||
if (!filterExt || filterExt.includes(ext) || entry.name.startsWith('.')) {
|
||||
fs.copyFileSync(srcPath, destPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (fs.existsSync(path.resolve('src', 'utils', 'activity-detector.js'))) {
|
||||
fs.copyFileSync(path.resolve('src', 'utils', 'activity-detector.js'), path.join(STAGING_DIR, 'src', 'utils', 'activity-detector.js'));
|
||||
}
|
||||
|
||||
// Copia package.json enxuto (apenas dependências de runtime do gateway)
|
||||
// 1. Copia bin/ de forma completa
|
||||
copyRecursiveSync(path.resolve('bin'), path.join(STAGING_DIR, 'bin'));
|
||||
|
||||
// 2. Copia src/gateway/ de forma dinâmica e completa (NUNCA mais omitirá módulos novos)
|
||||
copyRecursiveSync(path.resolve('src', 'gateway'), path.join(STAGING_DIR, 'src', 'gateway'));
|
||||
|
||||
// 3. Copia src/utils/ de forma dinâmica e completa
|
||||
copyRecursiveSync(path.resolve('src', 'utils'), path.join(STAGING_DIR, 'src', 'utils'));
|
||||
|
||||
// 4. Copia package.json enxuto (apenas dependências de runtime do gateway)
|
||||
const fullPkg = JSON.parse(fs.readFileSync('package.json', 'utf8'));
|
||||
const agentPkg = {
|
||||
name: 'maestri-remote-agent',
|
||||
@ -47,7 +57,8 @@ const agentPkg = {
|
||||
'maestri-remote': 'bin/maestri-remote.js'
|
||||
},
|
||||
scripts: {
|
||||
start: 'node bin/maestri-remote.js start'
|
||||
start: 'node bin/maestri-remote.js start',
|
||||
verify: 'node bin/maestri-remote.js --verify'
|
||||
},
|
||||
dependencies: {
|
||||
ws: fullPkg.dependencies.ws || '^8.18.0'
|
||||
@ -55,11 +66,12 @@ const agentPkg = {
|
||||
};
|
||||
fs.writeFileSync(path.join(STAGING_DIR, 'package.json'), JSON.stringify(agentPkg, null, 2));
|
||||
|
||||
// Adiciona scripts de inicialização rápida com auto-restart em atualizações para Windows e Linux
|
||||
// 5. Adiciona scripts de inicialização rápida com auto-restart e auto-recuperação de emergência (Self-Healing)
|
||||
const startBat = `@echo off
|
||||
setlocal
|
||||
setlocal enabledelayedexpansion
|
||||
title Maestri Remote Daemon
|
||||
set "MAESTRI_MANAGED_BY_WRAPPER=1"
|
||||
set "CONSECUTIVE_FAILURES=0"
|
||||
|
||||
:loop
|
||||
echo ==============================================
|
||||
@ -75,16 +87,39 @@ echo Iniciando gateway de comunicacao...
|
||||
node bin\\maestri-remote.js start
|
||||
set "CODE=%ERRORLEVEL%"
|
||||
|
||||
if "%CODE%"=="42" goto restart
|
||||
if "%CODE%"=="0" goto restart
|
||||
if "%CODE%"=="42" (
|
||||
set "CONSECUTIVE_FAILURES=0"
|
||||
goto restart
|
||||
)
|
||||
if "%CODE%"=="0" (
|
||||
set "CONSECUTIVE_FAILURES=0"
|
||||
goto restart
|
||||
)
|
||||
if "%CODE%"=="130" (
|
||||
echo.
|
||||
echo [Maestri Remote] Daemon encerrado pelo operador.
|
||||
exit /b 0
|
||||
)
|
||||
|
||||
rem Incrementa contador de falhas consecutivas
|
||||
set /a CONSECUTIVE_FAILURES+=1
|
||||
echo.
|
||||
echo [Maestri Remote] Gateway finalizado com codigo %CODE%.
|
||||
echo [Maestri Remote] Gateway finalizado com codigo %CODE% (Falha consecutiva: !CONSECUTIVE_FAILURES!).
|
||||
|
||||
rem Se acumular 3 falhas consecutivas, aciona protocolo de auto-recuperacao de emergencia
|
||||
if !CONSECUTIVE_FAILURES! GEQ 3 (
|
||||
echo.
|
||||
echo [Maestri Remote ALERTA] Multiplas falhas consecutivas detectadas.
|
||||
echo [Maestri Remote ALERTA] Executando protocolo de auto-recuperacao de emergencia via Relay...
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -Command "$ErrorActionPreference = 'Stop'; try { Write-Host 'Baixando pacote limpo do Relay...'; Invoke-WebRequest -Uri 'https://remote.winicomw.ddnsfree.com/maestri-agent.zip' -OutFile '.emergency_update.zip'; Write-Host 'Aplicando arquivos integro...'; Expand-Archive -Path '.emergency_update.zip' -DestinationPath '.' -Force; Remove-Item '.emergency_update.zip'; Write-Host 'Restauracao de emergencia concluida com sucesso!'; exit 0 } catch { Write-Host 'Falha no download de emergencia:' $_.Exception.Message; exit 1 }"
|
||||
if !ERRORLEVEL! EQU 0 (
|
||||
set "CONSECUTIVE_FAILURES=0"
|
||||
echo [Maestri Remote] Pacote restaurado! Reiniciando em 2 segundos...
|
||||
timeout /t 2 /nobreak >nul
|
||||
goto loop
|
||||
)
|
||||
)
|
||||
|
||||
echo Tentando reiniciar em 3 segundos... (Pressione Ctrl+C para sair)
|
||||
timeout /t 3
|
||||
goto loop
|
||||
@ -107,6 +142,7 @@ if [ ! -d "node_modules" ]; then
|
||||
fi
|
||||
|
||||
export MAESTRI_MANAGED_BY_WRAPPER=1
|
||||
FAIL_COUNT=0
|
||||
|
||||
while true; do
|
||||
echo ""
|
||||
@ -114,13 +150,27 @@ while true; do
|
||||
node bin/maestri-remote.js start
|
||||
EXIT_CODE=$?
|
||||
if [ $EXIT_CODE -eq 42 ] || [ $EXIT_CODE -eq 0 ]; then
|
||||
FAIL_COUNT=0
|
||||
echo ""
|
||||
echo "[Maestri Remote] Daemon atualizado com sucesso. Reiniciando em 2 segundos..."
|
||||
sleep 2
|
||||
else
|
||||
elif [ $EXIT_CODE -eq 130 ]; then
|
||||
echo ""
|
||||
echo "[Maestri Remote] Gateway finalizado com codigo $EXIT_CODE."
|
||||
echo "[Maestri Remote] Daemon encerrado pelo operador."
|
||||
break
|
||||
else
|
||||
FAIL_COUNT=$((FAIL_COUNT + 1))
|
||||
echo ""
|
||||
echo "[Maestri Remote] Gateway finalizado com codigo $EXIT_CODE (Falha $FAIL_COUNT)."
|
||||
if [ $FAIL_COUNT -ge 3 ]; then
|
||||
echo "[Maestri Remote] Executando auto-recuperacao de emergencia..."
|
||||
curl -sSfL "https://remote.winicomw.ddnsfree.com/maestri-agent.zip" -o ".emergency.zip" && \
|
||||
unzip -o -q ".emergency.zip" -d "." && \
|
||||
rm -f ".emergency.zip" && \
|
||||
FAIL_COUNT=0 && \
|
||||
echo "[Maestri Remote] Recuperacao concluida!"
|
||||
fi
|
||||
sleep 3
|
||||
fi
|
||||
done
|
||||
`;
|
||||
@ -148,15 +198,68 @@ No seu celular, toque em "+ Estacao" ou digite o PIN para conectar imediatamente
|
||||
`;
|
||||
fs.writeFileSync(path.join(STAGING_DIR, 'README.txt'), readme);
|
||||
|
||||
// ====================================================================
|
||||
// 6. SMOKE TEST OBRIGATÓRIO DE PRÉ-EMPACOTAMENTO (Integrity Verification)
|
||||
// ====================================================================
|
||||
console.log('[BuildAgentPkg] Executando Smoke Test e validacao estrita de integridade no pacote staging...');
|
||||
|
||||
// 6.1. Verifica se todos os arquivos importados em src/gateway existem fisicamente no staging
|
||||
const gatewayFiles = fs.readdirSync(path.join(STAGING_DIR, 'src', 'gateway')).filter(f => f.endsWith('.js'));
|
||||
for (const file of gatewayFiles) {
|
||||
const fullPath = path.join(STAGING_DIR, 'src', 'gateway', file);
|
||||
const content = fs.readFileSync(fullPath, 'utf8');
|
||||
const importRegex = /(?:import|from)\s+['"](\.[^'"]+)['"]/g;
|
||||
let match;
|
||||
while ((match = importRegex.exec(content)) !== null) {
|
||||
const importRel = match[1];
|
||||
const resolvedPath = path.resolve(path.dirname(fullPath), importRel);
|
||||
if (!fs.existsSync(resolvedPath)) {
|
||||
throw new Error(`[BuildAgentPkg FATAL] Integridade comprometida! O arquivo ${file} importa '${importRel}', mas ele NAO EXISTE no pacote staging (${resolvedPath})!`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 6.2. Executa node --check em cada arquivo JS empacotado
|
||||
const allJsFiles = [];
|
||||
function findJs(dir) {
|
||||
for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const p = path.join(dir, ent.name);
|
||||
if (ent.isDirectory()) findJs(p);
|
||||
else if (p.endsWith('.js')) allJsFiles.push(p);
|
||||
}
|
||||
}
|
||||
findJs(STAGING_DIR);
|
||||
|
||||
for (const js of allJsFiles) {
|
||||
try {
|
||||
execSync(`node --check "${js}"`, { stdio: 'pipe' });
|
||||
} catch (chkErr) {
|
||||
throw new Error(`[BuildAgentPkg FATAL] Sintaxe invalida em ${js}: ${chkErr.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 6.3. Executa teste de import do bootloader
|
||||
try {
|
||||
execSync(`node "${path.join(STAGING_DIR, 'bin', 'maestri-remote.js')}" --verify`, {
|
||||
cwd: STAGING_DIR,
|
||||
stdio: 'pipe',
|
||||
env: { ...process.env, NODE_PATH: path.resolve('node_modules') }
|
||||
});
|
||||
console.log('[BuildAgentPkg] Smoke Test APROVADO! Todos os modulos e dependencias sao 100% integraveis.');
|
||||
} catch (vErr) {
|
||||
throw new Error(`[BuildAgentPkg FATAL] Falha no teste de execucao do bootloader: ${vErr.message}`);
|
||||
}
|
||||
|
||||
// ====================================================================
|
||||
// 7. GERAÇÃO DO ZIP
|
||||
// ====================================================================
|
||||
console.log(`[BuildAgentPkg] Gerando ${DIST_ZIP}...`);
|
||||
if (fs.existsSync(DIST_ZIP)) {
|
||||
fs.unlinkSync(DIST_ZIP);
|
||||
}
|
||||
|
||||
// Criação do ZIP padrão compatível com Windows Explorer (sem o bug de ./ do bsdtar)
|
||||
let zipSuccess = false;
|
||||
try {
|
||||
// Tenta Compress-Archive do PowerShell (padrão oficial do Windows Explorer)
|
||||
execSync(`powershell -NoProfile -Command "Compress-Archive -Path '${STAGING_DIR}\\*' -DestinationPath '${DIST_ZIP}' -Force"`, { stdio: 'inherit' });
|
||||
zipSuccess = true;
|
||||
} catch (psErr) {
|
||||
@ -164,7 +267,6 @@ try {
|
||||
}
|
||||
|
||||
if (!zipSuccess) {
|
||||
// Fallback: usa tar com * em vez de . para não criar ./ na raiz
|
||||
execSync(`tar -a -c -f "${DIST_ZIP}" -C "${STAGING_DIR}" *`, { stdio: 'inherit' });
|
||||
}
|
||||
|
||||
|
||||
@ -7,7 +7,21 @@ import { MaestriAdapter } from './maestri-adapter.js';
|
||||
import { cleanTerminalOutput } from '../utils/text-sanitizer.js';
|
||||
import { detectTerminalActivity } from '../utils/activity-detector.js';
|
||||
import { AgentUpdater } from './agent-updater.js';
|
||||
import { CanvasAutoWiringMonitor } from './canvas-auto-wiring.js';
|
||||
|
||||
let CanvasAutoWiringMonitor = class FallbackAutoWiringMonitor {
|
||||
constructor() {}
|
||||
start() {}
|
||||
stop() {}
|
||||
};
|
||||
|
||||
try {
|
||||
const autoWiringModule = await import('./canvas-auto-wiring.js');
|
||||
if (autoWiringModule && autoWiringModule.CanvasAutoWiringMonitor) {
|
||||
CanvasAutoWiringMonitor = autoWiringModule.CanvasAutoWiringMonitor;
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('[GatewayDaemon] Modulo canvas-auto-wiring nao disponivel ou falhou ao carregar:', err.message);
|
||||
}
|
||||
|
||||
export class GatewayDaemon {
|
||||
constructor(options = {}) {
|
||||
|
||||
43
test/build-agent-pkg.test.js
Normal file
43
test/build-agent-pkg.test.js
Normal file
@ -0,0 +1,43 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { execSync } from 'node:child_process';
|
||||
|
||||
test('BuildAgentPkg - Empacotamento Completo e Validação de Integridade do Daemon', async (t) => {
|
||||
await t.test('deve conter todos os arquivos de src/gateway e src/utils dentro de public/maestri-agent.zip', () => {
|
||||
const zipPath = path.resolve('public', 'maestri-agent.zip');
|
||||
assert.ok(fs.existsSync(zipPath), 'maestri-agent.zip deve existir em public/');
|
||||
|
||||
// Obtém a lista real de arquivos em src/gateway
|
||||
const gatewaySrcFiles = fs.readdirSync(path.resolve('src', 'gateway')).filter(f => f.endsWith('.js'));
|
||||
const utilsSrcFiles = fs.readdirSync(path.resolve('src', 'utils')).filter(f => f.endsWith('.js'));
|
||||
|
||||
// Inspeciona o zip via PowerShell ou unzip
|
||||
let zipEntries = [];
|
||||
try {
|
||||
const output = execSync(`powershell -NoProfile -Command "Add-Type -AssemblyName System.IO.Compression.FileSystem; [System.IO.Compression.ZipFile]::OpenRead('${zipPath}').Entries | Select-Object -ExpandProperty FullName"`, { encoding: 'utf8' });
|
||||
zipEntries = output.split(/\r?\n/).map(s => s.trim().replace(/\\/g, '/')).filter(Boolean);
|
||||
} catch {
|
||||
const output = execSync(`tar -tf "${zipPath}"`, { encoding: 'utf8' });
|
||||
zipEntries = output.split(/\r?\n/).map(s => s.trim().replace(/\\/g, '/')).filter(Boolean);
|
||||
}
|
||||
|
||||
// Valida que TODOS os arquivos de src/gateway estão no zip
|
||||
for (const f of gatewaySrcFiles) {
|
||||
const expected = `src/gateway/${f}`;
|
||||
assert.ok(zipEntries.includes(expected), `O arquivo ${expected} DEVE estar presente no pacote zip de distribuição!`);
|
||||
}
|
||||
|
||||
// Valida que TODOS os arquivos de src/utils estão no zip
|
||||
for (const f of utilsSrcFiles) {
|
||||
const expected = `src/utils/${f}`;
|
||||
assert.ok(zipEntries.includes(expected), `O arquivo ${expected} DEVE estar presente no pacote zip de distribuição!`);
|
||||
}
|
||||
|
||||
// Valida presença de canvas-auto-wiring.js explicitamente
|
||||
assert.ok(zipEntries.includes('src/gateway/canvas-auto-wiring.js'), 'canvas-auto-wiring.js DEVE estar presente!');
|
||||
assert.ok(zipEntries.includes('bin/maestri-remote.js'), 'bin/maestri-remote.js DEVE estar presente!');
|
||||
assert.ok(zipEntries.includes('iniciar.bat'), 'iniciar.bat DEVE estar presente!');
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user