| const { BrowserWindow, ipcMain } = require('electron'); |
| const path = require('path'); |
|
|
| |
| 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' |
| ]); |
|
|
| |
| 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' |
| ]); |
|
|
| |
| |
| |
| class DebugManager { |
| constructor() { |
| this.debugWindow = null; |
| this.mainWindow = null; |
| this.logs = []; |
| this.commandHistory = []; |
| this.maxLogs = 1000; |
| this.maxCommandHistory = 100; |
| |
| this.setupIpcHandlers(); |
| } |
|
|
| |
| |
| |
| 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() { |
| |
| ipcMain.handle('diagnostics:get-logs', async (event, options = {}) => { |
| const limit = options.limit || 100; |
| return this.logs.slice(0, limit); |
| }); |
|
|
| |
| ipcMain.handle('diagnostics:get-health', async () => { |
| try { |
| |
| return { |
| cpu: 0, |
| memory: process.memoryUsage().rss, |
| connections: 0, |
| uptime: process.uptime() |
| }; |
| } catch (error) { |
| console.error('Error getting health metrics:', error); |
| return { |
| cpu: 0, |
| memory: 0, |
| connections: 0, |
| uptime: process.uptime() |
| }; |
| } |
| }); |
|
|
| |
| 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 []; |
| } |
| }); |
|
|
| |
| ipcMain.handle('diagnostics:get-command-history', async () => { |
| return this.commandHistory.slice(0, 50); |
| }); |
|
|
| |
| ipcMain.handle('diagnostics:clear-command-history', async () => { |
| this.commandHistory = []; |
| return true; |
| }); |
|
|
| |
| ipcMain.handle('diagnostics:run-e2e-tests', async () => { |
| return this.runE2eTests(); |
| }); |
|
|
| |
| ipcMain.handle('diagnostics:open-test-report', async () => { |
| return this.openTestReport(); |
| }); |
|
|
| |
| 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); |
| } |
|
|
| |
| const sanitizedCommand = command.trim(); |
| const commandBase = sanitizedCommand.split(' ')[0].toLowerCase(); |
| |
| |
| 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 }; |
| } |
|
|
| |
| 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}`); |
| |
| |
| if (this.debugWindow && !this.debugWindow.isDestroyed()) { |
| this.debugWindow.webContents.send('terminal:command-executed', commandEntry); |
| } |
|
|
| |
| if (commandBase === 'help') { |
| return this.handleHelpCommand(); |
| |
| } 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); |
| } |
| } |
|
|
| |
| |
| 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 }; |
| } |
|
|
| |
| 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); |
|
|
| |
| if (this.logs.length > this.maxLogs) { |
| this.logs = this.logs.slice(0, this.maxLogs); |
| } |
|
|
| |
| if (this.debugWindow && !this.debugWindow.isDestroyed()) { |
| this.debugWindow.webContents.send('diagnostic:new-log', processedLog); |
| this.debugWindow.webContents.send('terminal:new-log', processedLog); |
| } |
| } |
|
|
| |
| sendHealthUpdate(healthData) { |
| if (this.debugWindow && !this.debugWindow.isDestroyed()) { |
| this.debugWindow.webContents.send('diagnostic:health-update', healthData); |
| } |
| } |
|
|
| |
| sendWorkflowsUpdate(workflowsData) { |
| if (this.debugWindow && !this.debugWindow.isDestroyed()) { |
| this.debugWindow.webContents.send('diagnostic:workflows-update', workflowsData); |
| } |
| } |
|
|
| |
| 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`); |
| } |
| } |
|
|
| |
| 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() |
| }); |
| } |
| } |
|
|
| |
| closeDebugWindow() { |
| if (this.debugWindow && !this.debugWindow.isDestroyed()) { |
| this.debugWindow.close(); |
| } |
| } |
|
|
| |
| 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'); |
| } |
| } |
|
|
| |
| 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; |
| } |
|
|
| |
| 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' |
| |
| }); |
|
|
| 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 |
| }; |
| } |
| } |
|
|
| |
| 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 ก่อน' |
| }; |
| } |
|
|
| |
| 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; |