File size: 19,452 Bytes
857cdcf | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 | 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; |