chahuadev-framework-en / debug-manager.js
chahuadev
Update README
857cdcf
const { BrowserWindow, ipcMain } = require('electron');
const path = require('path');
// --- Command Firewall: Whitelist ของคำสั่งที่ปลอดภัย ---
const ALLOWED_COMMANDS = new Set([
// คำสั่งภายในระบบ
'help', 'clear', 'workflows', 'cache', 'logs', 'status', 'info', 'test', 'e2e', 'report',
// คำสั่งภายนอกที่ปลอดภัย
'node', 'npm', 'git', 'ping', 'tracert', 'ipconfig', 'ifconfig', 'whoami', 'date', 'time',
// คำสั่งสำหรับการพัฒนา
'npx', 'playwright', 'jest', 'mocha', 'yarn', 'pnpm',
// คำสั่งระบบพื้นฐาน
'echo', 'pwd', 'ls', 'dir', 'hostname', 'uname'
]);
// --- Blacklist ของคำสั่งอันตราย ---
const DANGEROUS_COMMANDS = new Set([
'rm', 'rmdir', 'del', 'deltree', 'format', 'fdisk', 'mkfs', 'dd',
'shutdown', 'reboot', 'halt', 'poweroff', 'init', 'killall', 'pkill',
'chmod', 'chown', 'su', 'sudo', 'passwd', 'useradd', 'userdel',
'wget', 'curl', 'nc', 'netcat', 'telnet', 'ftp', 'sftp',
'eval', 'exec', 'system', 'shell', 'bash', 'sh', 'cmd', 'powershell',
'python', 'php', 'perl', 'ruby', 'java', 'javac'
]);
/**
* Debug Manager - จัดการหน้าต่าง Hybrid Diagnostic Dashboard
*/
class DebugManager {
constructor() {
this.debugWindow = null;
this.mainWindow = null; // เพิ่ม property สำหรับ main window
this.logs = [];
this.commandHistory = [];
this.maxLogs = 1000;
this.maxCommandHistory = 100;
this.setupIpcHandlers();
}
/**
* ตั้งค่า main window reference
*/
setMainWindow(window) {
this.mainWindow = window;
console.log(' Main Window connected to Debug Manager');
}
createDebugWindow() {
if (this.debugWindow && !this.debugWindow.isDestroyed()) {
this.debugWindow.focus();
return;
}
this.debugWindow = new BrowserWindow({
width: 1600,
height: 1000,
minWidth: 1200,
minHeight: 800,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.join(__dirname, 'preload.js')
},
title: 'Chahuadev Hybrid Diagnostic Dashboard',
icon: path.join(__dirname, 'src/assets/icons/icon.png'),
show: false,
backgroundColor: '#1a1a1a'
});
this.debugWindow.loadFile('debugger.html');
this.debugWindow.once('ready-to-show', () => {
this.debugWindow.show();
this.sendWelcomeMessage();
});
this.debugWindow.on('closed', () => {
this.debugWindow = null;
});
console.log(' Hybrid Debug Window สร้างแล้ว');
}
sendWelcomeMessage() {
if (this.debugWindow && !this.debugWindow.isDestroyed()) {
this.debugWindow.webContents.send('terminal:welcome', {
message: 'Hybrid Diagnostic Dashboard ready!',
timestamp: new Date().toISOString()
});
}
}
setupIpcHandlers() {
// ดึง logs ย้อนหลัง
ipcMain.handle('diagnostics:get-logs', async (event, options = {}) => {
const limit = options.limit || 100;
return this.logs.slice(0, limit);
});
// ดึงข้อมูล health
ipcMain.handle('diagnostics:get-health', async () => {
try {
// Simplified health data without health-monitor dependency
return {
cpu: 0, // Placeholder - health monitoring removed
memory: process.memoryUsage().rss,
connections: 0, // Placeholder
uptime: process.uptime()
};
} catch (error) {
console.error('Error getting health metrics:', error);
return {
cpu: 0,
memory: 0,
connections: 0,
uptime: process.uptime()
};
}
});
// ดึงข้อมูล running workflows - Disabled (workflow engine removed)
ipcMain.handle('diagnostics:get-workflows', async () => {
try {
console.log(' Workflow engine has been removed from system');
return [];
} catch (error) {
console.error('Error getting workflows:', error);
return [];
}
});
// Command history
ipcMain.handle('diagnostics:get-command-history', async () => {
return this.commandHistory.slice(0, 50); // Return last 50 commands
});
// Clear command history
ipcMain.handle('diagnostics:clear-command-history', async () => {
this.commandHistory = [];
return true;
});
// E2E Testing
ipcMain.handle('diagnostics:run-e2e-tests', async () => {
return this.runE2eTests();
});
// Open Test Report
ipcMain.handle('diagnostics:open-test-report', async () => {
return this.openTestReport();
});
// Terminal-specific handlers
ipcMain.handle('terminal:execute-command', async (event, command) => {
return this.executeTerminalCommand(command);
});
ipcMain.handle('terminal:get-system-info', async () => {
return {
platform: process.platform,
arch: process.arch,
nodeVersion: process.version,
pid: process.pid,
uptime: process.uptime(),
memory: process.memoryUsage(),
cwd: process.cwd()
};
});
}
async executeTerminalCommand(command) {
const commandEntry = {
command,
timestamp: new Date().toISOString(),
id: Date.now()
};
this.commandHistory.unshift(commandEntry);
if (this.commandHistory.length > this.maxCommandHistory) {
this.commandHistory = this.commandHistory.slice(0, this.maxCommandHistory);
}
// --- Security Check: Command Firewall ---
const sanitizedCommand = command.trim();
const commandBase = sanitizedCommand.split(' ')[0].toLowerCase();
// ตรวจสอบ Blacklist ก่อน (เพื่อความปลอดภัยสูงสุด)
if (DANGEROUS_COMMANDS.has(commandBase)) {
const errorMessage = ` SECURITY ALERT: Command '${commandBase}' is explicitly blocked for security reasons!`;
console.warn(`[Security] Blocked dangerous command: ${command}`);
this.sendTerminalMessage(errorMessage, 'error');
this.sendCommandResult(command, null, errorMessage);
return { success: false, error: errorMessage, blocked: true };
}
// ตรวจสอบ Whitelist
if (!ALLOWED_COMMANDS.has(commandBase)) {
const errorMessage = ` Command '${commandBase}' is not whitelisted. Only approved commands are allowed.`;
console.warn(`[Security] Blocked non-whitelisted command: ${command}`);
this.sendTerminalMessage(errorMessage, 'error');
this.sendCommandResult(command, null, errorMessage);
return { success: false, error: errorMessage, blocked: true };
}
// คำสั่งผ่านการตรวจสอบแล้ว
console.log(`[Security] Command approved: ${command}`);
// Broadcast command to debug window
if (this.debugWindow && !this.debugWindow.isDestroyed()) {
this.debugWindow.webContents.send('terminal:command-executed', commandEntry);
}
// จัดการคำสั่งภายในระบบ
if (commandBase === 'help') {
return this.handleHelpCommand();
// Clear command removed - prevents clearing of real-time logs
} else if (commandBase === 'status') {
return this.handleStatusCommand();
} else if (commandBase === 'e2e') {
return this.runE2eTests();
} else if (commandBase === 'report') {
return this.openTestReport();
} else {
// สำหรับคำสั่งภายนอก ให้จำลองการทำงาน (ไม่รันจริง)
return this.handleExternalCommand(sanitizedCommand);
}
}
// --- Security Command Handlers ---
handleHelpCommand() {
const helpText = `
Secure Terminal Commands:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
System Commands:
help - Show this help message
clear - Clear terminal screen
status - Show system status
info - Show system information
Testing Commands:
e2e - Run E2E tests
report - Open test report
Diagnostic Commands:
logs - Show system logs
workflows - Show running workflows
cache - Show cache information
Security Notice:
Only whitelisted commands are allowed
Dangerous commands are blocked for security
All commands are logged for audit
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
`;
this.sendTerminalMessage(helpText, 'info');
return { success: true, output: helpText };
}
handleClearCommand() {
if (this.debugWindow && !this.debugWindow.isDestroyed()) {
this.debugWindow.webContents.send('terminal:clear');
}
return { success: true, output: 'Terminal cleared' };
}
handleStatusCommand() {
const stats = this.getStats();
const statusText = `
System Status:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Logs: ${stats.totalLogs}
Commands: ${stats.totalCommands}
Debug Window: ${stats.isWindowOpen ? 'Open' : 'Closed'}
Uptime: ${Math.floor(stats.uptime)}s
Memory: ${Math.round(stats.memoryUsage.rss / 1024 / 1024)} MB
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
`;
this.sendTerminalMessage(statusText, 'info');
return { success: true, output: statusText };
}
handleExternalCommand(command) {
// จำลองการทำงานของคำสั่งภายนอกโดยไม่รันจริง
const simulatedOutput = `
Security Mode: External command simulation
Command: ${command}
Status: Approved but not executed for security reasons
Note: This is a simulated response to prevent potential security risks
`;
this.sendTerminalMessage(simulatedOutput, 'info');
this.sendCommandResult(command, simulatedOutput);
return { success: true, output: simulatedOutput, simulated: true };
}
// เพิ่ม log ใหม่
addLog(logData) {
const processedLog = {
id: Date.now() + Math.random(),
timestamp: logData.timestamp || new Date().toISOString(),
level: logData.level || 'info',
source: logData.source || 'System',
message: logData.message || '',
error: logData.error || null,
stack: logData.stack || null,
context: logData.context || {},
filePath: logData.filePath || null,
lineNumber: logData.lineNumber || null,
functionName: logData.functionName || null,
codeSnippet: logData.codeSnippet || null
};
this.logs.unshift(processedLog);
// จำกัดจำนวน logs
if (this.logs.length > this.maxLogs) {
this.logs = this.logs.slice(0, this.maxLogs);
}
// ส่งไปยัง debug window ถ้าเปิดอยู่
if (this.debugWindow && !this.debugWindow.isDestroyed()) {
this.debugWindow.webContents.send('diagnostic:new-log', processedLog);
this.debugWindow.webContents.send('terminal:new-log', processedLog);
}
}
// ส่งข้อมูล health update
sendHealthUpdate(healthData) {
if (this.debugWindow && !this.debugWindow.isDestroyed()) {
this.debugWindow.webContents.send('diagnostic:health-update', healthData);
}
}
// ส่งข้อมูล workflows update
sendWorkflowsUpdate(workflowsData) {
if (this.debugWindow && !this.debugWindow.isDestroyed()) {
this.debugWindow.webContents.send('diagnostic:workflows-update', workflowsData);
}
}
// ส่งข้อความไปยัง terminal
sendTerminalMessage(message, type = 'info') {
console.log(`[DebugManager] Sending terminal message: ${message} (type: ${type})`);
if (this.debugWindow && !this.debugWindow.isDestroyed()) {
this.debugWindow.webContents.send('terminal:message', {
message,
type,
timestamp: new Date().toISOString()
});
console.log(`[DebugManager] Terminal message sent successfully`);
} else {
console.log(`[DebugManager] Debug window is not available or destroyed`);
}
}
// ส่งผลลัพธ์คำสั่งไปยัง terminal
sendCommandResult(command, result, error = null) {
if (this.debugWindow && !this.debugWindow.isDestroyed()) {
this.debugWindow.webContents.send('terminal:command-result', {
command,
result,
error,
timestamp: new Date().toISOString()
});
}
}
// ปิด debug window
closeDebugWindow() {
if (this.debugWindow && !this.debugWindow.isDestroyed()) {
this.debugWindow.close();
}
}
// ตรวจสอบว่า debug window เปิดอยู่หรือไม่
isDebugWindowOpen() {
return this.debugWindow && !this.debugWindow.isDestroyed();
}
// รับข้อมูลสถิติ
getStats() {
return {
totalLogs: this.logs.length,
totalCommands: this.commandHistory.length,
isWindowOpen: this.isDebugWindowOpen(),
uptime: process.uptime(),
memoryUsage: process.memoryUsage()
};
}
// เคลียร์ข้อมูลทั้งหมด
clearAllData() {
this.logs = [];
this.commandHistory = [];
if (this.debugWindow && !this.debugWindow.isDestroyed()) {
this.debugWindow.webContents.send('terminal:clear-all');
}
}
// Export logs
exportLogs(filepath) {
const fs = require('fs');
const exportData = {
timestamp: new Date().toISOString(),
logs: this.logs,
commandHistory: this.commandHistory,
stats: this.getStats()
};
fs.writeFileSync(filepath, JSON.stringify(exportData, null, 2));
return true;
}
// E2E Testing ระบบ - เวอร์ชันแก้ไข: แก้ปัญหา CLI ไม่รันคำสั่ง
async runE2eTests() {
const { spawn } = require('child_process');
const path = require('path');
this.sendTerminalMessage(' Launching E2E tests in a new CLI window...', 'info');
try {
const projectRoot = process.cwd();
const testCommand = `cd /d "${projectRoot}" && npx playwright test && echo. && echo. && echo ================================= && echo. && echo E2E Tests Finished. && echo. && echo ================================= && pause || echo. && echo. && echo ================================= && echo. && echo E2E Tests Failed. && echo. && echo ================================= && pause`;
const terminalProcess = spawn('cmd.exe', ['/k', testCommand], {
detached: true,
stdio: 'ignore'
// shell: true <-- เอาบรรทัดนี้ออก
});
terminalProcess.unref();
const successMessage = ' E2E tests started in a new CLI window.';
this.sendTerminalMessage(successMessage, 'success');
return {
success: true,
message: successMessage
};
} catch (error) {
const errorMessage = ` Failed to launch E2E test window: ${error.message}`;
this.sendTerminalMessage(errorMessage, 'error');
return {
success: false,
error: error.message
};
}
}
// เปิดรายงานผลการทดสอบ HTML
async openTestReport() {
const { shell } = require('electron');
const path = require('path');
const fs = require('fs');
try {
const testResultsPath = path.join(process.cwd(), 'test-results');
const indexPath = path.join(testResultsPath, 'index.html');
this.sendTerminalMessage('Checking for test report...', 'info');
// ตรวจสอบว่ามีไฟล์รายงานหรือไม่
if (!fs.existsSync(indexPath)) {
return {
success: false,
error: 'ไม่พบรายงานผลการทดสอบ - โปรดรันการทดสอบ E2E ก่อน'
};
}
// เปิดไฟล์รายงานด้วย default browser
await shell.openPath(indexPath);
this.sendTerminalMessage('HTML Test Report opened successfully', 'success');
return {
success: true,
message: 'เปิดรายงานผลการทดสอบใน Browser แล้ว',
reportPath: indexPath
};
} catch (error) {
const errorMessage = `Failed to open test report: ${error.message}`;
this.sendTerminalMessage(errorMessage, 'error');
return {
success: false,
error: error.message
};
}
}
}
module.exports = DebugManager;