340 lines
12 KiB
JavaScript
340 lines
12 KiB
JavaScript
import test from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import EventEmitter from 'node:events';
|
|
import { GatewayDaemon } from '../src/gateway/daemon.js';
|
|
import { handleClientWsMessage } from '../src/relay/client-message-handler.js';
|
|
import { handleGatewayWsMessage } from '../src/relay/gateway-message-handler.js';
|
|
import { SessionManager } from '../src/relay/session-manager.js';
|
|
|
|
class MockSocket extends EventEmitter {
|
|
constructor() {
|
|
super();
|
|
this.OPEN = 1;
|
|
this.readyState = 1;
|
|
this.sent = [];
|
|
}
|
|
send(data) {
|
|
this.sent.push(data);
|
|
}
|
|
}
|
|
|
|
test('GatewayDaemon - FILE_READ_REQ: Deve ler arquivo existente no workspace com Base64 e MIME type correto', async () => {
|
|
const daemon = new GatewayDaemon({ pin: '112233' });
|
|
const mockWs = new MockSocket();
|
|
daemon.ws = mockWs;
|
|
daemon.connected = true;
|
|
|
|
// Usa um arquivo real do projeto que certamente existe
|
|
const testPath = 'package.json';
|
|
await daemon.handleRelayMessage({
|
|
type: 'FILE_READ_REQ',
|
|
path: testPath,
|
|
agentName: 'TestAgent',
|
|
chatId: 'chat-101'
|
|
});
|
|
|
|
assert.equal(mockWs.sent.length, 1);
|
|
const resp = JSON.parse(mockWs.sent[0]);
|
|
assert.equal(resp.type, 'FILE_READ_RESP');
|
|
assert.equal(resp.ok, true);
|
|
assert.equal(resp.path, testPath);
|
|
assert.equal(resp.name, 'package.json');
|
|
assert.equal(resp.mimeType, 'application/json');
|
|
assert.equal(resp.agentName, 'TestAgent');
|
|
assert.equal(resp.chatId, 'chat-101');
|
|
assert.ok(typeof resp.contentBase64 === 'string' && resp.contentBase64.length > 0);
|
|
|
|
// Decodifica Base64 e valida conteúdo
|
|
const decoded = Buffer.from(resp.contentBase64, 'base64').toString('utf8');
|
|
assert.ok(decoded.includes('maestri-remote-agent'));
|
|
});
|
|
|
|
test('GatewayDaemon - FILE_READ_REQ: Sandbox defensivo deve bloquear escape de diretório (../)', async () => {
|
|
const daemon = new GatewayDaemon({ pin: '112233' });
|
|
const mockWs = new MockSocket();
|
|
daemon.ws = mockWs;
|
|
daemon.connected = true;
|
|
|
|
await daemon.handleRelayMessage({
|
|
type: 'FILE_READ_REQ',
|
|
path: '../../../../../../etc/passwd',
|
|
agentName: 'TestAgent',
|
|
chatId: 'chat-sandbox'
|
|
});
|
|
|
|
assert.equal(mockWs.sent.length, 1);
|
|
const resp = JSON.parse(mockWs.sent[0]);
|
|
assert.equal(resp.type, 'FILE_READ_RESP');
|
|
assert.equal(resp.ok, false);
|
|
assert.ok(resp.error.includes('Acesso negado') || resp.error.includes('workspace'));
|
|
});
|
|
|
|
test('GatewayDaemon - FILE_READ_REQ: Deve retornar erro informativo se arquivo não existir', async () => {
|
|
const daemon = new GatewayDaemon({ pin: '112233' });
|
|
const mockWs = new MockSocket();
|
|
daemon.ws = mockWs;
|
|
daemon.connected = true;
|
|
|
|
await daemon.handleRelayMessage({
|
|
type: 'FILE_READ_REQ',
|
|
path: 'arquivo-totalmente-inexistente-12345.xyz',
|
|
agentName: 'TestAgent'
|
|
});
|
|
|
|
assert.equal(mockWs.sent.length, 1);
|
|
const resp = JSON.parse(mockWs.sent[0]);
|
|
assert.equal(resp.type, 'FILE_READ_RESP');
|
|
assert.equal(resp.ok, false);
|
|
assert.ok(resp.error.includes('não encontrado'));
|
|
});
|
|
|
|
test('GatewayDaemon - FILE_READ_REQ: Bloqueio defensivo para arquivos que excedem 20 MB', async () => {
|
|
const daemon = new GatewayDaemon({ pin: '112233' });
|
|
const mockWs = new MockSocket();
|
|
daemon.ws = mockWs;
|
|
daemon.connected = true;
|
|
|
|
// Cria temporariamente um arquivo fictício e testa ou mocka fs.statSync
|
|
const originalStat = fs.statSync;
|
|
try {
|
|
fs.statSync = (targetPath) => {
|
|
if (String(targetPath).includes('mock-large-file.bin')) {
|
|
return {
|
|
isFile: () => true,
|
|
size: 21 * 1024 * 1024 // 21 MB
|
|
};
|
|
}
|
|
return originalStat(targetPath);
|
|
};
|
|
|
|
// Cria arquivo vazio temporário
|
|
const largeDummy = path.resolve(process.cwd(), 'mock-large-file.bin');
|
|
fs.writeFileSync(largeDummy, 'dummy');
|
|
|
|
await daemon.handleRelayMessage({
|
|
type: 'FILE_READ_REQ',
|
|
path: 'mock-large-file.bin',
|
|
agentName: 'Claude'
|
|
});
|
|
|
|
assert.equal(mockWs.sent.length, 1);
|
|
const resp = JSON.parse(mockWs.sent[0]);
|
|
assert.equal(resp.type, 'FILE_READ_RESP');
|
|
assert.equal(resp.ok, false);
|
|
assert.ok(resp.error.includes('20 MB'));
|
|
|
|
if (fs.existsSync(largeDummy)) fs.unlinkSync(largeDummy);
|
|
} finally {
|
|
fs.statSync = originalStat;
|
|
}
|
|
});
|
|
|
|
test('Relay - handleClientWsMessage deve rotear FILE_READ_REQ para Gateway e devolver erro se offline', () => {
|
|
const manager = new SessionManager();
|
|
const gatewayWs = new MockSocket();
|
|
const clientWs = new MockSocket();
|
|
const pin = '556677';
|
|
const loggedEvents = [];
|
|
const mockTelemetry = { logEvent: (evt) => loggedEvents.push(evt) };
|
|
|
|
// 1. Estação offline: deve responder erro imediato ao cliente
|
|
handleClientWsMessage({
|
|
ws: clientWs,
|
|
sessionPin: pin,
|
|
msg: {
|
|
type: 'FILE_READ_REQ',
|
|
path: 'evidence/test.png',
|
|
agentName: 'Claude'
|
|
},
|
|
sessionManager: manager,
|
|
telemetryService: mockTelemetry
|
|
});
|
|
|
|
assert.equal(clientWs.sent.length, 1);
|
|
const offlineResp = JSON.parse(clientWs.sent[0]);
|
|
assert.equal(offlineResp.type, 'FILE_READ_RESP');
|
|
assert.equal(offlineResp.ok, false);
|
|
assert.ok(offlineResp.error.includes('offline'));
|
|
|
|
// 2. Conecta Gateway e reenvia: deve encaminhar com telemetria
|
|
manager.registerGateway(pin, gatewayWs, 'Estacao-Dev');
|
|
clientWs.sent.length = 0;
|
|
|
|
handleClientWsMessage({
|
|
ws: clientWs,
|
|
sessionPin: pin,
|
|
msg: {
|
|
type: 'FILE_READ_REQ',
|
|
path: 'docs/spec.md',
|
|
agentName: 'Claude',
|
|
chatId: 'chat-99'
|
|
},
|
|
sessionManager: manager,
|
|
telemetryService: mockTelemetry
|
|
});
|
|
|
|
assert.equal(gatewayWs.sent.length, 1);
|
|
const forwarded = JSON.parse(gatewayWs.sent[0]);
|
|
assert.equal(forwarded.type, 'FILE_READ_REQ');
|
|
assert.equal(forwarded.path, 'docs/spec.md');
|
|
assert.equal(forwarded.agentName, 'Claude');
|
|
|
|
assert.equal(loggedEvents.length, 2);
|
|
assert.equal(loggedEvents[1].category, 'file_transfer');
|
|
assert.equal(loggedEvents[1].action, 'file_read_req');
|
|
});
|
|
|
|
test('Relay - handleGatewayWsMessage deve fazer broadcast de FILE_READ_RESP aos clientes e logar telemetria', () => {
|
|
const manager = new SessionManager();
|
|
const gatewayWs = new MockSocket();
|
|
const clientWs = new MockSocket();
|
|
const loggedEvents = [];
|
|
const pin = '889900';
|
|
|
|
manager.registerGateway(pin, gatewayWs, 'Estacao-Files');
|
|
manager.registerClient(pin, clientWs);
|
|
clientWs.sent.length = 0;
|
|
|
|
handleGatewayWsMessage({
|
|
sessionPin: pin,
|
|
msg: {
|
|
type: 'FILE_READ_RESP',
|
|
path: 'docs/evidence.png',
|
|
name: 'evidence.png',
|
|
mimeType: 'image/png',
|
|
size: 4096,
|
|
contentBase64: 'aW1n',
|
|
ok: true,
|
|
chatId: 'chat-88',
|
|
agentName: 'Claude'
|
|
},
|
|
sessionManager: manager,
|
|
telemetryService: { logEvent: (evt) => loggedEvents.push(evt) }
|
|
});
|
|
|
|
assert.equal(clientWs.sent.length, 1);
|
|
const clientMsg = JSON.parse(clientWs.sent[0]);
|
|
assert.equal(clientMsg.type, 'FILE_READ_RESP');
|
|
assert.equal(clientMsg.name, 'evidence.png');
|
|
assert.equal(clientMsg.ok, true);
|
|
assert.equal(clientMsg.size, 4096);
|
|
|
|
assert.equal(loggedEvents.length, 1);
|
|
assert.equal(loggedEvents[0].category, 'file_transfer');
|
|
assert.equal(loggedEvents[0].action, 'file_read_resp');
|
|
});
|
|
|
|
test('Frontend - extractFilePaths, renderFileChips e modais de preview devem funcionar no ambiente JSDOM', async () => {
|
|
const { JSDOM } = await import('jsdom');
|
|
const html = `
|
|
<!DOCTYPE html>
|
|
<html>
|
|
<body>
|
|
<div id="container"></div>
|
|
<div id="file-preview-modal" style="display: none;">
|
|
<span id="file-preview-icon"></span>
|
|
<h3 id="file-preview-title"></h3>
|
|
<span id="file-preview-meta"></span>
|
|
<div id="file-preview-body"></div>
|
|
<button id="btn-copy-file-content" style="display: none;"></button>
|
|
<button id="btn-save-file"></button>
|
|
</div>
|
|
</body>
|
|
</html>
|
|
`;
|
|
const dom = new JSDOM(html);
|
|
global.window = dom.window;
|
|
global.document = dom.window.document;
|
|
Object.defineProperty(globalThis, 'navigator', { value: dom.window.navigator, configurable: true, writable: true });
|
|
global.WebSocket = MockSocket;
|
|
|
|
// Executa o script do app
|
|
await import('../public/app.js');
|
|
const extractFilePaths = dom.window.extractFilePaths;
|
|
const renderFileChips = dom.window.renderFileChips;
|
|
const openFilePreviewModal = dom.window.openFilePreviewModal;
|
|
const closeFilePreviewModal = dom.window.closeFilePreviewModal;
|
|
|
|
assert.equal(typeof extractFilePaths, 'function', 'extractFilePaths deve estar exposta no window');
|
|
assert.equal(typeof renderFileChips, 'function', 'renderFileChips deve estar exposta no window');
|
|
assert.equal(typeof openFilePreviewModal, 'function', 'openFilePreviewModal deve estar exposta no window');
|
|
assert.equal(typeof closeFilePreviewModal, 'function', 'closeFilePreviewModal deve estar exposta no window');
|
|
|
|
// 1. Testa regex e extração de caminhos
|
|
const sampleOutput = `
|
|
Arquivo gerado em docs/changes/0-download-arquivos-terminal-app/spec.md com sucesso!
|
|
Evidência salva em 'evidence/print.png'.
|
|
Ignorar versão v1.0.2 e link https://remote.winicomw.ddnsfree.com/api/health.
|
|
Log final em test.log e script deploy.ps1.
|
|
`;
|
|
|
|
const paths = extractFilePaths(sampleOutput);
|
|
assert.ok(paths.includes('docs/changes/0-download-arquivos-terminal-app/spec.md'));
|
|
assert.ok(paths.includes('evidence/print.png'));
|
|
assert.ok(paths.includes('test.log'));
|
|
assert.ok(paths.includes('deploy.ps1'));
|
|
assert.ok(!paths.some(p => p.includes('http')));
|
|
assert.ok(!paths.some(p => p === 'v1.0.2'));
|
|
|
|
// 2. Testa criação dos chips
|
|
const chipsContainer = renderFileChips(paths);
|
|
assert.equal(chipsContainer.className, 'file-chips-container');
|
|
const buttons = chipsContainer.querySelectorAll('.btn-file-chip');
|
|
assert.equal(buttons.length, paths.length);
|
|
assert.equal(buttons[0].getAttribute('data-path'), paths[0]);
|
|
|
|
// 3. Testa Preview de Arquivo de Texto / Código
|
|
const modal = dom.window.document.getElementById('file-preview-modal');
|
|
const title = dom.window.document.getElementById('file-preview-title');
|
|
const meta = dom.window.document.getElementById('file-preview-meta');
|
|
const body = dom.window.document.getElementById('file-preview-body');
|
|
const copyBtn = dom.window.document.getElementById('btn-copy-file-content');
|
|
|
|
const textSample = '# Spec Markdown\nLinha 2 de teste';
|
|
const textBase64 = Buffer.from(textSample, 'utf8').toString('base64');
|
|
|
|
openFilePreviewModal({
|
|
name: 'spec.md',
|
|
path: 'docs/spec.md',
|
|
mimeType: 'text/markdown',
|
|
size: Buffer.byteLength(textSample),
|
|
contentBase64: textBase64,
|
|
ok: true
|
|
});
|
|
|
|
assert.equal(modal.style.display, 'flex');
|
|
assert.equal(title.textContent, 'spec.md');
|
|
assert.ok(meta.textContent.includes('text/markdown'));
|
|
assert.equal(copyBtn.style.display, 'inline-flex');
|
|
const codeEl = body.querySelector('code.file-preview-code');
|
|
assert.ok(codeEl, 'Deve conter bloco de código para texto');
|
|
assert.equal(codeEl.textContent, textSample);
|
|
|
|
// 4. Testa Preview de Imagem
|
|
openFilePreviewModal({
|
|
name: 'evidence.png',
|
|
path: 'evidence/evidence.png',
|
|
mimeType: 'image/png',
|
|
size: 1024,
|
|
contentBase64: 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==',
|
|
ok: true
|
|
});
|
|
|
|
assert.equal(title.textContent, 'evidence.png');
|
|
assert.equal(copyBtn.style.display, 'none');
|
|
const imgEl = body.querySelector('img.file-preview-image');
|
|
assert.ok(imgEl, 'Deve renderizar elemento img para imagens');
|
|
assert.ok(imgEl.src.startsWith('data:image/png;base64,'));
|
|
|
|
// 5. Fechar modal
|
|
closeFilePreviewModal();
|
|
assert.equal(modal.style.display, 'none');
|
|
|
|
dom.window.close();
|
|
delete global.window;
|
|
delete global.document;
|
|
delete global.WebSocket;
|
|
});
|