chahuadev commited on
Commit ·
857cdcf
1
Parent(s): 0c3905c
Update README
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+7-60
- .gitignoreAdded+84
- .wslconfigAdded+11
- ApiTraceDebugger.jsAdded+284
- LICENSE.mdAdded+54
- README.md+263-3
- app.htmlAdded
- auth-dialog.jsAdded+171
- backend/utils/inspector-worker.jsAdded+169
- backend/utils/project-inspector-ipc.jsAdded+247
- backend/utils/project-inspector.jsAdded+1813
- build-desktop.batAdded+220
- build-linux-wsl.shAdded+90
- build_assets/plugins/.gitkeepAdded+2
- checksums.jsonAdded+13
- checksums.sigAdded+1
- config/default.jsonAdded+102
- config/obfuscator.config.jsAdded+143
- config/production.jsonAdded+102
- debug-manager.jsAdded+501
- debugger.htmlAdded+884
- debugger.jsAdded+659
- generate-checksums.jsAdded+73
- generate-manifests.jsAdded+124
- junk-map-layout.jsonAdded+242
- main.jsAdded+2464
- modules/button-generator.jsAdded+621
- modules/cache-manager.jsAdded+350
- modules/callback-hub.jsAdded+202
- modules/callback-logger.jsAdded+147
- modules/cli.jsAdded+301
- modules/context-manager.jsAdded+368
- modules/error-handler.jsAdded+380
- modules/executor.jsAdded+242
- modules/health-monitor.jsAdded+207
- modules/key-system.jsAdded+167
- modules/plugin-manager.jsAdded+96
- modules/retry-controller.jsAdded+131
- modules/rollback-manager.jsAdded+274
- modules/security-logger.jsAdded+346
- modules/svg-icons.jsAdded+253
- modules/system-detector.jsAdded+1157
- modules/tamper-detector.jsAdded+387
- npm-runner.batAdded+144
- package.jsonAdded+261
- packages/@chahuadev/framework/LICENSE.mdAdded+54
- packages/@chahuadev/framework/README.mdAdded+143
- packages/@chahuadev/framework/index.jsAdded+26
- packages/@chahuadev/framework/install.jsAdded+73
- packages/@chahuadev/framework/package.jsonAdded+16
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.avro filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.lz4 filter=lfs diff=lfs merge=lfs -text*.mds filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text# Audio files - uncompressed*.pcm filter=lfs diff=lfs merge=lfs -text*.sam filter=lfs diff=lfs merge=lfs -text*.raw filter=lfs diff=lfs merge=lfs -text# Audio files - compressed*.aac filter=lfs diff=lfs merge=lfs -text*.flac filter=lfs diff=lfs merge=lfs -text*.mp3 filter=lfs diff=lfs merge=lfs -text*.ogg filter=lfs diff=lfs merge=lfs -text*.wav filter=lfs diff=lfs merge=lfs -text# Image files - uncompressed*.bmp filter=lfs diff=lfs merge=lfs -text*.gif filter=lfs diff=lfs merge=lfs -text*.png filter=lfs diff=lfs merge=lfs -text*.tiff filter=lfs diff=lfs merge=lfs -text# Image files - compressed*.jpg filter=lfs diff=lfs merge=lfs -text*.jpeg filter=lfs diff=lfs merge=lfs -text*.webp filter=lfs diff=lfs merge=lfs -text# Video files - compressed*.mp4 filter=lfs diff=lfs merge=lfs -text*.webm filter=lfs diff=lfs merge=lfs -text1234567chahuadev-junk-sweeper1.png filter=lfs diff=lfs merge=lfs -textchahuadev-junk-sweeper.png filter=lfs diff=lfs merge=lfs -texticons/icon.png filter=lfs diff=lfs merge=lfs -texticons/logo.ico filter=lfs diff=lfs merge=lfs -texticons/logo.png filter=lfs diff=lfs merge=lfs -texticons/icon.ico filter=lfs diff=lfs merge=lfs -texticons/app-icon.png filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384# Dependenciesnode_modules/npm-debug.log*yarn-debug.log*yarn-error.log*package-lock.jsonyarn.lock
# Runtime*.loglogs/pids/*.pid*.seed*.pid.lock
# Coverage and testingcoverage/.nyc_output/.jest/
# Environment.env.env.local.env.development.local.env.test.local.env.production.local
# Editor files.vscode/.idea/*.swp*.swo*~
# OS generated files.DS_Store.DS_Store?._*.Spotlight-V100.Trashesehthumbs.dbThumbs.db
# Backup directories (created by this tool)emoji-backup-*/backup-*/
# Temporary test filestest/temp/test/fixtures/temp/test
# Distributiondist/build/
# NPM.npm.npmrc
# Ignore binary imagesicons/
# Layout files (auto-generated per project)layouts/*.json
# Python runtime — downloaded at build time, never committed# Run: npm run download-python-win (Windows only, ~12 MB)runtimes/
# Python compiled cache__pycache__/*.pyc*.pyo
# .NET build artifactsengines/cs_scanner/bin/engines/cs_scanner/obj/*.pydlogo.icologo.png
icon.png1234567891011[interop]appendWindowsPath = true
[automount]enabled = trueroot = /mntoptions = "metadata,umask=0022,fmask=0011"mountFsTab = true
[filesystem]umask = 0022123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284// ApiTraceDebugger.js
const fs = require('fs');const path = require('path');const { app } = require('electron');
// เก็บ reference ของฟังก์ชันดั้งเดิมไว้ก่อนที่จะ patch เพื่อป้องกัน circular dependencyconst originalFs = { readFileSync: fs.readFileSync, writeFileSync: fs.writeFileSync, existsSync: fs.existsSync, mkdirSync: fs.mkdirSync, readdirSync: fs.readdirSync, unlinkSync: fs.unlinkSync, statSync: fs.statSync, createWriteStream: fs.createWriteStream};
const originalPath = { join: path.join, resolve: path.resolve, dirname: path.dirname, extname: path.extname, basename: path.basename, relative: path.relative};
/** * [ปรับปรุงใหม่] ระบบดีบั๊กสำหรับติดตามและบันทึก API Call ลงไฟล์แบบ Real-time * @class ApiTraceDebugger */class ApiTraceDebugger { constructor() { this.isActive = false; this.logStream = null; // Stream สำหรับเขียนไฟล์ this.logFilePath = null; // Path ของไฟล์ Log ปัจจุบัน this.originalFunctions = new Map(); this.pluginsPath = this._getPluginsPath(); }
/** * [ปรับปรุงใหม่] เริ่มการทำงาน, สร้างไฟล์ และเปิด Stream */ start() { if (this.isActive) { return; }
try { // ตรวจสอบว่า app พร้อมใช้งาน if (!app || !app.getPath) { console.warn('[API TRACE] App ยังไม่พร้อม ข้าม API Trace initialization'); return; }
// สร้างโฟลเดอร์สำหรับเก็บ Log ถ้ายังไม่มี const logDir = originalPath.join(app.getPath('userData'), 'logs', 'api-traces'); if (!originalFs.existsSync(logDir)) { originalFs.mkdirSync(logDir, { recursive: true }); }
// สร้างชื่อไฟล์ Log ที่ไม่ซ้ำกัน const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); this.logFilePath = originalPath.join(logDir, `trace-${timestamp}.log`);
// สร้าง Write Stream ไปยังไฟล์ Log this.logStream = originalFs.createWriteStream(this.logFilePath, { flags: 'a' });
this.isActive = true; this._writeHeader(); // เขียนข้อมูลเริ่มต้นลงไฟล์ console.log(`[API TRACE] REAL-TIME MODE: เริ่มบันทึก Log ไปที่ไฟล์: ${this.logFilePath}`);
// เริ่มทำการ Patch ฟังก์ชันเป้าหมาย this._patchAllFunctions();
} catch (error) { console.error('[API TRACE] ไม่สามารถเริ่มระบบ Real-time logger ได้:', error); this.isActive = false; } }
/** * [ปรับปรุงใหม่] หยุดการทำงานและปิด Stream */ stop() { if (!this.isActive) { return; } this.isActive = false; console.log('[API TRACE] หยุดการทำงานและกำลังคืนค่าฟังก์ชันดั้งเดิม...');
// คืนค่าฟังก์ชันดั้งเดิม this._unpatchAllFunctions();
// ปิด Stream และไฟล์ Log if (this.logStream) { this.logStream.end('\n--- LOGGING STOPPED ---\n'); this.logStream = null; console.log('[API TRACE] ปิดไฟล์ Log เรียบร้อยแล้ว'); } }
/** * [เพิ่มใหม่] ฟังก์ชันสำหรับหา Path ของโฟลเดอร์ plugins * @private */ _getPluginsPath() { try { // ตรวจสอบว่า app พร้อมใช้งานหรือไม่ก่อน if (!app || !app.getPath) { console.warn('[API TRACE] App ยังไม่พร้อม ข้าม plugins path detection'); return null; }
if (app.isPackaged) { // โหมด Production: โฟลเดอร์ plugins จะอยู่ข้างไฟล์ .exe // ใช้ originalPath เพื่อป้องกัน circular dependency return originalPath.join(originalPath.dirname(app.getPath('exe')), 'plugins'); } else { // โหมด Development: อยู่ใน AppData // ใช้ originalPath เพื่อป้องกัน circular dependency return originalPath.join(app.getPath('userData'), 'plugins'); } } catch (e) { console.warn('[API TRACE] ไม่สามารถหา Path ของโฟลเดอร์ plugins ได้:', e.message); return null; } }
/** * [แก้ไข] เพิ่มการกรองโฟลเดอร์ plugins เข้าไป * ฟังก์ชันค้นหาไฟล์และบรรทัดที่เรียกใช้ (Call Site) * @private */ _getCallSite() { const originalPrepareStackTrace = Error.prepareStackTrace; try { Error.prepareStackTrace = (_, stack) => stack; const err = new Error(); const stack = err.stack; Error.prepareStackTrace = originalPrepareStackTrace;
for (let i = 2; i < stack.length; i++) { const frame = stack[i]; const fileName = frame.getFileName();
if (fileName) { const isNodeModule = fileName.includes('node_modules'); const isInternal = fileName.startsWith('node:internal'); const isSelf = fileName.endsWith('ApiTraceDebugger.js'); // [แก้ไข] ตรวจสอบว่าเป็นไฟล์ในโฟลเดอร์ plugins หรือไม่ และใช้ originalPath const isPlugin = this.pluginsPath ? fileName.startsWith(this.pluginsPath) : false;
if (!isNodeModule && !isInternal && !isSelf && !isPlugin) { // ใช้ originalPath เพื่อป้องกัน circular dependency const relativePath = originalPath.relative(process.cwd(), fileName); return `${relativePath}:${frame.getLineNumber()}`; } } } } catch (e) { Error.prepareStackTrace = originalPrepareStackTrace; } return 'unknown'; }
/** * [ปรับปรุงใหม่] ฟังก์ชันภายในสำหรับบันทึก Log โดยจะเขียนลงไฟล์ทันที */ _logTrace(moduleName, functionName, args, result, error, callSite) { // ถ้า stream ไม่พร้อมทำงาน ให้ข้ามไป if (!this.logStream) { return; }
const logType = error ? '[API-ERR ]' : '[API-CALL]'; const timestamp = new Date().toISOString();
// จัดรูปแบบ Arguments และ ผลลัพธ์ const formatArg = (arg) => { if (typeof arg === 'string') { if (arg.length > 150) return `'${arg.substring(0, 147)}...'`; return `'${arg}'`; } if (typeof arg === 'object' && arg !== null) return JSON.stringify(arg); return String(arg); }; const argsString = args.map(formatArg).join(', ');
let outcomeString = ''; if (error) { outcomeString = `=> ERROR: ${error.message}`; } else { let resultStr = JSON.stringify(result); if (resultStr && resultStr.length > 200) { resultStr = resultStr.substring(0, 197) + '...'; } outcomeString = `=> RESULT: ${resultStr}`; }
// สร้าง Log 1 บรรทัดและเขียนลง Stream const line = `${timestamp} ${logType} ${moduleName}.${functionName}(${argsString}) ${outcomeString} (from ${callSite})\n`; this.logStream.write(line); }
/** * ฟังก์ชันภายในสำหรับทำการ Patch (แทนที่) ฟังก์ชันเป้าหมาย * @private */ _patchFunction(module, moduleName, functionName) { const originalFunction = module[functionName];
if (typeof originalFunction !== 'function' || this.originalFunctions.has(`${moduleName}.${functionName}`)) { return; }
this.originalFunctions.set(`${moduleName}.${functionName}`, originalFunction);
const self = this; const patchFunction = function (...args) { const callSite = self._getCallSite();
// [แก้ไข] เพิ่มการกรอง `plugins` เข้าไปในเงื่อนไข และใช้ originalPath const isNodeModule = callSite.includes('node_modules'); const isPlugin = self.pluginsPath ? callSite.startsWith(originalPath.relative(process.cwd(), self.pluginsPath)) : false;
// ถ้ามาจาก node_modules ��รือ plugins ให้ข้ามการบันทึก Log if (isNodeModule || isPlugin) { return originalFunction.apply(this, args); }
let result, error = null; try { result = originalFunction.apply(this, args); } catch (e) { error = e; }
self._logTrace(moduleName, functionName, args, result, error, callSite);
if (error) { throw error; } return result; };
module[functionName] = patchFunction; }
// ฟังก์ชันสำหรับวนลูป Patch (แยกออกมาเพื่อความสะอาด) _patchAllFunctions() { const modulesToTrace = { fs: ['readFileSync', 'writeFileSync', 'existsSync', 'mkdirSync', 'readdirSync', 'unlinkSync', 'statSync'], path: ['join', 'resolve', 'dirname', 'extname', 'basename'] }; for (const moduleName in modulesToTrace) { const functions = modulesToTrace[moduleName]; const module = require(moduleName); for (const functionName of functions) { this._patchFunction(module, moduleName, functionName); } } }
// ฟังก์ชันสำหรับวนลูป Unpatch _unpatchAllFunctions() { for (const [key, originalFunction] of this.originalFunctions.entries()) { const [module, functionName] = key.split('.'); require(module)[functionName] = originalFunction; } this.originalFunctions.clear(); }
// เขียน Header ลงไฟล์ Log _writeHeader() { if (!this.logStream) return; const header = `=========================================== Chahuadev API Trace Log (Real-time)===========================================Start Time : ${new Date().toISOString()}Platform : ${process.platform}Version : ${app.getVersion ? app.getVersion() : 'Unknown'}Log File : ${this.logFilePath}-------------------------------------------
`; this.logStream.write(header); }}
module.exports = new ApiTraceDebugger();123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354# CHAHUADEV NON-COMMERCIAL & ACCEPTABLE USE LICENSE
Copyright (c) 2026 Chahuadev. All rights reserved.
This software and its source code are provided for educational, personal, and open-source community use. By downloading, accessing, or using this software, you agree to the following conditions:
---
## 1. FREE DISTRIBUTION ONLY (การแจกจ่ายต้องฟรีเท่านั้น)
You are permitted to download, copy, modify, and distribute the software and its source code, provided that such distribution is **strictly free of charge**.
---
## 2. NO COMMERCIAL USE (ห้ามใช้หรือดัดแปลงเพื่อการค้า)
You may **NOT** use, modify, distribute, or incorporate this software (or any of its parts) for any commercial purposes. This includes, but is not limited to:
- Selling the software or derived versions.- Locking the software behind a paywall or subscription.- Using the software to provide commercial services.- Placing advertisements within the software.
---
## 3. ACCEPTABLE USE / NO MALICIOUS USE (ห้ามใช้ในทางที่ผิด)
This software must not be used for any illegal, malicious, or harmful activities. You are strictly prohibited from using this codebase to:
- Create malware, ransomware, or any destructive software.- Bypass security systems, steal data, or perform unauthorized access.- Violate any local, national, or international laws.
If the software is found to be used in violation of these terms, your license to use it is immediately and permanently terminated without notice.
---
## 4. ATTRIBUTION (ต้องแสดงแหล่งที่มา)
Any permitted distribution or modification must clearly credit the original author:
> Original work by **Chahuadev** — https://chahuadev.com
You may not remove, obscure, or alter any copyright notices or attribution present in the source code or documentation.
---
## 5. DISCLAIMER OF LIABILITY (ข้อสงวนสิทธิ์ความรับผิดชอบ)
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---
For questions regarding licensing, contact: **Chahuadev** via https://chahuadev.com123---license: mit---123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263# Chahuadev Framework - Plugin Management System> Electron-based Desktop Application for Managing and Executing NPM Projects---## DocumentationAll documentation files have been organized in the `docs/` folder:### Core Documentation- **[docs/README.md](docs/README.md)** - Original project README- **[docs/IMPLEMENTATION_COMPLETE.txt](docs/IMPLEMENTATION_COMPLETE.txt)** - Project implementation status- **[docs/EMOJI_REMOVAL_COMPLETE.md](docs/EMOJI_REMOVAL_COMPLETE.md)** - Emoji removal system documentation### Authentication & Security- **[docs/OFFLINE_AUTH_GUIDE.md](docs/OFFLINE_AUTH_GUIDE.md)** - Offline authentication system guide- **[docs/OFFLINE_AUTH_CHANGES.md](docs/OFFLINE_AUTH_CHANGES.md)** - Offline authentication changes and implementation- **[docs/AUTH_SECURITY_GUIDE.md](docs/AUTH_SECURITY_GUIDE.md)** - Authentication security in ValidationGateway- **[docs/AUTH_SECURITY_IMPLEMENTATION.txt](docs/AUTH_SECURITY_IMPLEMENTATION.txt)** - Auth security implementation details- **[docs/SWITCH_TO_OAUTH_GUIDE.md](docs/SWITCH_TO_OAUTH_GUIDE.md)** - How to switch back to OAuth---## 🐧 Running the AppImage on Linux / WSL2 (Ubuntu)First install the required system libraries (one-time setup):```bashsudo apt-get update && sudo apt-get install -y \libnss3 libatk1.0-0 libatk-bridge2.0-0 libcups2 \libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 \libxrandr2 libgbm1 libasound2```Then run the AppImage:```bashchmod +x "Chahuadev-Framework.AppImage"DISPLAY=:0 WAYLAND_DISPLAY=wayland-0 \./"Chahuadev-Framework.AppImage" \--appimage-extract-and-run --no-sandbox --disable-gpu```> **WSL2 tip:** Copy the AppImage to the WSL native filesystem first for best performance:> ```bash> # Path after: npm install -g @chahuadev/framework> # (no sudo)> cp ~/.npm-global/lib/node_modules/@chahuadev/framework/bin/Chahuadev-Framework.AppImage /tmp/ChahuadevFramework.AppImage> # (with sudo)> # cp /usr/lib/node_modules/@chahuadev/framework/bin/Chahuadev-Framework.AppImage /tmp/ChahuadevFramework.AppImage> chmod +x /tmp/ChahuadevFramework.AppImage> DISPLAY=:0 WAYLAND_DISPLAY=wayland-0 /tmp/ChahuadevFramework.AppImage \> --appimage-extract-and-run --no-sandbox --disable-gpu> ```---## Quick Start```bash# Install dependenciesnpm install# Start development servernpm start# Start with dev modenpm run dev# Generate buildsnpm run build # All platformsnpm run build-win # Windows onlynpm run build-msi # MSI installernpm run build-exe # Portable executablenpm run build-nsis # NSIS installer```---## Key Features**Offline Authentication** - No internet connection required**SVG Icon System** - 40+ SVG icons for UI/logging**Fort-Knox Security** - Anti-debugging, tamper detection, runtime integrity checks**Gateway Pattern** - Centralized command processing and validation**Multi-User Support** - Admin, Developer, User roles with permission levels**Plugin Management** - Load and execute NPM projects as plugins---## Project Structure```chahuadev-framework/├── docs/ # Documentation (moved here)│ ├── README.md│ ├── IMPLEMENTATION_COMPLETE.txt│ ├── OFFLINE_AUTH_GUIDE.md│ ├── AUTH_SECURITY_GUIDE.md│ └── ...├── src/├── backend/ # Backend utilities├── modules/ # Core modules│ ├── svg-icons.js # SVG icon system (40+ icons)│ ├── tamper-detector.js│ └── ...├── scripts/ # Build and utility scripts├── main.js # Electron main process├── preload.js # Preload script for IPC├── index.html # Main UI├── validation_gateway.js # Command gateway with auth└── package.json```---## Authentication System### Demo Users (Offline Mode)```Username: admin | Password: demo123 | Role: Administrator | Permissions: read, write, adminUsername: developer | Password: demo123 | Role: Developer | Permissions: read, writeUsername: user | Password: demo123 | Role: User | Permissions: read```### Token Storage- Location: `~/.chahuadev/auth.json`- Expiration: 24 hours### Permission Levels- `read` - View data, list plugins- `write` - Run commands, execute npm- `admin` - System configuration, auth checks---## Security Features### Fort-Knox Level Security- Anti-debugging protection- Tamper detection system- Runtime integrity checks- DevTools protection- Supply chain security verification### Authentication Security- Account lockout (5 attempts, 5-minute timeout)- Token expiration checking- Permission-based access control- Command-level authentication checks### Command Security- IPC command sanitization- Dangerous pattern detection- Whitelist-based execution- Plugin signature verification---## Logging System### Text-based Logging TagsInstead of emoji, the system now uses text-based tags:```[SUCCESS] - Operation successful[ERROR] - Error occurred[FAILED] - Operation failed[DENIED] - Access denied[LOCKED] - Account/resource locked[UNLOCKED] - Account/resource unlocked[EXPIRED] - Token expired[AUTH] - Authentication operation[PERMISSION] - Permission check[GATEWAY] - Gateway operation[ADMIN] - Administrator action[DEV] - Developer action[USER] - User action```---## SVG Icons System40+ SVG icons available in `modules/svg-icons.js`:### Security & Auth Icons- lock, unlock, shield, checkCircle, alertCircle, xCircle- userCheck, userX, user, users### System Icons- zap, settings, loader, refresh, eye, eyeOff- check, x, alertTriangle, info, bell, clock### Usage```javascriptconst SVGIcons = require('./modules/svg-icons.js');// Get SVG stringconst svg = SVGIcons.getSVG('lock', 'icon-small');// Create DOM elementconst elem = SVGIcons.createSVGElement('user', 'user-icon');```---## Development Commands```bash# Start developmentnpm start # Normal startnpm run dev # Development modenpm run dev-mode # Development mode with flags# Securitynpm run generate-checksums # Generate file checksumsnpm run security:check # Run security checksnpm run security:audit # Audit dependenciesnpm run security:report # Generate security report# Buildingnpm run build # Build all platformsnpm run build-win # Windows buildnpm run build-msi # MSI installernpm run build-exe # Portable executablenpm run build-nsis # NSIS installer# Testingnpm test # Run testsnpm run test:logo # Test logo system```---## For More Information- See **[docs/](docs/)** folder for detailed documentation- Check specific guides for authentication, security, and emoji removal- Review `AUTH_SECURITY_GUIDE.md` for authentication implementation details---## LicenseNon-Commercial & Acceptable Use — See [LICENSE.md](LICENSE.md)---## ContributingFor contributing guidelines, see the main documentation files in `docs/` folder---**Status**: Production Ready**Version**: 1.0.0**Last Updated**: February 17, 2026---*Chahuadev Framework - Making Project Management Simple & Secure*
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171/** * Auth Dialog System - ระบบกล่องแจ้งเตือนล็อกอิน * สำหรับแจ้งเตือนเมื่อผู้ใช้ยังไม่ได้ล็อกอิน */
class AuthDialog { constructor() { this.createStyles(); }
createStyles() { const styles = ` .auth-dialog-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.8); backdrop-filter: blur(5px); display: flex; align-items: center; justify-content: center; z-index: 15000; animation: auth-dialog-fade-in 0.3s ease-out; }
.auth-dialog-box { background: linear-gradient(135deg, #1a1a1a 0%, #0a0a0a 100%); border: 2px solid #333; border-radius: 12px; padding: 30px; max-width: 400px; width: 90%; box-shadow: 0 20px 40px rgba(0, 0, 0, 0.5), 0 0 0 1px rgba(255, 255, 255, 0.1), inset 0 1px 0 rgba(255, 255, 255, 0.1); animation: auth-dialog-slide-up 0.3s ease-out; text-align: center; }
.auth-dialog-header { color: #e0e0e0; font-size: 18px; font-weight: 600; margin-bottom: 8px; padding-bottom: 15px; border-bottom: 1px solid #333; }
.auth-dialog-message { color: #b0b0b0; font-size: 16px; line-height: 1.5; margin-bottom: 25px; margin-top: 15px; }
.auth-dialog-button { background: linear-gradient(135deg, #0ea5e9, #0284c7); border: none; color: white; padding: 12px 24px; border-radius: 8px; font-size: 14px; font-weight: 600; cursor: pointer; transition: all 0.3s ease; box-shadow: 0 4px 15px rgba(14, 165, 233, 0.3); min-width: 100px; }
.auth-dialog-button:hover { background: linear-gradient(135deg, #0284c7, #0369a1); transform: translateY(-2px); box-shadow: 0 6px 20px rgba(14, 165, 233, 0.4); }
.auth-dialog-button:active { transform: translateY(0); }
@keyframes auth-dialog-fade-in { from { opacity: 0; } to { opacity: 1; } }
@keyframes auth-dialog-slide-up { from { opacity: 0; transform: translateY(30px) scale(0.9); } to { opacity: 1; transform: translateY(0) scale(1); } } `;
// เพิ่ม CSS styles if (!document.getElementById('auth-dialog-styles')) { const styleElement = document.createElement('style'); styleElement.id = 'auth-dialog-styles'; styleElement.textContent = styles; document.head.appendChild(styleElement); } }
show(options = {}) { const { title = 'ข้อความจาก chahuadev.com', message = 'กรุณาล็อกอินก่อนใช้งาน', buttonText = 'ตกลง' } = options;
// ลบ dialog เก่าถ้ามี this.hide();
// สร้าง dialog overlay const overlay = document.createElement('div'); overlay.className = 'auth-dialog-overlay'; overlay.id = 'auth-dialog-overlay';
// สร้าง dialog box const dialog = document.createElement('div'); dialog.className = 'auth-dialog-box';
dialog.innerHTML = ` <div class="auth-dialog-header">${title}</div> <div class="auth-dialog-message">${message}</div> <button class="auth-dialog-button" onclick="authDialog.hide()">${buttonText}</button> `;
overlay.appendChild(dialog); document.body.appendChild(overlay);
// ปิด dialog เมื่อคลิกข้างนอก overlay.addEventListener('click', (e) => { if (e.target === overlay) { this.hide(); } });
// ปิด dialog ด้วย ESC key const escapeHandler = (e) => { if (e.key === 'Escape') { this.hide(); document.removeEventListener('keydown', escapeHandler); } }; document.addEventListener('keydown', escapeHandler); }
hide() { const overlay = document.getElementById('auth-dialog-overlay'); if (overlay) { overlay.style.animation = 'auth-dialog-fade-in 0.2s ease-out reverse'; setTimeout(() => { overlay.remove(); }, 200); } }}
// สร้าง instance ของ AuthDialogwindow.authDialog = new AuthDialog();123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169const { parentPort } = require('worker_threads');const path = require('path');
// ProjectInspector class will be imported in the message handler
/** * Inspector Worker - Project Analysis Worker Thread * * Worker Thread สำหรับการวิเคราะห์โปรเจกต์แบบไม่ blocking UI * ทำงานแยกต่างหากจาก Main Process เพื่อป้องกันการค้างของ UI * * การทำงาน: * 1. รับ path จาก Main Process ผ่าน message * 2. ใช้ ProjectInspector instance ที่ถูก export มา * 3. เริ่มการวิเคราะห์แบบ asynchronous * 4. ส่งผลลัพธ์กลับไปให้ Main Process * 5. จัดการ error ทุกกรณี */
console.log(' [Inspector Worker] Worker thread started');
// เมื่อได้รับคำสั่งจาก Main ProcessparentPort.on('message', async (data) => { const { projectPath, scanTarget = 'โปรเจกต์' } = data; try { console.log(` [Inspector Worker] Received job to analyze ${scanTarget}: ${projectPath}`); // ส่งสถานะเริ่มต้นกลับไป parentPort.postMessage({ type: 'progress', message: `เริ่มการวิเคราะห์ ${scanTarget}...`, progress: 0 }); // สร้าง ProjectInspector instance พร้อม status callback const statusUpdateCallback = (message) => { // ส่งสถานะอัปเดตไปยัง Main Process ทันที parentPort.postMessage({ type: 'status-update', data: message }); }; // --- เพิ่มการตรวจสอบ Error ตรงนี้ --- let ProjectInspector; try { // ลอง require ไฟล์ ProjectInspector ProjectInspector = require('./project-inspector'); } catch (e) { throw new Error(`Failed to require ProjectInspector: ${e.message}`); }
if (typeof ProjectInspector !== 'function') { throw new Error('ProjectInspector that was required is not a constructor. Check module.exports.'); }
// สร้าง ProjectInspector instance โดยส่ง callback เข้าไป const inspector = new ProjectInspector(statusUpdateCallback); console.log(` [Inspector Worker] Created ProjectInspector with status callback`); // ส่งสถานะการเตรียมตัว parentPort.postMessage({ type: 'progress', message: 'กำลังเตรียมเครื่องมือวิเคราะห์...', progress: 10 }); // เริ่มการวิเคราะห์ (ต่อไปนี้เป็นงานหนัก) const startTime = Date.now(); console.log(` [Inspector Worker] Starting intensive analysis of: ${projectPath}`); // ส่งสถานะเริ่มสแกน parentPort.postMessage({ type: 'progress', message: 'กำลังสแกนไฟล์ทั้งหมด...', progress: 25 }); // ทำการวิเคราะห์หลัก (จุดที่ใช้เวลานาน) const analysisResult = await inspector.analyzeProject(projectPath); const endTime = Date.now(); const duration = (endTime - startTime) / 1000; console.log(` [Inspector Worker] Analysis completed in ${duration}s`); console.log(` [Inspector Worker] Found ${analysisResult.totalFiles} files, ${analysisResult.totalIssues} issues`); // ส่งสถานะเสร็จสิ้น parentPort.postMessage({ type: 'progress', message: 'การวิเคราะห์เสร็จสมบูรณ์!', progress: 100 }); // ส่งผลลัพธ์สุดท้ายกลับไปให้ Main Process parentPort.postMessage({ type: 'analysis-result', success: true, analysis: analysisResult, scanTarget, duration, timestamp: new Date().toISOString() });
// Force cleanup and graceful exit after successful completion console.log(' [Inspector Worker] Results sent, scheduling graceful exit...'); setTimeout(() => { console.log(' [Inspector Worker] Analysis complete, terminating gracefully'); process.exit(0); }, 100);
} catch (error) { console.error(` [Inspector Worker] Analysis failed:`, error); // ส่ง Error ที่ชัดเจนกลับไป parentPort.postMessage({ type: 'analysis-result', success: false, error: { message: error.message, stack: error.stack, name: error.name, timestamp: new Date().toISOString() } });
// Force cleanup and exit after error setTimeout(() => { console.log(' [Inspector Worker] Error handled, terminating gracefully'); process.exit(0); }, 50); }});
// จัดการ error ที่ไม่คาดคิดprocess.on('unhandledRejection', (reason, promise) => { console.error(' [Inspector Worker] Unhandled Rejection at:', promise, 'reason:', reason); parentPort.postMessage({ type: 'error', error: { message: `Unhandled rejection: ${reason}`, stack: reason?.stack || 'No stack trace available', name: 'UnhandledRejection', timestamp: new Date().toISOString() } });});
process.on('uncaughtException', (error) => { console.error(' [Inspector Worker] Uncaught Exception:', error); parentPort.postMessage({ type: 'error', error: { message: error.message, stack: error.stack, name: error.name, timestamp: new Date().toISOString() } }); // Don't exit immediately to allow for graceful cleanup setTimeout(() => { console.log(' [Inspector Worker] Graceful shutdown after uncaught exception'); process.exit(0); }, 100);});
console.log(' [Inspector Worker] Listening for messages from Main Process...'); 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247const { ipcMain, app } = require('electron');const { Worker } = require('worker_threads');const path = require('path');const fs = require('fs');// Note: projectInspector is now handled by Worker Thread
// Track if handlers are already registeredlet handlersRegistered = false;
/** * IPC Handlers สำหรับ Project Inspector * @param {Object} logger - Logger object * @param {Object} debugManager - Debug manager instance * @param {Object} cmdLogger - CMD logger for real-time display */function setupProjectInspectorIPC(logger, debugManager, cmdLogger) { // ป้องกันการลงทะเบียนซ้ำ if (handlersRegistered) { console.log(' Project Inspector IPC handlers already registered, skipping...'); return; }
try { // Project Inspector IPC Handlers (ใช้ Worker Threads เพื่อป้องกัน UI ค้าง) ipcMain.handle('project:analyze', async (event, projectPath) => { return new Promise((resolve, reject) => { try { let pathToScan; let scanTarget; // ถ้าไม่ได้ระบุ path มา, ให้สแกนโฟลเดอร์ plugins เป็น default if (!projectPath) { console.log('No path provided, defaulting to plugins directory.'); scanTarget = 'ปลั๊กอินทั้งหมด'; // หา Path ของโฟลเดอร์ plugins ที่ถูกต้อง if (app.isPackaged) { pathToScan = path.join(path.dirname(app.getPath('exe')), 'plugins'); } else { pathToScan = path.join(app.getPath('userData'), 'plugins'); } } else { pathToScan = projectPath; scanTarget = 'โปรเจกต์เฉพาะ'; }
console.log(`[IPC] Starting project analysis for ${scanTarget}: ${pathToScan}`); // ตรวจสอบว่าโฟลเดอร์มีอยู่จริง if (!fs.existsSync(pathToScan)) { fs.mkdirSync(pathToScan, { recursive: true }); console.log(`Created missing directory: ${pathToScan}`); }
logger.info('Starting project analysis with Worker Thread', { pathToScan, scanTarget }); // ส่งข้อความเริ่มต้นไปยัง CMD if (cmdLogger) { cmdLogger.info(`[Inspector] Starting project analysis...`); cmdLogger.info(`[Inspector] Scan target: ${scanTarget}`); cmdLogger.info(`[Inspector] Path to scan: ${pathToScan}`); } // สร้าง Worker Thread สำหรับการวิเคราะห์ const worker = new Worker(path.join(__dirname, 'inspector-worker.js')); console.log(`[IPC] Created Worker Thread for analysis`); if (cmdLogger) { cmdLogger.debug(`[Inspector] Worker Thread created successfully`); }
// รอรับผลลัพธ์และสถานะจาก Worker worker.on('message', (result) => { if (result.type === 'progress') { // ส่ง progress update ไปให้ Frontend (ถ้าต้องการ) const progressMessage = `Progress: ${result.message} (${result.progress}%)`; console.log(`[IPC] ${progressMessage}`); // ส่ง progress ไปยัง CMD แบบ real-time if (cmdLogger) { cmdLogger.info(`[Inspector] ${progressMessage}`); } // event.sender.send('project:analysis-progress', result); } else if (result.type === 'status-update') { // ส่งสถานะ real-time ไปให้ UI และ CMD ทันที console.log(`[IPC] Status: ${result.data}`); // ส่งไปยัง CMD แบบ real-time if (cmdLogger) { cmdLogger.info(`[Inspector] ${result.data}`); } try { // ส่งสถานะไปยัง debug window หรือ main window event.sender.send('inspector:status-update', result.data); // ส่งสถานะไปยัง debug manager ถ้ามี (สำหรับ Real-time Terminal Display) if (debugManager) { // ตรวจสอบว่า debug window เปิดอยู่หรือไม่ if (debugManager.isDebugWindowOpen && debugManager.isDebugWindowOpen()) { // ส่งข้อความไปยัง terminal ใน debug window debugManager.sendTerminalMessage && debugManager.sendTerminalMessage(result.data, 'info'); console.log(`[IPC] Status sent to debug terminal: ${result.data}`); } else { console.log(`[IPC] Debug window is closed, skipping terminal message`); } } else { console.log(`[IPC] Debug manager not available`); } } catch (error) { console.warn('[IPC] Failed to send status update to renderer:', error.message); } } else if (result.type === 'analysis-result') { // จัดการผลลัพธ์สุดท้าย if (result.success) { logger.info('Project analysis completed successfully', { totalFiles: result.analysis.totalFiles, totalIssues: result.analysis.totalIssues, scanTarget: result.scanTarget, duration: result.duration }); const successMessage = `Worker completed successfully in ${result.duration}s - Files: ${result.analysis.totalFiles}, Issues: ${result.analysis.totalIssues}`; console.log(`[IPC] ${successMessage}`); // ส่งผลลัพธ์สุดท้ายไปยัง CMD if (cmdLogger) { cmdLogger.info(`[Inspector] ${successMessage}`); cmdLogger.info(`[Inspector] Analysis completed for: ${result.scanTarget}`); } resolve({ success: true, analysis: result.analysis, scanTarget: result.scanTarget, duration: result.duration }); // Let worker terminate gracefully on its own } else { // จัดการ error case logger.error('Project analysis failed in Worker', result.error); const errorMessage = `Worker failed: ${result.error.message || result.error}`; console.error(`[IPC] ${errorMessage}`); // ส่ง error ไปยัง CMD if (cmdLogger) { cmdLogger.error(`[Inspector] ${errorMessage}`); } resolve({ success: false, error: result.error.message }); // Let worker terminate gracefully on its own } } });
// รอรับ Error ที่ไม่คาดคิดจาก Worker worker.on('error', (err) => { logger.error('Worker encountered unrecoverable error', err); const errorMessage = `Worker unrecoverable error: ${err.message}`; console.error(`[IPC] ${errorMessage}`); // ส่ง error ไปยัง CMD if (cmdLogger) { cmdLogger.error(`[Inspector] ${errorMessage}`); } resolve({ success: false, error: err.message }); worker.terminate(); }); // ตรวจสอบการปิด Worker worker.on('exit', (code) => { if (code !== 0) { const exitMessage = `Worker stopped with exit code ${code}`; console.error(`[IPC] ${exitMessage}`); // ส่ง exit message ไปยัง CMD if (cmdLogger) { cmdLogger.warn(`[Inspector] ${exitMessage}`); } } });
// สั่งให้ Worker เริ่มทำงานโดยส่ง data เข้าไป worker.postMessage({ projectPath: pathToScan, scanTarget }); // ส่งข้อความที่เริ่มงานไปยัง CMD if (cmdLogger) { cmdLogger.info(`[Inspector] Sending analysis request to Worker Thread...`); } } catch (error) { logger.error('Failed to create Worker for project analysis', error); const errorMessage = `Failed to create Worker: ${error.message}`; // ส่ง error ไปยัง CMD if (cmdLogger) { cmdLogger.error(`[Inspector] ${errorMessage}`); } resolve({ success: false, error: error.message }); } }); });
ipcMain.handle('project:get-stats', async (event, analysis) => { try { // สำหรับ get-stats เราสามารถคำนวณใน Main Process ได้ เพราะไม่ใช่งานหนัก const ProjectInspector = require('./project-inspector'); const tempInspector = new ProjectInspector(); const stats = tempInspector.getAnalysisStats(analysis); return { success: true, stats }; } catch (error) { logger.error('Failed to get project stats', error); return { success: false, error: error.message }; } });
ipcMain.handle('project:set-rules', async (event, rules) => { try { // สำหรับ set-rules เราจัดเก็บใน memory หรือ file เพื่อให้ Worker ใช้ได้ // ตอนนี้จะ implement แบบง่ายๆ ก่อน console.log('[IPC] Analysis rules updated:', rules); // TODO: Implement rules storage for Worker Threads return { success: true, message: 'Rules will be applied to next analysis' }; } catch (error) { logger.error('Failed to set analysis rules', error); return { success: false, error: error.message }; } });
// ทำเครื่องหมายว่าลงทะเบียนแล้ว handlersRegistered = true; console.log(' Project Inspector IPC handlers registered'); } catch (error) { console.error(' Failed to register Project Inspector IPC handlers:', error); throw error; }}
module.exports = setupProjectInspectorIPC; 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813const fs = require('fs');const path = require('path');
// ตรวจสอบและใช้ Dependencies ที่จำเป็นสำหรับการวิเคราะห์ขั้นสูงlet acorn, cheerio;let dependencyWarning = null;try { acorn = require('acorn'); cheerio = require('cheerio'); console.log(' Advanced analysis packages loaded successfully');} catch (error) { console.warn(' Some analysis packages not found. Advanced checking will be disabled.'); dependencyWarning = 'Advanced analysis (HTML/JS/IPC) is disabled because required packages (acorn, cheerio) are missing.'; acorn = null; cheerio = null;}
/** * Project Inspector V.2 - Full-Stack Application Integrity Analysis System * * ระบบวิเคราะห์ความสมบูรณ์ของแอปพลิเคชันแบบ Full-Stack * ตรวจสอบ "ไวยากรณ์ของสถาปัตยกรรม" ตั้งแต่ Frontend ไปจนถึง Backend * * ความสามารถใหม่: * 1. HTML-JS Link Analysis - ตรวจสอบการเชื่อมต่อระหว่าง HTML กับ JavaScript * 2. IPC Communication Analysis - ตรวจสอบการสื่อสาร Renderer Main Process * 3. Visual Regression Detection - ตรวจสอบ Layout และ UI Integrity * 4. Architecture Grammar Validation - ตรวจสอบไวยากรณ์ของสถาปัตยกรรม * * พร้อมระบบคัดกรองไฟล์ของระบบแบบ Professional * * การปรับแต่งสำหรับการดีบัก: * - index.html ได้รับการปลดล็อกจาก exclusion rules เพื่อให้สามารถตรวจเจอปัญหาได้ * - ระบบจะสแกนและวิเคราะห์ index.html อย่างละเอียดเหมือนไฟล์อื่นๆ * * การปรับปรุงครั้งใหญ่: * - ปรับปรุงกฎการคัดกรองให้ฉลาดขึ้น (Smart Exclusion Rules) * - เพิ่มการรองรับไฟล์สมัยใหม่ (Modern File Extensions) * - ปรับปรุงการจัดการ Dependencies */class ProjectInspector { // แก้ไข constructor ให้รับ status callback constructor(statusUpdateCallback = () => {}) { this.statusUpdate = statusUpdateCallback; this.fileContentCache = new Map(); this.dependencyWarning = dependencyWarning; // เก็บ warning message // อัปเกรดกฎการวิเคราะห์ให้ครอบคลุม Full-Stack this.analysisRules = { // การวิเคราะห์พื้นฐาน checkSyntax: acorn !== null, checkMissingFiles: true, checkUnusedFiles: false, checkMissingDependencies: true, checkCircularDependencies: true, checkDuplicateExports: true, checkImportExportMismatch: acorn !== null, // การวิเคราะห์ขั้นสูง (ใหม่) checkHtmlJsLinks: cheerio !== null && acorn !== null, // วิเคราะห์ HTML-JS connections checkIpcIntegrity: acorn !== null, // วิเคราะห์ IPC communication checkVisualRegression: true, // เตรียมพร้อมสำหรับ Visual Testing checkArchitectureGrammar: true // วิเคราะห์ไวยากรณ์สถาปัตยกรรม };
// ข้อมูลสำหรับการวิเคราะห์ขั้นสูง this.htmlElements = new Map(); // เก็บ HTML elements และ IDs this.jsHandlers = new Map(); // เก็บ JavaScript event handlers this.ipcChannels = new Map(); // เก็บ IPC channels this.cssClasses = new Set(); // เก็บ CSS classes
// [ปรับปรุงครั้งใหญ่] กฎการคัดกรองที่ฉลาดขึ้น - แก้ปัญหาการสแกนไม่ครอบคลุม this.isExcluded = (filePath, projectRootPath) => { // กฎข้อที่ 0: เด็ดขาดที่สุด - ห้ามทุกอย่างที่อยู่ใน node_modules // กฎนี้จะทำงานก่อนเสมอและมีประสิทธิภาพสูงสุด if (filePath.includes(path.sep + 'node_modules' + path.sep)) { return true; }
const relativePath = path.relative(projectRootPath, filePath); const baseName = path.basename(filePath).toLowerCase();
// --- กฎข้อที่ 1: โฟลเดอร์ระดับรูทที่ต้องข้ามเสมอ (Root-level exclusions only) --- // ตรวจสอบกับ relativePath เพื่อให้แน่ใจว่าเป็นโฟลเดอร์ที่อยู่ระดับบนสุดจริงๆ const rootLevelExclusions = ['dist', 'build', '.git', 'test-results']; if (rootLevelExclusions.some(dir => relativePath.startsWith(dir + path.sep) || relativePath === dir)) { return true; }
// --- กฎข้อที่ 2: โฟลเดอร์ระบบ Chahuadev Framework (เฉพาะของ Framework เท่านั้น) --- const frameworkSystemDirs = new Set(['vendor', 'resources', 'bridge', 'logs', 'temp_extract']); const pathParts = relativePath.split(path.sep); if (pathParts.some(part => frameworkSystemDirs.has(part))) { return true; }
// --- กฎข้อที่ 3: ชื่อไฟล์ระบบที่ต้องข้ามเสมอ --- const definitiveFileExclusions = new Set([ 'splash.html', 'loading.html', 'debugger.html', 'main.js', 'preload.js', 'validation_gateway.js', 'debug-manager.js', 'project-inspector.js', 'project-inspector-ipc.js', 'generate-checksums.js', 'generate-keys.js', 'generate-manifests.js' ]); if (definitiveFileExclusions.has(baseName)) return true;
// --- กฎข้อที่ 4: รูปแบบชื่อไฟล์ที่ต้องข้าม --- if (baseName.endsWith('.min.js') || baseName.endsWith('.bundle.js')) { return true; }
// --- กฎข้อที่ 5: ไฟล์ประเภทที่ไม่ควรสแกน (Binary files) --- const binaryExtensions = ['.exe', '.dll', '.so', '.dylib', '.asar']; if (binaryExtensions.some(ext => baseName.endsWith(ext))) { return true; }
// ถ้าไม่เข้าเงื่อนไขใดๆ เลย แสดงว่าไฟล์นี้ควรถูกสแกน return false; }; // Multi-Language Project Type Detection Rules this.projectTypeRules = { 'node': { identifierFiles: ['package.json'], extensions: ['.js', '.mjs', '.ts', '.jsx', '.json'], checks: ['syntax', 'dependencies', 'imports'] }, 'python': { identifierFiles: ['requirements.txt', 'setup.py', 'pyproject.toml'], extensions: ['.py'], checks: ['syntax', 'imports'] }, 'php': { identifierFiles: ['composer.json', 'composer.lock'], extensions: ['.php'], checks: ['syntax', 'dependencies'] }, 'static_html': { identifierFiles: ['index.html', 'main.html'], extensions: ['.html', '.css', '.js', '.scss', '.less'], checks: ['links', 'assets'] } }; }
/** * ฟังก์ชัน detectProjectType ที่ใช้ isExcluded เป็นด่านแรก * @param {string} projectPath - เส้นทางของโปรเจกต์ * @returns {object} - { type: string, identifierFile: string | null } */ detectProjectType(projectPath) { console.log(` Detecting project type for: ${projectPath}`); // ตรวจสอบไฟล์ identifier สำหรับแต่ละประเภท for (const [type, rules] of Object.entries(this.projectTypeRules)) { for (const identifierFile of rules.identifierFiles) { const filePath = path.join(projectPath, identifierFile);
// ตรวจสอบก่อนว่าไฟล์ identifier ถูกสั่งให้ข้ามหรือไม่ if (this.isExcluded(filePath, projectPath)) { console.log(` Skipping ${identifierFile} for ${type} detection (excluded by system rules)`); continue; }
if (fs.existsSync(filePath)) { console.log(` Detected ${type} project (found ${identifierFile})`); return { type, identifierFile }; } } } // Fallback: ตรวจสอบจากนามสกุลไฟล์ที่มีอยู่ try { const files = fs.readdirSync(projectPath); // ตรวจหา .py files if (files.some(file => file.endsWith('.py'))) { console.log(' Detected python project (found .py files)'); return { type: 'python', identifierFile: null }; } // ตรวจหา .php files if (files.some(file => file.endsWith('.php'))) { console.log(' Detected php project (found .php files)'); return { type: 'php', identifierFile: null }; } // ตรวจหา HTML files (ต้องไม่ถูก exclude) const htmlFiles = files.filter(file => { const filePath = path.join(projectPath, file); return file.endsWith('.html') && !this.isExcluded(filePath, projectPath); }); if (htmlFiles.length > 0) { console.log(' Detected static_html project (found .html files)'); return { type: 'static_html', identifierFile: null }; } // ตรวจหา .js files (default Node.js) if (files.some(file => file.endsWith('.js'))) { console.log(' Detected node project (found .js files)'); return { type: 'node', identifierFile: null }; } } catch (error) { console.warn(` Error reading directory ${projectPath}:`, error.message); } console.log(' Unknown project type'); return { type: 'unknown', identifierFile: null }; }
/** * อ่านเนื้อหาไฟล์พร้อม Cache (สำหรับ Metadata Flag Detection) */ readFileContent(filePath) { if (this.fileContentCache.has(filePath)) { return this.fileContentCache.get(filePath); } const content = fs.readFileSync(filePath, 'utf-8'); this.fileContentCache.set(filePath, content); return content; }
/** * อัปเดตฟังก์ชัน walkDirectory ให้ส่งสถานะ Real-time */ walkDirectory(dir, projectPath, filelist = []) { if (!projectPath) projectPath = dir; // กำหนด root path ครั้งแรก
// ส่งสถานะว่ากำลังจะสแกนโฟลเดอร์นี้ this.statusUpdate(` Scanning directory: ${path.relative(projectPath, dir) || '.'}`);
try { const items = fs.readdirSync(dir, { withFileTypes: true });
for (const item of items) { const fullPath = path.join(dir, item.name);
// ตรวจสอบกับกฎคัดกรองก่อนทำอะไรทั้งสิ้น! if (this.isExcluded(fullPath, projectPath)) { // ส่งสถานะว่ากำลังข้ามไฟล์/โฟลเดอร์นี้ this.statusUpdate(` Skipping: ${item.name}`); continue; // ข้ามทันที - ไม่เข้าไปใน node_modules, .asar, หรือไฟล์ระบบ }
if (item.isDirectory()) { // ข้าม hidden folders เพิ่มเติม if (!item.name.startsWith('.')) { this.walkDirectory(fullPath, projectPath, filelist); } } else if (this.isPluginFile(item.name)) { // ส่งสถานะว่าพบไฟล์ที่จะนำไปวิเคราะห์ this.statusUpdate(` Found file: ${item.name}`); filelist.push(fullPath); } } } catch (error) { console.warn(`Cannot read directory ${dir}:`, error.message); } return filelist; }
/** * [ปรับปรุงครั้งใหญ่] ตรวจสอบไฟล์ปลั๊กอินด้วยการรองรับไฟล์สมัยใหม่ * เปลี่ยนจาก Whitelist เป็น Comprehensive Coverage */ isPluginFile(filename) { // รายการนามสกุลไฟล์ที่ครอบคลุมการพัฒนาสมัยใหม่ const pluginExtensions = [ // JavaScript & Frameworks '.js', '.mjs', '.ts', '.jsx', '.tsx', // Web Frontend '.html', '.htm', '.css', '.scss', '.sass', '.less', '.vue', // Backend Languages '.py', '.php', '.rb', '.go', '.rs', '.java', // Config & Data '.json', '.yaml', '.yml', '.xml', '.toml', '.ini', // Documentation & Text '.txt', '.md', '.markdown', '.rst', // Template Engines '.ejs', '.pug', '.handlebars', '.hbs', // Other useful formats '.sql', '.graphql', '.env' ]; const systemFiles = ['package.json', 'requirements.txt', 'composer.json', 'Cargo.toml', 'go.mod']; // อนุญาตไฟล์การกำหนดค่าที่สำคัญ if (systemFiles.includes(filename)) return true; // อนุญาตไฟล์ที่มีนามสกุลที่เกี่ยวข้องกับปลั๊กอิน return pluginExtensions.some(ext => filename.endsWith(ext)); }
/** * ฟังก์ชันหลักในการเริ่มวิเคราะห์โปรเจกต์ (เวอร์ชันปรับปรุงขั้นสุดท้าย) */ async analyzeProject(projectPath = process.cwd()) { const analysis = { timestamp: new Date().toISOString(), projectPath, totalFiles: 0, totalIssues: 0, issues: [], dependencies: new Map(), fileGraph: new Map(), unusedFiles: [], circularDeps: [], stats: { syntaxErrors: 0, missingFiles: 0, unusedFiles: 0, missingDependencies: 0, circularDependencies: 0, duplicateExports: 0, importExportMismatch: 0, typeSpecificIssues: 0 } };
try { console.log(' Starting Project Inspector analysis...'); // ส่งสถานะเริ่มต้นการวิเคราะห์ this.statusUpdate(' Starting Project Inspector analysis...'); // Multi-Language Project Type Detection this.statusUpdate(' Detecting project type...'); const detectionResult = this.detectProjectType(projectPath); const projectType = detectionResult.type; analysis.projectType = projectType; this.statusUpdate(` Project type detected: ${projectType}`);
// --- การตรวจสอบ System File Exclusion ที่เด็ดขาดขึ้น --- if (detectionResult.identifierFile) { const identifierFilePath = path.join(projectPath, detectionResult.identifierFile); if (this.isExcluded(identifierFilePath, projectPath)) { console.log(` Skipping type-specific analysis for '${projectType}' because its identifier file '${detectionResult.identifierFile}' is excluded by System File Exclusion rules.`); analysis.typeAnalysis = { projectType, typeSpecificIssues: [], recommendations: ['ข้ามการวิเคราะห์เฉพาะประเภทเพราะไฟล์หลักอยู่ใน System File Exclusion rules'] }; } else { // Type-specific Analysis (จะทำงานก็ต่อเมื่อไม่ถูกข้าม) const typeAnalysis = this.analyzeByProjectType(projectPath, projectType); analysis.typeAnalysis = typeAnalysis; // เพิ่ม type-specific issues เข้าไปใน main issues analysis.issues.push(...typeAnalysis.typeSpecificIssues); analysis.totalIssues += typeAnalysis.typeSpecificIssues.length; analysis.stats.typeSpecificIssues = typeAnalysis.typeSpecificIssues.length; console.log(` Project type detected: ${projectType}`); if (typeAnalysis.recommendations.length > 0) { console.log(` Recommendations: ${typeAnalysis.recommendations.length} items`); } } } else { // กรณีไม่มี identifierFile ให้ทำ type analysis ปกติ const typeAnalysis = this.analyzeByProjectType(projectPath, projectType); analysis.typeAnalysis = typeAnalysis; analysis.issues.push(...typeAnalysis.typeSpecificIssues); analysis.totalIssues += typeAnalysis.typeSpecificIssues.length; analysis.stats.typeSpecificIssues = typeAnalysis.typeSpecificIssues.length; console.log(` Project type detected: ${projectType}`); if (typeAnalysis.recommendations.length > 0) { console.log(` Recommendations: ${typeAnalysis.recommendations.length} items`); } } // 1. รวบรวมไฟล์ทั้งหมด (walkDirectory จะคัดกรองเบื้องต้นแล้ว) this.statusUpdate(' Collecting files to analyze...'); const filesToAnalyze = this.walkDirectory(projectPath, projectPath); const finalFileList = [];
// --- เพิ่มการคัดกรองชั้นที่สองโดยการอ่านเนื้อหาไฟล์ (Metadata Flag) --- this.statusUpdate(' Performing secondary file filtering...'); for (const filePath of filesToAnalyze) { try { const content = this.readFileContent(filePath); // ถ้าเจอ "ป้ายกำกับ" ของไฟล์ระบบ ให้ข้ามไป if (content.includes('CHAHUADEV_SYSTEM_FILE')) { console.log(` Skipping file with system flag: ${path.basename(filePath)}`); continue; } finalFileList.push(filePath); } catch (e) { // ถ้าอ่านไฟล์ไม่ได้ ก็ข้ามไป continue; } }
analysis.totalFiles = finalFileList.length; this.statusUpdate(` Found ${analysis.totalFiles} files to analyze`); // เพิ่มการแจ้งเตือนเกี่ยวกับ Dependencies ที่ขาดหายไป if (this.dependencyWarning) { analysis.issues.push({ type: 'ConfigurationWarning', severity: 'warning', file: 'Project Inspector', message: this.dependencyWarning, suggestion: 'Run "npm install acorn cheerio" in your project directory to enable advanced analysis features.', line: 1, column: 1 }); analysis.totalIssues += 1; console.log(` ${this.dependencyWarning}`); } if (analysis.totalFiles === 0) { console.log(' No plugin files found in project'); // สำหรับโปรเจกต์ที่ไม่ใช่ Node.js/JavaScript ให้ส่งผล type analysis กลับ if (projectType !== 'node' && projectType !== 'unknown') { console.log(` Analysis completed for ${projectType} project (no plugin files needed)`); return analysis; } return analysis; } const allProjectFiles = new Set(); finalFileList.forEach(file => { const relativePath = path.relative(projectPath, file); allProjectFiles.add(relativePath); });
// 2. วิเคราะห์แต่ละไฟล์ this.statusUpdate(' Starting file analysis...'); for (const filePath of finalFileList) { try { const code = fs.readFileSync(filePath, 'utf-8'); const relativePath = path.relative(projectPath, filePath); // ส่งสถานะว่ากำลังวิเคราะห์ไฟล์นี้ this.statusUpdate(` Analyzing: ${relativePath}`); // 2.1 ตรวจสอบ Syntax if (this.analysisRules.checkSyntax && acorn) { const syntaxIssues = this.checkSyntax(code, relativePath, projectPath); analysis.issues.push(...syntaxIssues); analysis.stats.syntaxErrors += syntaxIssues.length; }
// 2.2 วิเคราะห์ Dependencies if (this.analysisRules.checkMissingFiles) { const depIssues = this.analyzeDependencies(code, filePath, projectPath, analysis); analysis.issues.push(...depIssues); analysis.stats.missingFiles += depIssues.length; }
// 2.3 ตรวจสอบ Duplicate Exports if (this.analysisRules.checkDuplicateExports && acorn) { const exportIssues = this.checkDuplicateExports(code, relativePath, projectPath); analysis.issues.push(...exportIssues); analysis.stats.duplicateExports += exportIssues.length; }
// 2.4 ตรวจสอบ Import/Export Mismatch if (this.analysisRules.checkImportExportMismatch && acorn) { const mismatchIssues = this.checkImportExportMismatch(code, filePath, projectPath); analysis.issues.push(...mismatchIssues); analysis.stats.importExportMismatch += mismatchIssues.length; }
} catch (error) { // ไม่สามารถวิเคราะห์ไฟล์นี้ได้ analysis.issues.push({ type: 'AnalysisError', severity: 'warning', file: path.relative(projectPath, filePath), message: `ไม่สามารถวิเคราะห์ไฟล์ได้: ${error.message}`, line: 1, column: 1 }); } }
// 3. หาไฟล์ที่ไม่ได้ใช้งาน if (this.analysisRules.checkUnusedFiles) { const unusedIssues = this.findUnusedFiles(analysis.dependencies, allProjectFiles, projectPath); analysis.issues.push(...unusedIssues); analysis.stats.unusedFiles += unusedIssues.length; }
// 4. ตรวจสอบ Circular Dependencies if (this.analysisRules.checkCircularDependencies) { const circularIssues = this.findCircularDependencies(analysis.fileGraph, projectPath); analysis.issues.push(...circularIssues); analysis.stats.circularDependencies += circularIssues.length; }
// 5. ตรวจสอบ Missing Dependencies ใน package.json if (this.analysisRules.checkMissingDependencies) { const missingDepIssues = this.checkMissingDependencies(analysis.dependencies, projectPath); analysis.issues.push(...missingDepIssues); analysis.stats.missingDependencies += missingDepIssues.length; }
// ========== ADVANCED ANALYSIS (NEW) ==========
// 6. วิเคราะห์การเชื่อมต่อ HTML-JavaScript if (this.analysisRules.checkHtmlJsLinks) { const htmlFiles = finalFileList.filter(f => f.endsWith('.html')); const jsFiles = finalFileList.filter(f => f.endsWith('.js') && !f.includes('.min.js')); if (htmlFiles.length > 0 && jsFiles.length > 0) { this.statusUpdate(' [Advanced] Running HTML-JavaScript link analysis...'); console.log(' [Advanced] Running HTML-JavaScript link analysis...'); const htmlJsIssues = this.analyzeHtmlJsLinks(htmlFiles, jsFiles, projectPath); analysis.issues.push(...htmlJsIssues); analysis.stats.htmlJsLinkIssues = htmlJsIssues.length; } }
// 7. วิเคราะห์การสื่อสาร IPC if (this.analysisRules.checkIpcIntegrity) { const rendererFiles = finalFileList.filter(f => (f.endsWith('.js') && !f.includes('main.js')) || f.includes('preload.js') || f.includes('renderer') ); const mainFiles = finalFileList.filter(f => f.includes('main.js') || f.includes('debug-manager.js') ); this.statusUpdate(' [Advanced] Running IPC communication analysis...'); if (rendererFiles.length > 0 && mainFiles.length > 0) { console.log(' [Advanced] Running IPC communication analysis...'); const ipcIssues = this.analyzeIpcIntegrity(rendererFiles, mainFiles, projectPath); analysis.issues.push(...ipcIssues); analysis.stats.ipcIntegrityIssues = ipcIssues.length; } }
// 8. ตรวจสอบไวยากรณ์ของสถาปัตยกรรม if (this.analysisRules.checkArchitectureGrammar) { this.statusUpdate(' [Advanced] Running architecture grammar validation...'); console.log(' [Advanced] Running architecture grammar validation...'); const architectureIssues = this.validateArchitectureGrammar(projectPath, finalFileList); analysis.issues.push(...architectureIssues); analysis.stats.architectureGrammarIssues = architectureIssues.length; }
analysis.totalIssues = analysis.issues.length; // ล้าง cache หลังจากวิเคราะห์เสร็จ this.fileContentCache.clear(); this.statusUpdate(` Analysis completed: ${analysis.totalIssues} issues found in ${analysis.totalFiles} files`); console.log(` Project Inspector completed: ${analysis.totalIssues} issues found in ${analysis.totalFiles} files`); return analysis;
} catch (error) { console.error(' Project Inspector failed:', error); throw error; } }
/** * วิเคราะห์ปลั๊กอินตามประเภท * @param {string} projectPath - เส้นทางของโปรเจกต์ * @param {string} projectType - ประเภทของโปรเจกต์ * @returns {Object} - ผลการวิเคราะห์เฉพาะประเภท */ analyzeByProjectType(projectPath, projectType) { const typeAnalysis = { projectType, typeSpecificIssues: [], recommendations: [] };
try { switch (projectType) { case 'node': return this.analyzeNodeProject(projectPath, typeAnalysis); case 'python': return this.analyzePythonProject(projectPath, typeAnalysis); case 'php': return this.analyzePhpProject(projectPath, typeAnalysis); case 'static_html': return this.analyzeHtmlProject(projectPath, typeAnalysis); default: typeAnalysis.recommendations.push('ไม่สามารถระบุประเภทโปรเจกต์ได้ - แนะนำให้เพิ่มไฟล์ manifest'); return typeAnalysis; } } catch (error) { console.error(` Error analyzing ${projectType} project:`, error); typeAnalysis.typeSpecificIssues.push({ type: 'analysis_error', severity: 'high', message: `ไม่สามารถวิเคราะห์โปรเจกต์ประเภท ${projectType} ได้: ${error.message}` }); return typeAnalysis; } }
/** * วิเคราะห์โปรเจกต์ Node.js */ analyzeNodeProject(projectPath, typeAnalysis) { const packageJsonPath = path.join(projectPath, 'package.json'); if (fs.existsSync(packageJsonPath)) { try { const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')); // ตรวจสอบ main entry point if (!packageJson.main && !packageJson.scripts?.start) { typeAnalysis.typeSpecificIssues.push({ type: 'missing_entry_point', severity: 'medium', message: 'ไม่พบ main entry point หรือ start script ใน package.json' }); typeAnalysis.recommendations.push('เพิ่ม "main": "index.js" หรือ "scripts": {"start": "node index.js"} ใน package.json'); } // ตรวจสอบ dependencies if (!packageJson.dependencies && !packageJson.devDependencies) { typeAnalysis.recommendations.push('โปรเจกต์ไม่มี dependencies - ตรวจสอบว่าต้องการ package เพิ่มเติมหรือไม่'); } } catch (error) { typeAnalysis.typeSpecificIssues.push({ type: 'invalid_package_json', severity: 'high', message: 'ไฟล์ package.json ไม่ถูกต้อง: ' + error.message }); } } return typeAnalysis; }
/** * วิเคราะห์โปรเจกต์ Python */ analyzePythonProject(projectPath, typeAnalysis) { const requirementsPath = path.join(projectPath, 'requirements.txt'); // ตรวจสอบ requirements.txt if (fs.existsSync(requirementsPath)) { try { const requirements = fs.readFileSync(requirementsPath, 'utf8'); if (requirements.trim().length === 0) { typeAnalysis.recommendations.push('ไฟล์ requirements.txt ว่างเปล่า - พิจารณาเพิ่ม dependencies ที่จำเป็น'); } } catch (error) { typeAnalysis.typeSpecificIssues.push({ type: 'invalid_requirements', severity: 'medium', message: 'ไม่สามารถอ่านไฟล์ requirements.txt ได้: ' + error.message }); } } else { typeAnalysis.recommendations.push('แนะนำให้สร้างไฟล์ requirements.txt สำหรับจัดการ Python dependencies'); } // ตรวจหาไฟล์ main const mainFiles = ['main.py', 'app.py', '__main__.py']; const hasMainFile = mainFiles.some(file => fs.existsSync(path.join(projectPath, file))); if (!hasMainFile) { typeAnalysis.recommendations.push('แนะนำให้มีไฟล์ main entry point เช่น main.py หรือ app.py'); } return typeAnalysis; }
/** * วิเคราะห์โปรเจกต์ PHP */ analyzePhpProject(projectPath, typeAnalysis) { const composerJsonPath = path.join(projectPath, 'composer.json'); if (fs.existsSync(composerJsonPath)) { try { const composerJson = JSON.parse(fs.readFileSync(composerJsonPath, 'utf8')); // ตรวจสอบ autoload if (!composerJson.autoload) { typeAnalysis.recommendations.push('แนะนำให้เพิ่ม autoload configuration ใน composer.json'); } } catch (error) { typeAnalysis.typeSpecificIssues.push({ type: 'invalid_composer_json', severity: 'high', message: 'ไฟล์ composer.json ไม่ถูกต้อง: ' + error.message }); } } else { typeAnalysis.recommendations.push('แนะนำให้สร้างไฟล์ composer.json สำหรับจัดการ PHP dependencies'); } // ตรวจหาไฟล์ main const mainFiles = ['index.php', 'main.php', 'app.php']; const hasMainFile = mainFiles.some(file => fs.existsSync(path.join(projectPath, file))); if (!hasMainFile) { typeAnalysis.recommendations.push('แนะนำให้มีไฟล์ entry point เช่น index.php'); } return typeAnalysis; }
/** * วิเคราะห์โปรเจกต์ HTML */ analyzeHtmlProject(projectPath, typeAnalysis) { const indexHtmlPath = path.join(projectPath, 'index.html'); if (fs.existsSync(indexHtmlPath)) { try { const htmlContent = fs.readFileSync(indexHtmlPath, 'utf8'); // ตรวจสอบ external resources const cssLinks = (htmlContent.match(/<link[^>]*\.css/g) || []).length; const jsScripts = (htmlContent.match(/<script[^>]*\.js/g) || []).length; if (cssLinks === 0) { typeAnalysis.recommendations.push('ไม่พบไฟล์ CSS - พิจารณาเพิ่ม styling'); } if (jsScripts === 0) { typeAnalysis.recommendations.push('ไม่พบไฟล์ JavaScript - ตรวจสอบว่าเป็น static site หรือต้องการ interactivity'); } // ตรวจสอบโครงสร้าง HTML พื้นฐาน if (!htmlContent.includes('<title>')) { typeAnalysis.typeSpecificIssues.push({ type: 'missing_title', severity: 'low', message: 'ไม่พบ <title> tag ใน HTML' }); } } catch (error) { typeAnalysis.typeSpecificIssues.push({ type: 'invalid_html', severity: 'medium', message: 'ไม่สามารถอ่านไฟล์ index.html ได้: ' + error.message }); } } else { typeAnalysis.typeSpecificIssues.push({ type: 'missing_index_html', severity: 'high', message: 'ไม่พบไฟล์ index.html' }); } return typeAnalysis; }
/** * ดึง code snippet รอบๆ บรรทัดที่มีปัญหา */ extractCodeSnippet(filePath, problemLine, contextLines = 2) { try { // ตรวจสอบ cache ก่อน let content; if (this.fileContentCache.has(filePath)) { content = this.fileContentCache.get(filePath); } else { content = fs.readFileSync(filePath, 'utf8'); this.fileContentCache.set(filePath, content); }
const lines = content.split('\n'); const startLine = Math.max(0, problemLine - contextLines - 1); const endLine = Math.min(lines.length, problemLine + contextLines); const snippetLines = []; for (let i = startLine; i < endLine; i++) { const lineNumber = i + 1; const isErrorLine = lineNumber === problemLine; const prefix = isErrorLine ? '>' : ' '; const lineNumStr = lineNumber.toString().padStart(3, ' '); snippetLines.push(`${prefix} ${lineNumStr} | ${lines[i] || ''}`); } return { snippet: snippetLines.join('\n'), problemLine: lines[problemLine - 1] || '', totalLines: lines.length }; } catch (error) { return { snippet: 'ไม่สามารถอ่านไฟล์ได้', problemLine: '', totalLines: 0 }; } }
/** * สร้าง issue object พร้อม code snippet */ createIssue(type, severity, filePath, line, column, message, suggestion, projectPath) { const relativePath = typeof filePath === 'string' && path.isAbsolute(filePath) ? path.relative(projectPath || process.cwd(), filePath) : filePath; const absolutePath = path.isAbsolute(filePath) ? filePath : path.resolve(projectPath || process.cwd(), filePath); const codeInfo = this.extractCodeSnippet(absolutePath, line); return { type, severity, file: relativePath, line, column, message, suggestion, codeSnippet: codeInfo.snippet, problemLine: codeInfo.problemLine, totalLines: codeInfo.totalLines }; }
/** * อัปเดต checkSyntax ให้ตรวจเฉพาะไฟล์ JS ที่ไม่ถูกบีบอัด (Professional Version) */ checkSyntax(code, relativePath, projectPath) { // ทำงานเฉพาะกับไฟล์ .js และ .mjs เท่านั้น if (!relativePath.endsWith('.js') && !relativePath.endsWith('.mjs')) { return []; }
// ข้ามไฟล์ที่ถูกบีบอัดหรือ minified (เพราะมักจะให้ผลลวง) const filename = path.basename(relativePath).toLowerCase(); if (filename.includes('.min.') || filename.includes('.bundle.') || filename.includes('.compiled.')) { return []; }
const issues = []; // ถ้าไม่มี acorn ให้ return array ว่าง if (!acorn) { return issues; } try { acorn.parse(code, { sourceType: 'module', locations: true, ecmaVersion: 'latest', allowReturnOutsideFunction: true }); } catch (error) { if (error instanceof SyntaxError) { const issue = this.createIssue( 'SyntaxError', 'error', relativePath, error.loc ? error.loc.line : 1, error.loc ? error.loc.column : 1, `ไวยากรณ์ผิดพลาด: ${error.message}`, this.getSyntaxErrorSuggestion(error.message), projectPath ); issues.push(issue); } } return issues; }
/** * วิเคราะห์ Dependencies ของไฟล์ */ analyzeDependencies(code, currentFilePath, projectPath, analysis) { const issues = []; try { const ast = acorn.parse(code, { sourceType: 'module', locations: true, ecmaVersion: 'latest', allowReturnOutsideFunction: true });
const relativePath = path.relative(projectPath, currentFilePath); analysis.fileGraph.set(relativePath, []);
this.walkAST(ast, (node) => { let depPath = null; let line = 1; let column = 1;
// Import statements if (node.type === 'ImportDeclaration' && node.source) { depPath = node.source.value; line = node.source.loc.start.line; column = node.source.loc.start.column; } // Require calls else if (node.type === 'CallExpression' && node.callee.name === 'require' && node.arguments.length > 0 && node.arguments[0].type === 'Literal') { depPath = node.arguments[0].value; line = node.arguments[0].loc.start.line; column = node.arguments[0].loc.start.column; }
if (depPath && typeof depPath === 'string') { // เก็บ dependency ไว้ใน graph analysis.fileGraph.get(relativePath).push(depPath); // ตรวจสอบเฉพาะ relative imports if (depPath.startsWith('./') || depPath.startsWith('../')) { const absoluteDepPath = path.resolve(path.dirname(currentFilePath), depPath); const relativeDepPath = path.relative(projectPath, absoluteDepPath); analysis.dependencies.set(relativeDepPath, true); analysis.dependencies.set(relativeDepPath + '.js', true);
// ตรวจสอบว่าไฟล์มีอยู่จริงหรือไม่ if (!fs.existsSync(absoluteDepPath) && !fs.existsSync(absoluteDepPath + '.js')) { const issue = this.createIssue( 'MissingFile', 'error', currentFilePath, line, column, `ไม่พบไฟล์ที่ต้องการ: '${depPath}'`, this.getMissingFileSuggestion(depPath, currentFilePath), projectPath ); issues.push(issue); } } // ตรวจสอบ npm packages else if (!depPath.startsWith('/') && !depPath.includes('node_modules')) { analysis.dependencies.set(depPath, true); } } });
} catch (error) { // ไม่สามารถ parse ได้ แสดงว่ามี syntax error อยู่แล้ว } return issues; }
/** * ตรวจสอบ Duplicate Exports */ checkDuplicateExports(code, relativePath, projectPath) { const issues = []; const exports = new Map(); try { const ast = acorn.parse(code, { sourceType: 'module', locations: true, ecmaVersion: 'latest', allowReturnOutsideFunction: true });
this.walkAST(ast, (node) => { if (node.type === 'ExportNamedDeclaration' && node.declaration) { const exportName = node.declaration.id ? node.declaration.id.name : 'anonymous'; if (exports.has(exportName)) { const issue = this.createIssue( 'DuplicateExport', 'error', relativePath, node.loc.start.line, node.loc.start.column, `Export ซ้ำ: '${exportName}' ถูก export แล้วที่บรรทัด ${exports.get(exportName)}`, `ลบ export ที่ซ้ำหรือเปลี่ยนชื่อ export`, projectPath ); issues.push(issue); } else { exports.set(exportName, node.loc.start.line); } } });
} catch (error) { // ไม่สามารถ parse ได้ } return issues; }
/** * ตรวจสอบ Import/Export Mismatch * หาเจอ Runtime Error ที่เกิดจากการ import สิ่งที่ไม่ได้ export จากไฟล์ปลายทาง */ checkImportExportMismatch(code, currentFilePath, projectPath) { const issues = []; try { const ast = acorn.parse(code, { sourceType: 'module', locations: true, ecmaVersion: 'latest', allowReturnOutsideFunction: true });
// เก็บรายการ imports ที่ต้องตรวจสอบ const importsToCheck = [];
this.walkAST(ast, (node) => { // ตรวจสอบ Named Imports เช่น import { NodePalette } from './node-palette.js' if (node.type === 'ImportDeclaration' && node.source) { const modulePath = node.source.value; // เช็คเฉพาะ relative imports if (modulePath.startsWith('./') || modulePath.startsWith('../')) { const importedNames = []; // รวบรวมชื่อที่ import เข้ามา if (node.specifiers) { node.specifiers.forEach(spec => { if (spec.type === 'ImportSpecifier') { // Named import: import { NodePalette } importedNames.push({ name: spec.imported.name, localName: spec.local.name, line: spec.loc.start.line, column: spec.loc.start.column }); } else if (spec.type === 'ImportDefaultSpecifier') { // Default import: import NodePalette importedNames.push({ name: 'default', localName: spec.local.name, line: spec.loc.start.line, column: spec.loc.start.column }); } }); }
if (importedNames.length > 0) { importsToCheck.push({ modulePath, importedNames, line: node.loc.start.line, column: node.loc.start.column }); } } } });
// ตรวจสอบแต่ละ import for (const importData of importsToCheck) { const absoluteModulePath = path.resolve(path.dirname(currentFilePath), importData.modulePath); const modulePathWithJs = absoluteModulePath.endsWith('.js') ? absoluteModulePath : absoluteModulePath + '.js'; // ตรวจสอบว่าไฟล์มีอยู่จริง let targetFilePath = null; if (fs.existsSync(absoluteModulePath)) { targetFilePath = absoluteModulePath; } else if (fs.existsSync(modulePathWithJs)) { targetFilePath = modulePathWithJs; }
if (targetFilePath) { // อ่านไฟล์ปลายทางและหา exports try { let targetCode; if (this.fileContentCache.has(targetFilePath)) { targetCode = this.fileContentCache.get(targetFilePath); } else { targetCode = fs.readFileSync(targetFilePath, 'utf8'); this.fileContentCache.set(targetFilePath, targetCode); }
const availableExports = this.extractExportsFromCode(targetCode); // ตรวจสอบแต่ละ imported name for (const imported of importData.importedNames) { if (!availableExports.has(imported.name)) { const issue = this.createIssue( 'MissingExport', 'error', currentFilePath, importData.line, importData.column, `ไฟล์ '${importData.modulePath}' ไม่ได้ export '${imported.name}' ออกมา`, `ตรวจสอบการ export ในไฟล์ ${importData.modulePath} หรือเปลี่ยนชื่อที่ import ให้ถูกต้อง`, projectPath ); issues.push(issue); } } } catch (error) { // ไม่สามารถอ่านไฟล์ปลายทางได้ } } }
} catch (error) { // ไม่สามารถ parse ได้ } return issues; }
/** * สกัด exports ทั้งหมดจากโค้ด */ extractExportsFromCode(code) { const exports = new Set(); try { const ast = acorn.parse(code, { sourceType: 'module', locations: true, ecmaVersion: 'latest', allowReturnOutsideFunction: true });
this.walkAST(ast, (node) => { // Export declarations if (node.type === 'ExportNamedDeclaration') { if (node.declaration) { // export function name() {} หรือ export class Name {} if (node.declaration.id) { exports.add(node.declaration.id.name); } // export const a = 1, b = 2; else if (node.declaration.declarations) { node.declaration.declarations.forEach(decl => { if (decl.id && decl.id.name) { exports.add(decl.id.name); } }); } } // export { a, b }; else if (node.specifiers) { node.specifiers.forEach(spec => { if (spec.exported) { exports.add(spec.exported.name); } }); } } // Default exports else if (node.type === 'ExportDefaultDeclaration') { exports.add('default'); } // module.exports pattern (CommonJS) else if (node.type === 'AssignmentExpression' && node.left.type === 'MemberExpression' && node.left.object.name === 'module' && node.left.property.name === 'exports') { exports.add('default'); } });
} catch (error) { // ไม่สามารถ parse ได้ } return exports; }
/** * หาไฟล์ที่ไม่ได้ใช้งาน */ findUnusedFiles(dependencies, allProjectFiles, projectPath) { const issues = []; const usedFiles = new Set(); // เก็บรายชื่อไฟล์ที่ถูกใช้งาน dependencies.forEach((_, depPath) => { usedFiles.add(depPath); });
// หาไฟล์ที่ไม่ได้ใช้งาน allProjectFiles.forEach(file => { if (!usedFiles.has(file) && !file.includes('main.js') && !file.includes('index.js') && !file.includes('preload.js')) { const issue = this.createIssue( 'UnusedFile', 'warning', file, 1, 1, 'ไฟล์นี้ไม่ได้ถูกใช้งานโดยไฟล์อื่นๆ', 'ลบไฟล์ที่ไม่ได้ใช้งาน หรือเพิ่ม import ในไฟล์อื่น', projectPath ); issues.push(issue); } }); return issues; }
/** * หา Circular Dependencies */ findCircularDependencies(fileGraph, projectPath) { const issues = []; const visited = new Set(); const recursionStack = new Set(); const dfs = (file, path = []) => { if (recursionStack.has(file)) { const cycle = [...path, file]; const cycleStart = cycle.indexOf(file); const circularPath = cycle.slice(cycleStart); const issue = this.createIssue( 'CircularDependency', 'warning', file, 1, 1, `พบการอ้างอิงแบบวงกลม: ${circularPath.join(' -> ')}`, 'ปรับโครงสร้างไฟล์เพื่อหลีกเลี่ยง circular dependency', projectPath ); issues.push(issue); return; } if (visited.has(file)) return; visited.add(file); recursionStack.add(file); const dependencies = fileGraph.get(file) || []; for (const dep of dependencies) { if (dep.startsWith('./') || dep.startsWith('../')) { dfs(dep, [...path, file]); } } recursionStack.delete(file); }; for (const file of fileGraph.keys()) { if (!visited.has(file)) { dfs(file); } } return issues; }
/** * ตรวจสอบ Missing Dependencies ใน package.json */ checkMissingDependencies(dependencies, projectPath) { // สร้าง Set ของโมดูลพื้นฐานของ Node.js const nodeBuiltins = new Set([ 'fs', 'path', 'os', 'crypto', 'events', 'child_process', 'util', 'stream', 'https', 'http', 'url', 'querystring', 'zlib', 'worker_threads', 'cluster', 'net', 'tls', 'dns', 'dgram', 'readline', 'repl', 'vm', 'module', 'assert', 'buffer', 'console', 'process', 'timers', 'string_decoder', 'punycode' ]);
const issues = []; try { const packageJsonPath = path.join(projectPath, 'package.json'); if (!fs.existsSync(packageJsonPath)) { return issues; } const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8')); const installedDeps = new Set([ ...Object.keys(packageJson.dependencies || {}), ...Object.keys(packageJson.devDependencies || {}) ]); dependencies.forEach((_, depPath) => { // ตรวจสอบเงื่อนไขใหม่ที่ฉลาดขึ้น if (!depPath.startsWith('./') && !depPath.startsWith('../') && !path.isAbsolute(depPath) && // ไม่ใช่ path เต็ม !nodeBuiltins.has(depPath) && // ไม่ใช่โมดูลของ Node.js !depPath.includes('.js') && !installedDeps.has(depPath)) { issues.push({ type: 'MissingDependency', severity: 'error', file: 'package.json', line: 1, column: 1, message: `ไม่พบ dependency '${depPath}' ใน package.json`, suggestion: `รัน: npm install ${depPath}` }); } }); } catch (error) { // ไม่สามารถอ่าน package.json ได้ } return issues; }
/** * เดินทาง AST */ walkAST(node, callback) { if (!node || typeof node !== 'object') return; callback(node); for (const key in node) { if (node.hasOwnProperty(key)) { const child = node[key]; if (Array.isArray(child)) { child.forEach(item => this.walkAST(item, callback)); } else if (child && typeof child === 'object') { this.walkAST(child, callback); } } } }
/** * แนะนำแก้ไข Syntax Error */ getSyntaxErrorSuggestion(errorMessage) { if (errorMessage.includes('Unexpected token')) { return 'ตรวจสอบเครื่องหมายวรรคตอน เช่น { } ( ) [ ] หรือ ;'; } if (errorMessage.includes('Unexpected string')) { return 'ตรวจสอบ quote marks (" หรือ \') ให้ถูกต้อง'; } if (errorMessage.includes('Unexpected identifier')) { return 'ตรวจสอบชื่อตัวแปรหรือฟังก์ชัน'; } return 'ตรวจสอบไวยากรณ์ JavaScript'; }
/** * แนะนำแก้ไข Missing File */ getMissingFileSuggestion(depPath, currentFilePath) { const dir = path.dirname(currentFilePath); const suggestedPath = path.resolve(dir, depPath); return `ตรวจสอบว่าไฟล์อยู่ที่ ${suggestedPath} หรือปรับ path ให้ถูกต้อง`; }
/** * ตั้งค่ากฎการวิเคราะห์ */ setAnalysisRules(rules) { this.analysisRules = { ...this.analysisRules, ...rules }; }
/** * ได้รับสถิติการวิเคราะห์ */ getAnalysisStats(analysis) { return { totalFiles: analysis.totalFiles, totalIssues: analysis.totalIssues, severityBreakdown: { error: analysis.issues.filter(i => i.severity === 'error').length, warning: analysis.issues.filter(i => i.severity === 'warning').length, info: analysis.issues.filter(i => i.severity === 'info').length }, typeBreakdown: analysis.stats }; }
// ========== ADVANCED ANALYSIS METHODS (NEW) ==========
/** * HTML-JS Link Analyzer - วิเคราะห์การเชื่อมต่อระหว่าง HTML กับ JavaScript * ตรวจสอบ getElementById, onclick handlers, และ DOM element integrity */ analyzeHtmlJsLinks(htmlFiles, jsFiles, projectPath) { if (!cheerio || !acorn) { console.warn(' HTML-JS analysis requires cheerio and acorn packages'); return []; }
const issues = []; console.log(' [HTML-JS] Starting HTML-JavaScript link analysis...');
// Step 1: Parse HTML files to extract IDs and onclick handlers const htmlData = this.parseHtmlFiles(htmlFiles, projectPath); // Step 2: Parse JS files to extract getElementById calls and function declarations const jsData = this.parseJsFiles(jsFiles, projectPath);
// Step 3: Cross-reference and find mismatches // Check for missing element IDs jsData.getElementByIdCalls.forEach(call => { if (!htmlData.elementIds.has(call.id)) { issues.push(this.createIssue( 'MissingElementID', 'error', call.file, call.line, call.column, `getElementById('${call.id}') เรียกใช้ ID ที่ไม่มีอยู่ใน HTML`, `เพิ่ม element ที่มี id="${call.id}" ใน HTML หรือตรวจสอบ ID ให้ถูกต้อง`, projectPath )); } });
// Check for missing onclick handlers htmlData.onclickHandlers.forEach(handler => { if (!jsData.functionDeclarations.has(handler.functionName)) { issues.push(this.createIssue( 'MissingFunctionHandler', 'error', handler.file, handler.line, 1, `onclick="${handler.functionName}()" เรียกใช้ฟังก์ชันที่ไม่มีอยู่`, `สร้างฟังก์ชัน ${handler.functionName}() ใน JavaScript หรือตรวจสอบชื่อฟังก์ชัน`, projectPath )); } });
// Check for unused element IDs htmlData.elementIds.forEach((elementInfo, id) => { const isUsed = jsData.getElementByIdCalls.some(call => call.id === id); if (!isUsed && id !== 'app' && id !== 'root') { // ข้าม common framework IDs issues.push(this.createIssue( 'UnusedElementID', 'info', elementInfo.file, elementInfo.line, 1, `Element ID "${id}" ไม่ได้ถูกใช้งานใน JavaScript`, `ลบ ID ที่ไม่จำเป็น หรือเพิ่มโค้ด JavaScript ที่ใช้งาน ID นี้`, projectPath )); } });
console.log(` [HTML-JS] Analysis complete. Found ${issues.length} issues.`); return issues; }
/** * IPC Communication Analyzer - วิเคราะห์การสื่อสาร IPC ระหว่าง Renderer Main * ตรวจสอบ ipcRenderer.invoke กับ ipcMain.handle channel integrity */ analyzeIpcIntegrity(rendererFiles, mainFiles, projectPath) { if (!acorn) { console.warn(' IPC analysis requires acorn package'); return []; }
const issues = []; console.log(' [IPC] Starting IPC communication analysis...');
// Step 1: Parse renderer files for ipcRenderer.invoke calls const rendererChannels = this.parseRendererIpcCalls(rendererFiles, projectPath); // Step 2: Parse main files for ipcMain.handle definitions const mainHandlers = this.parseMainIpcHandlers(mainFiles, projectPath);
// Step 3: Cross-reference channels // Check for missing IPC handlers rendererChannels.forEach(channel => { if (!mainHandlers.has(channel.name)) { issues.push(this.createIssue( 'MissingIpcHandler', 'error', channel.file, channel.line, channel.column, `ipcRenderer.invoke('${channel.name}') ไม่มี handler ใน Main Process`, `เพิ่ม ipcMain.handle('${channel.name}', ...) ใน main.js`, projectPath )); } });
// Check for unused IPC handlers mainHandlers.forEach((handlerInfo, channelName) => { const isUsed = rendererChannels.some(channel => channel.name === channelName); if (!isUsed) { issues.push(this.createIssue( 'UnusedIpcHandler', 'warning', handlerInfo.file, handlerInfo.line, 1, `ipcMain.handle('${channelName}') ไม่ได้ถูกเรียกใช้จาก Renderer`, `ลบ handler ที่ไม่ใช้ หรือเพิ่มการเรียกใช้จาก frontend`, projectPath )); } });
console.log(` [IPC] Analysis complete. Found ${issues.length} issues.`); return issues; }
/** * Architecture Grammar Validator - ตรวจสอบไวยากรณ์ของสถาปัตยกรรม * ตรวจสอบรูปแบบการจัดวางไฟล์และการตั้งชื่อตามมาตรฐาน */ validateArchitectureGrammar(projectPath, fileList) { const issues = []; console.log(' [Architecture] Starting architecture grammar validation...');
// Rule 1: HTML files should be in root or have corresponding JS files const htmlFiles = fileList.filter(f => f.endsWith('.html')); const jsFiles = fileList.filter(f => f.endsWith('.js'));
htmlFiles.forEach(htmlFile => { const baseName = path.basename(htmlFile, '.html'); const expectedJsFile = jsFiles.find(jsFile => path.basename(jsFile, '.js') === baseName || path.basename(jsFile, '.js') === baseName + '.script' );
if (!expectedJsFile && baseName !== 'splash' && baseName !== 'loading') { const relativePath = path.relative(projectPath, htmlFile); issues.push(this.createIssue( 'MissingCompanionJS', 'warning', relativePath, 1, 1, `HTML file "${baseName}.html" ไม่มีไฟล์ JavaScript คู่`, `สร้างไฟล์ ${baseName}.js สำหรับจัดการ logic ของหน้านี้`, projectPath )); } });
// Rule 2: Check for proper electron app structure const hasMainJs = fileList.some(f => path.basename(f) === 'main.js'); const hasPreloadJs = fileList.some(f => path.basename(f) === 'preload.js'); const hasIndexHtml = fileList.some(f => path.basename(f) === 'index.html');
if (hasMainJs && !hasPreloadJs) { issues.push(this.createIssue( 'MissingPreloadScript', 'warning', 'project structure', 1, 1, 'Electron app ควรมี preload.js สำหรับ security', 'สร้างไฟล์ preload.js เพื่อปรับปรุงความปลอดภัย', projectPath )); }
if (hasMainJs && !hasIndexHtml) { issues.push(this.createIssue( 'MissingIndexHtml', 'error', 'project structure', 1, 1, 'Electron app ต้องมี index.html เป็นหน้าหลัก', 'สร้างไฟล์ index.html เป็น entry point ของแอป', projectPath )); }
console.log(` [Architecture] Grammar validation complete. Found ${issues.length} issues.`); return issues; }
// ========== HELPER METHODS FOR ADVANCED ANALYSIS ==========
/** * Parse HTML files to extract element IDs and onclick handlers */ /** * Parse HTML files to extract element IDs and onclick handlers * เวอร์ชันแก้ไข: เพิ่มการค้นหาหมายเลขบรรทัดจริง */ parseHtmlFiles(htmlFiles, projectPath) { const elementIds = new Map(); const onclickHandlers = [];
htmlFiles.forEach(filePath => { try { // 1. อ่านเนื้อหาไฟล์ทั้งหมดเก็บไว้ const content = fs.readFileSync(filePath, 'utf-8'); const lines = content.split('\n'); // แบ่งเนื้อหาเป็นบรรทัด const $ = cheerio.load(content); const relativePath = path.relative(projectPath, filePath);
// 2. ค้นหา Elements ที่มี ID $('[id]').each((i, elem) => { const id = $(elem).attr('id'); if (id) { // 3. ค้นหาหมายเลขบรรทัดของ ID ที่เจอ let lineNumber = 1; // ค่าเริ่มต้น for (let j = 0; j < lines.length; j++) { // ค้นหาบรรทัดที่มี id="your-id" หรือ id='your-id' if (lines[j].includes(`id="${id}"`) || lines[j].includes(`id='${id}'`)) { lineNumber = j + 1; // +1 เพราะ index ของ array เริ่มที่ 0 break; // เจอแล้ว หยุดค้นหา } }
elementIds.set(id, { file: relativePath, line: lineNumber, // ใช้หมายเลขบรรทัดที่หาเจอ tag: elem.tagName }); } });
// ส่วนของ onclick ยังคงทำงานเหมือนเดิม $('[onclick]').each((i, elem) => { const onclick = $(elem).attr('onclick'); if (onclick) { const functionMatch = onclick.match(/(\w+)\s*\(/); if (functionMatch) { onclickHandlers.push({ functionName: functionMatch[1], file: relativePath, line: 1, // onclick ยังใช้ line 1 ไปก่อนได้ element: elem.tagName }); } } });
} catch (error) { console.warn(` Could not parse HTML file: ${filePath}`); } });
return { elementIds, onclickHandlers }; }
/** * Parse JS files to extract getElementById calls and function declarations */ parseJsFiles(jsFiles, projectPath) { const getElementByIdCalls = []; const functionDeclarations = new Set();
jsFiles.forEach(filePath => { try { const content = fs.readFileSync(filePath, 'utf-8'); const relativePath = path.relative(projectPath, filePath); // Skip minified files if (filePath.includes('.min.js')) return;
const ast = acorn.parse(content, { sourceType: 'module', locations: true, ecmaVersion: 'latest', allowReturnOutsideFunction: true });
this.walkAST(ast, (node) => { // Find getElementById calls if (node.type === 'CallExpression' && node.callee && node.callee.type === 'MemberExpression' && node.callee.property && node.callee.property.name === 'getElementById' && node.arguments.length > 0 && node.arguments[0].type === 'Literal') { getElementByIdCalls.push({ id: node.arguments[0].value, file: relativePath, line: node.loc ? node.loc.start.line : 1, column: node.loc ? node.loc.start.column : 1 }); }
// Find function declarations if (node.type === 'FunctionDeclaration' && node.id) { functionDeclarations.add(node.id.name); }
// Find function expressions assigned to variables if (node.type === 'VariableDeclarator' && node.id && node.id.type === 'Identifier' && node.init && (node.init.type === 'FunctionExpression' || node.init.type === 'ArrowFunctionExpression')) { functionDeclarations.add(node.id.name); } });
} catch (error) { console.warn(` Could not parse JS file: ${filePath}`); } });
return { getElementByIdCalls, functionDeclarations }; }
/** * Parse renderer files for ipcRenderer.invoke calls */ parseRendererIpcCalls(rendererFiles, projectPath) { const channels = [];
rendererFiles.forEach(filePath => { try { const content = fs.readFileSync(filePath, 'utf-8'); const relativePath = path.relative(projectPath, filePath); if (filePath.includes('.min.js')) return;
const ast = acorn.parse(content, { sourceType: 'module', locations: true, ecmaVersion: 'latest', allowReturnOutsideFunction: true });
this.walkAST(ast, (node) => { // Find ipcRenderer.invoke calls if (node.type === 'CallExpression' && node.callee && node.callee.type === 'MemberExpression' && node.callee.property && node.callee.property.name === 'invoke' && node.arguments.length > 0 && node.arguments[0].type === 'Literal') { channels.push({ name: node.arguments[0].value, file: relativePath, line: node.loc ? node.loc.start.line : 1, column: node.loc ? node.loc.start.column : 1 }); } });
} catch (error) { console.warn(` Could not parse renderer file: ${filePath}`); } });
return channels; }
/** * Parse main files for ipcMain.handle definitions */ parseMainIpcHandlers(mainFiles, projectPath) { const handlers = new Map();
mainFiles.forEach(filePath => { try { const content = fs.readFileSync(filePath, 'utf-8'); const relativePath = path.relative(projectPath, filePath); const ast = acorn.parse(content, { sourceType: 'module', locations: true, ecmaVersion: 'latest', allowReturnOutsideFunction: true });
this.walkAST(ast, (node) => { // Find ipcMain.handle calls if (node.type === 'CallExpression' && node.callee && node.callee.type === 'MemberExpression' && node.callee.property && node.callee.property.name === 'handle' && node.arguments.length > 0 && node.arguments[0].type === 'Literal') { handlers.set(node.arguments[0].value, { file: relativePath, line: node.loc ? node.loc.start.line : 1 }); } });
} catch (error) { console.warn(` Could not parse main file: ${filePath}`); } });
return handlers; }}
module.exports = ProjectInspector; 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220@echo offchcp 65001 > nultitle Chahuadev Framework -- Desktop Builder
setlocal enabledelayedexpansionset "PROJECT_DIR=%~dp0"cd /d "%PROJECT_DIR%"
echo.echo ================================================================echo Chahuadev Framework -- Desktop Builder v1.0.0echo ================================================================echo.echo Project : %PROJECT_DIR%echo.
:menuecho Build options:echo.echo [1] Windows NSIS + Portable (build-win)echo [2] Windows NSIS Installer onlyecho [3] Windows Portable onlyecho [4] Windows MSI Installer onlyecho [5] Linux AppImage via WSLecho [6] Build exe + AppImageecho [7] Clean Delete dist folderecho [8] Status View build outputecho [9] Exitecho.set /p "choice= > "
if "%choice%"=="1" goto build_winif "%choice%"=="2" goto build_nsisif "%choice%"=="3" goto build_portableif "%choice%"=="4" goto build_msiif "%choice%"=="5" goto build_linuxif "%choice%"=="6" goto build_allif "%choice%"=="7" goto clean_distif "%choice%"=="8" goto show_statusif "%choice%"=="9" goto done
echo.echo [ERROR] Invalid choice. Try again.timeout /t 1 >nulgoto menu
REM ----------------------------------------------------------------:build_winecho.echo [BUILD] Windows -- NSIS + Portable...echo.call npm run build-winif %errorlevel% neq 0 ( echo. echo [FAILED] Windows build failed. pause goto menu)echo.echo [OK] Windows build complete.goto show_results
REM ----------------------------------------------------------------:build_nsisecho.echo [BUILD] Windows -- NSIS Installer...echo.call npm run build-nsisif %errorlevel% neq 0 ( echo. echo [FAILED] NSIS build failed. pause goto menu)echo.echo [OK] NSIS build complete.goto show_results
REM ----------------------------------------------------------------:build_portableecho.echo [BUILD] Windows -- Portable...echo.call npm run build-exeif %errorlevel% neq 0 ( echo. echo [FAILED] Portable build failed. pause goto menu)echo.echo [OK] Portable build complete.goto show_results
REM ----------------------------------------------------------------:build_msiecho.echo [BUILD] Windows -- MSI Installer...echo.call npm run build-msiif %errorlevel% neq 0 ( echo. echo [FAILED] MSI build failed. pause goto menu)echo.echo [OK] MSI build complete.goto show_results
REM ----------------------------------------------------------------:build_linuxecho.echo [BUILD] Linux -- AppImage via WSL...echo.call npm run build:linux:wslif %errorlevel% neq 0 ( echo. echo [FAILED] Linux build failed. echo Make sure WSL and Node.js are installed inside WSL. pause goto menu)echo.echo [OK] Linux build complete.goto show_results
REM ----------------------------------------------------------------:build_allecho.echo [!] Make sure Chahuadev Framework app is fully closed before building.echo (app.asar will be locked if the app is running)echo.set /p "confirm= Continue? (y/n): "if /i not "%confirm%"=="y" goto menuecho.echo [BUILD] exe + AppImage...echo.echo [1/2] Windows Portable (.exe)...call npm run build-exeif %errorlevel% neq 0 ( echo [FAILED] exe build failed. pause goto menu)echo [OK] exe done.echo.echo [2/2] Linux AppImage via WSL...call npm run build:linux:wslif %errorlevel% neq 0 ( echo [FAILED] AppImage build failed. echo Make sure WSL and Node.js are installed inside WSL. pause goto menu)echo [OK] AppImage done.echo.echo [OK] exe + AppImage builds complete.goto show_results
REM ----------------------------------------------------------------:clean_distecho.if exist "dist" ( echo [INFO] Deleting dist\... rmdir /s /q "dist" echo [OK] Done.) else ( echo [INFO] No dist folder found.)echo.pausegoto menu
REM ----------------------------------------------------------------:show_statusecho.echo [STATUS] Files in dist\:echo.if exist "dist" ( for %%f in ("dist\*.exe" "dist\*.msi" "dist\*.AppImage") do echo %%~nxf for /d %%d in ("dist\*") do ( for %%f in ("%%d\*.exe" "%%d\*.msi" "%%d\*.AppImage") do echo %%~nxf )) else ( echo [INFO] No dist folder. Run a build first.)echo.pausegoto menu
REM ----------------------------------------------------------------:show_resultsecho.echo ================================================================echo Build Resultsecho ================================================================echo.if exist "dist" ( for %%f in ("dist\*.exe" "dist\*.msi" "dist\*.AppImage") do echo %%~nxf for /d %%d in ("dist\*") do ( for %%f in ("%%d\*.exe" "%%d\*.msi" "%%d\*.AppImage") do echo %%~nxf ) echo. set /p "open_dist= Open dist folder? (y/n): " if /i "!open_dist!"=="y" start "" "%PROJECT_DIR%dist") else ( echo [INFO] No dist folder found.)echo.pausegoto menu
REM ----------------------------------------------------------------:doneecho.echo Goodbye.echo.endlocalexit /b 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990#!/bin/bash# Build Chahuadev Framework on WSL using native Linux filesystem
BUILD_DIR="/tmp/chahuadev-build-$$"WINDOWS_PROJECT="/mnt/d/Chahuadev/chahuadev-framework-en"OUTPUT_DIR="$WINDOWS_PROJECT/dist"
echo "========================================================"echo "Chahuadev Framework - Linux Build on WSL (Native FS)"echo "========================================================"echo ""
# Step 1: Create temp build directoryecho "[1/5] Setting up build environment..."mkdir -p "$BUILD_DIR"echo " Build directory: $BUILD_DIR"
# Step 2: Copy source code to WSL filesystemecho ""echo "[2/5] Copying project files (this may take a moment)..."cp -r "$WINDOWS_PROJECT" "$BUILD_DIR/project"if [ $? -ne 0 ]; then echo "ERROR: Failed to copy project files" rm -rf "$BUILD_DIR" exit 1fiecho " OK - Project copied"
# Step 3: Navigate and install dependenciesecho ""echo "[3/5] Installing dependencies..."cd "$BUILD_DIR/project"npm install 2>&1 | tail -5if [ $? -ne 0 ]; then echo "ERROR: npm install failed" rm -rf "$BUILD_DIR" exit 1fiecho " OK - Dependencies installed"
# Step 4: Buildecho ""echo "[4/5] Building Linux distribution (x64)..."export NODE_ENV=production
npm run generate-checksumsif [ $? -ne 0 ]; then echo "ERROR: generate-checksums failed" rm -rf "$BUILD_DIR" exit 1fi
echo ""echo "Running electron-builder..."npx electron-builder --linux --x64BUILD_STATUS=$?
# Step 5: Copy output backecho ""echo "[5/5] Copying build output back to Windows..."if [ $BUILD_STATUS -eq 0 ]; then # Remove old dist if exists rm -rf "$OUTPUT_DIR" # Copy new dist cp -r "$BUILD_DIR/project/dist" "$WINDOWS_PROJECT/" if [ $? -eq 0 ]; then echo " OK - Build output copied" echo "" echo "========================================================" echo "SUCCESS - Build completed!" echo "========================================================" echo "" echo "Output files:" ls -lh "$OUTPUT_DIR"/*.AppImage 2>/dev/null # Cleanup rm -rf "$BUILD_DIR" exit 0 else echo "ERROR: Failed to copy output" fielse echo "ERROR: Build failed"fi
# Cleanup on errorrm -rf "$BUILD_DIR"exit 112# This file ensures the plugins directory is tracked by Git# The plugins folder will be empty in the build output, ready for user plugins 12345678910111213{ "main.js": "222c0424abcddf6f3e8d3b1baa622f5471a567aac1a8486401cd1800766f53ca", "preload.js": "20791ca2e1ccb960af534537300c4c355edcf338391e36ff02e03510dc1664c6", "validation_gateway.js": "87d0675b666489c193031d2ea61f265e55cdcdd937932eecbf532ad9e6f0a716", "generate-manifests.js": "050cfeadf9aa259b51660cecbceee816f7ce2a6a4f1730454d30ab78aaf7c1f4", "modules/error-handler.js": "c6aa70f8ecfe5da280caf5f36ca9f8eedceb90e3ca096e6f110011f5aeee285e", "modules/security-logger.js": "04508a07a771d115da42701b70448a2cf005c85a301f83391837ed489142bf28", "modules/system-detector.js": "f7e9eb6a608d3a597df013375fd2760db97f790eba460e66f0dc7db138874ef4", "modules/button-generator.js": "863923b7922ac7eec544efedb12d33e2e9908fa80531a06b2e12f639d7aa5fbc", "modules/plugin-manager.js": "fc0940715218f76b0058327cd8ffe5800a94fee3fc42159ed7dffd99589baffc", "modules/executor.js": "3b839dc67b048ecd94c53f2edf92acdf9612cecd697ef410ec27b290c43dd32f", "modules/context-manager.js": "179c28cf401d67355d07175fee1a5fa80711c737a11438199f03e9f98bd0d828"}16bbd8be4b09efae19de6ed991ff91b8cf6fc45d693487bfa289c496048c30b433a7ce1c7898078df3174cd941a4598db56c605ca381106a4708f4870049629122d4409bfe4a3cba879b308ff8a88b5aebac9a450b9365e8d6a5ad919b7a79a2a3abe258d5aa9c663f9e8abf87ce5d51101d3354319b8b41326a7549e90b63552d183522f49c494adf6208235bca08f093ccb27efe180678dc808e1c33ade6e731c6bae59af272c0ab15f955e73a723ee057b892414dd31d1fd31d33d368683b448c0f8235275ef043fba4b925c4e0fe1b52e2b123599429647987bbe024d47d1274be177007cefd6a78da62074d24c807cdef5e36e1e2b3b542b5421ab1b2d68123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102{ "_comment": " Chahua Development Thailand - Default Configuration", "_author": " CEO: Saharath C.", "server": { "port": 3000, "host": "localhost", "cors": { "enabled": true, "allowedOrigins": [ "*" ], "allowedMethods": [ "GET", "POST", "PUT", "DELETE", "OPTIONS" ], "allowedHeaders": [ "Content-Type", "Authorization", "X-Requested-With" ] } }, "security": { "jwt": { "secret": "default-secret-change-in-production", "expiresIn": "24h", "algorithm": "HS256" }, "rateLimit": { "windowMs": 900000, "maxRequests": 100, "skipSuccessfulRequests": false }, "validation": { "enabled": true, "strictMode": true } }, "logging": { "level": "info", "path": "./chahuadev-framework/logs", "maxSize": 10485760, "maxFiles": 5, "enableConsole": true, "enableFile": true }, "cache": { "maxSize": 100, "defaultTTL": 300000, "cleanupInterval": 60000, "enablePersistence": false, "persistPath": "./chahuadev-framework/logs/cache" }, "retry": { "maxAttempts": 3, "baseDelay": 1000, "maxDelay": 30000, "backoffMultiplier": 2, "jitter": true }, "rollback": { "maxSnapshots": 10, "snapshotPath": "./chahuadev-framework/logs/snapshots", "autoCleanup": true }, "security_logger": { "alertThreshold": 10, "enableRealTimeAlerts": true, "logPath": "./chahuadev-framework/logs/security", "maxLogSize": 10485760, "maxLogFiles": 5 }, "health": { "checkInterval": 30000, "thresholds": { "cpu": 80, "memory": 85, "disk": 90 }, "enableAutoRecovery": true, "alertCooldown": 300000 }, "plugins": { "hotReload": true, "maxExecutionTime": 30000, "loadOnStartup": true, "enableLogging": true }, "api": { "timeout": 10000, "maxRetries": 3, "enableCaching": true }, "test": { "timeout": 5000, "parallel": true, "coverage": true }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143/** * JavaScript Obfuscator Configuration - Fort-Knox Level * * การป้องกันระดับสูงสุดสำหรับโค้ด JavaScript * ป้องกันการทำ Reverse Engineering และการอ่านโค้ดโดยไม่ได้รับอนุญาต * * คำเตือน: การตั้งค่าแบบนี้จะทำให้โค้ดช้าลงเล็กน้อย (5-15%) * แต่จะเพิ่มความปลอดภัยขึ้นอย่างมาก (90%+ harder to reverse engineer) */
module.exports = { // ===== CORE OBFUSCATION SETTINGS ===== // ทำให้ตัวแปรและฟังก์ชันชื่อใหม่ที่อ่านไม่ออก identifierNamesGenerator: 'mangled-shuffled', // เปลี่ยนจาก hexadecimal // เข้ารหัสสตริงทั้งหมด (ลดความเข้มงวด) stringArray: true, stringArrayIndexShift: true, stringArrayRotate: true, stringArrayShuffle: true, stringArrayWrappersCount: 2, // ลดจาก 5 stringArrayWrappersChainedCalls: true, stringArrayWrappersParametersMaxCount: 3, // ลดจาก 5 stringArrayWrappersType: 'function', stringArrayThreshold: 0.8, // ลดจาก 1 (100%) // ===== ANTI-DEBUGGING FEATURES ===== // ป้องกันการใช้ Debug Console debugProtection: true, debugProtectionInterval: 2000, // ตรวจสอบทุก 2 วินาที // ป้องกันการใช้ DevTools disableConsoleOutput: true, // ตรวจจับการใช้เครื่องมือ debugging selfDefending: true, // ===== CODE FLOW PROTECTION ===== // ทำให้โครงสร้างโค้ดซับซ้อน (ลดความเข้มงวด) controlFlowFlattening: true, controlFlowFlatteningThreshold: 0.5, // ลดจาก 1 // สร้าง Dead Code (โค้ดปลอม) เพื่อหลอกลวง (ลดความเข้มงวด) deadCodeInjection: true, deadCodeInjectionThreshold: 0.2, // ลดจาก 0.5 // ===== ADVANCED PROTECTION ===== // แบ่ง string ออกเป็นชิ้นเล็กๆ splitStrings: true, splitStringsChunkLength: 5, // ป้องกันการ beautify โค้ด compact: true, // ลบ comments และ whitespace ทั้งหมด numbersToExpressions: true, // เปลี่ยนตัวเลขเป็น expression simplify: true, // ===== SPECIFIC FOR ELECTRON APPS ===== // เป้าหมาย: Node.js environment target: 'node', // ไม่ obfuscate require() calls เพื่อไม่ให้แอป Electron พัง reservedNames: [ 'require', 'module', 'exports', '__dirname', '__filename', 'process', 'global', 'Buffer', // Electron APIs ที่ต้องการ 'ipcMain', 'ipcRenderer', 'BrowserWindow', 'app', 'dialog', 'shell', 'contextBridge', // เพิ่มชื่อฟังก์ชันสำคัญของเราเองที่ไม่ควรโดน obfuscate 'electronAPI', 'validationGateway' ], // ไม่ obfuscate properties เหล่านี้ reservedStrings: [ 'electron', 'node_modules', 'package.json', 'main.js', 'preload.js', 'renderer.js' ], // ===== PERFORMANCE TUNING ===== // ปรับให้เร็วขึ้นนิดหน่อย (แลกกับความปลอดภัยเล็กน้อย) unicodeEscapeSequence: false, // ปิดเพื่อประสิทธิภาพ // ===== FILES TO EXCLUDE ===== // ไม่ obfuscate ไฟล์พิเศษเหล่านี้ (จะตั้งค่าใน script) excludes: [ // ไฟล์ที่ไม่ควร obfuscate '**/node_modules/**', '**/test/**', '**/tests/**', '**/spec/**', '**/*.test.js', '**/*.spec.js', '**/vendor/**' ]};
/** * คำอธิบายระดับการป้องกัน: * * BASIC (เหมาะสำหรับ prototype): * - stringArray: false * - controlFlowFlattening: false * - debugProtection: false * * MEDIUM (เหมาะสำหรับ production ทั่วไป): * - stringArray: true, threshold: 0.5 * - controlFlowFlattening: true, threshold: 0.3 * - debugProtection: true * * MAXIMUM (สำหรับแอปที่มีมูลค่าสูง - config นี้): * - ทุกอย่างเปิดเต็มที่ * - Anti-debugging เปิด * - Dead code injection * * Note: ยิ่งการป้องกันสูง โค้ดจะยิ่งช้าและใหญ่ขึ้น * แต่จะยากต่อการ reverse engineer มากขึ้นตามไปด้วย */ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102{ "_comment": " Chahua Development Thailand - Production Configuration", "_author": " CEO: Saharath C.", "_warning": " PRODUCTION ENVIRONMENT - Use secure values!", "server": { "port": 8080, "host": "0.0.0.0", "cors": { "enabled": true, "allowedOrigins": [ "https://yourdomain.com", "https://api.yourdomain.com" ], "allowedMethods": [ "GET", "POST", "PUT", "DELETE" ], "allowedHeaders": [ "Content-Type", "Authorization" ] } }, "security": { "jwt": { "secret": "CHANGE_THIS_TO_SECURE_SECRET_IN_PRODUCTION", "expiresIn": "1h", "algorithm": "HS256" }, "rateLimit": { "windowMs": 900000, "maxRequests": 50, "skipSuccessfulRequests": true }, "validation": { "enabled": true, "strictMode": true } }, "logging": { "level": "warn", "path": "/var/log/chahuadev", "maxSize": 52428800, "maxFiles": 10, "enableConsole": false, "enableFile": true }, "cache": { "maxSize": 1000, "defaultTTL": 600000, "cleanupInterval": 300000, "enablePersistence": true, "persistPath": "/var/cache/chahuadev" }, "retry": { "maxAttempts": 5, "baseDelay": 2000, "maxDelay": 60000, "backoffMultiplier": 2.5, "jitter": true }, "rollback": { "maxSnapshots": 50, "snapshotPath": "/var/backups/chahuadev/snapshots", "autoCleanup": true }, "security_logger": { "alertThreshold": 5, "enableRealTimeAlerts": true, "logPath": "/var/log/chahuadev/security", "maxLogSize": 52428800, "maxLogFiles": 20 }, "health": { "checkInterval": 15000, "thresholds": { "cpu": 75, "memory": 80, "disk": 85 }, "enableAutoRecovery": true, "alertCooldown": 600000 }, "plugins": { "hotReload": false, "maxExecutionTime": 10000, "loadOnStartup": true, "enableLogging": false }, "api": { "timeout": 5000, "maxRetries": 5, "enableCaching": true }, "test": { "timeout": 10000, "parallel": false, "coverage": false }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501const { 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 simulationCommand: ${command}Status: Approved but not executed for security reasonsNote: 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; 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884<!DOCTYPE html><html lang="th"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>แดชบอร์ดวินิจฉัยระบบ Chahua Development</title> <style> /* --- CSS Variables for Clean Theme (Based on chahua_license) --- */ :root { --bg-color: #f8f9fa; --surface-color: #ffffff; --primary-text-color: #212529; --secondary-text-color: #6c757d; --accent-color: #0056b3; --accent-hover-color: #004085; --border-color: #dee2e6; --shadow-color: rgba(0, 0, 0, 0.1); --success-color: #28a745; --warning-color: #ffc107; --danger-color: #dc3545; --info-color: #17a2b8; --terminal-bg: #2d3748; --terminal-border: #4a5568; --font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; --border-radius: 12px; --shadow: 0 4px 15px rgba(0, 0, 0, 0.1); --transition: all 0.3s ease; }
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: var(--font-family); background: var(--bg-color); color: var(--primary-text-color); line-height: 1.6; overflow: hidden; height: 100vh; width: 100vw; }
/* Main Container Layout */ .dashboard-container { display: flex; height: 100vh; gap: 20px; padding: 20px; position: relative; }
/* Left Panel - Terminal Section */ .terminal-panel { background: var(--terminal-bg); border-radius: var(--border-radius); color: #ffffff; font-family: 'Courier New', monospace; box-shadow: var(--shadow); display: flex; flex-direction: column; overflow: hidden; border: 1px solid var(--border-color); flex: 0 0 auto; position: relative; min-width: 400px; max-width: 75%; width: calc(60% - 10px); }
.terminal-header { background: rgba(0, 86, 179, 0.1); padding: 15px 20px; border-bottom: 1px solid var(--border-color); display: flex; align-items: center; justify-content: space-between; }
.terminal-title { color: var(--accent-color); font-size: 1.1rem; margin: 0; font-weight: 600; display: flex; align-items: center; gap: 10px; }
.terminal-controls { display: flex; gap: 8px; }
.terminal-btn { background: var(--surface-color); color: var(--accent-color); border: 1px solid var(--border-color); padding: 6px 12px; border-radius: var(--border-radius); cursor: pointer; font-size: 0.8rem; font-weight: 500; transition: var(--transition); white-space: nowrap; }
.terminal-btn:hover { background: var(--accent-color); color: white; border-color: var(--accent-color); transform: translateY(-2px); box-shadow: 0 4px 8px rgba(0, 86, 179, 0.2); }
.terminal-btn:disabled { background: var(--bg-color); color: var(--secondary-text-color); cursor: not-allowed; border-color: var(--border-color); transform: none; box-shadow: none; }
.terminal-btn.export-btn { background: var(--success-color); border-color: var(--success-color); color: white; }
.terminal-btn.export-btn:hover:not(:disabled) { background: #1e7e34; border-color: #1e7e34; }
#terminal-container { flex: 1; padding: 20px; background: var(--terminal-bg); overflow: hidden; font-family: 'Consolas', 'Monaco', 'Courier New', monospace; font-size: 0.9rem; line-height: 1.4; }
/* Resize Handle */ .resize-handle { position: absolute; top: 0; right: -10px; width: 20px; height: 100%; cursor: col-resize; background: transparent; z-index: 10; user-select: none; display: flex; align-items: center; justify-content: center; }
.resize-handle::before { content: ''; width: 4px; height: 40px; background: var(--border-color); border-radius: 2px; transition: var(--transition); }
.resize-handle:hover::before { background: var(--accent-color); opacity: 0.7; }
.resize-handle.resizing::before { background: var(--accent-color); opacity: 1; box-shadow: 0 0 10px rgba(0, 86, 179, 0.5); }
.dashboard-container.resizing { user-select: none; }
.dashboard-container.resizing * { pointer-events: none; }
.dashboard-container.resizing .resize-handle { pointer-events: auto; }
/* Right Panel - Analysis Panel */ .analysis-panel { background: var(--surface-color); border-radius: var(--border-radius); box-shadow: var(--shadow); overflow: hidden; border: 1px solid var(--border-color); flex: 1; min-width: 300px; display: flex; flex-direction: column; }
.analysis-header { background: var(--surface-color); padding: 20px; border-bottom: 1px solid var(--border-color); }
.analysis-title { color: var(--accent-color); font-size: 1.3rem; font-weight: 600; margin: 0; text-align: center; }
.analysis-content { flex: 1; overflow-y: auto; padding: 20px; }
/* Inspector Panel */ .inspector-panel { background: var(--surface-color); border-radius: var(--border-radius); border: 1px solid var(--border-color); overflow: hidden; }
.inspector-header { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px; padding: 15px 20px; background: rgba(0, 86, 179, 0.05); border-bottom: 1px solid var(--border-color); }
.inspector-title { color: var(--accent-color); font-size: 1.1rem; font-weight: 600; display: flex; align-items: center; gap: 8px; }
.inspector-controls { display: flex; gap: 8px; flex-wrap: wrap; }
.inspector-content { padding: 20px; display: flex; flex-direction: column; gap: 15px; }
/* Inspector Stats */ .inspector-stats { background: rgba(0, 86, 179, 0.05); border-radius: var(--border-radius); padding: 15px; border: 1px solid var(--border-color); }
.stats-row { display: flex; justify-content: space-around; gap: 10px; margin-bottom: 10px; }
.stat-item { text-align: center; }
.stat-label { color: var(--secondary-text-color); font-size: 0.85rem; margin-bottom: 5px; }
.stat-value { color: var(--primary-text-color); font-size: 1.5rem; font-weight: bold; }
.stat-error { color: var(--danger-color); }
.stat-warning { color: var(--warning-color); }
/* Inspector Filters */ .inspector-filters { background: var(--surface-color); border-radius: var(--border-radius); padding: 15px; border: 1px solid var(--border-color); }
.filter-group { margin-bottom: 10px; display: flex; align-items: center; gap: 10px; }
.filter-group label { color: var(--secondary-text-color); font-size: 0.9rem; font-weight: 500; min-width: 120px; }
.filter-group select { flex: 1; padding: 8px 12px; border: 1px solid var(--border-color); border-radius: var(--border-radius); background: var(--surface-color); color: var(--primary-text-color); font-size: 0.9rem; transition: var(--transition); }
.filter-group select:focus { outline: none; border-color: var(--accent-color); box-shadow: 0 0 0 2px rgba(0, 86, 179, 0.2); }
/* Inspector Results */ .inspector-results { background: var(--surface-color); border-radius: var(--border-radius); padding: 20px; border: 1px solid var(--border-color); min-height: 200px; }
.no-selection { text-align: center; color: var(--secondary-text-color); padding: 30px; }
.no-selection i { font-size: 3rem; margin-bottom: 20px; color: var(--border-color); }
.no-selection h3 { color: var(--primary-text-color); margin-bottom: 10px; font-size: 1.2rem; }
/* Code Snippet */ .code-snippet { background: var(--terminal-bg) !important; color: #c9d1d9; font-family: 'Consolas', 'Courier New', monospace; white-space: pre; overflow-x: auto; border: 1px solid var(--border-color); border-radius: var(--border-radius); padding: 15px; margin: 10px 0; font-size: 0.85rem; line-height: 1.4; }
/* Detail Section */ .detail-section { margin-bottom: 20px; }
.detail-label { color: var(--accent-color); font-weight: 600; margin-bottom: 8px; font-size: 0.9rem; }
.detail-value { background: rgba(0, 86, 179, 0.05); padding: 12px; border-radius: var(--border-radius); font-family: 'Courier New', monospace; white-space: pre-wrap; word-break: break-word; border: 1px solid var(--border-color); font-size: 0.85rem; }
/* Scrollbar */ ::-webkit-scrollbar { width: 8px; }
::-webkit-scrollbar-track { background: var(--bg-color); }
::-webkit-scrollbar-thumb { background: var(--border-color); border-radius: 4px; }
::-webkit-scrollbar-thumb:hover { background: var(--secondary-text-color); }
/* CSS สำหรับ Log Viewer ใหม่ */ .log-viewer-container { flex: 1; background: #0d1117; /* สีดำสนิท */ color: #c9d1d9; /* สีเทาอ่อน */ font-family: 'Consolas', 'Courier New', monospace; font-size: 13px; padding: 15px; overflow-y: auto; /* ทำให้เลื่อนได้เมื่อ Log ยาว */ white-space: pre-wrap; /* ทำให้ขึ้นบรรทัดใหม่เมื่อยาวเกิน */ word-break: break-all; margin: 0; border: none; outline: none; }
/* สไตล์สำหรับแต่ละบรรทัดของ Log */ .log-line { display: block; margin: 0; padding: 1px 0; }
/* สีสำหรับ Log แต่ละประเภท */ .log-line.log-error { color: #f85149; font-weight: bold; } .log-line.log-warning { color: #f2cc60; } .log-line.log-success { color: #7ee787; } .log-line.log-info { color: #8b949e; } /* สีเทาสำหรับข้อมูลทั่วไป */ .log-line.log-debug { color: #58a6ff; } /* สีฟ้าสำหรับ debug */ .log-line.log-command { color: #bc8cff; font-style: italic; }
/* Responsive adjustments */ @media (max-width: 768px) { .dashboard-container { flex-direction: column; } .terminal-panel { width: 100%; max-width: none; height: 50%; } .inspector-controls { justify-content: center; } }
/* Hide dev buttons unless in dev mode */ body:not(.dev-mode) .dev-only { display: none !important; } </style></head><body> <div class="dashboard-container"> <!-- Left Panel - Terminal Section --> <div class="terminal-panel"> <div class="terminal-header"> <div class="terminal-title"> <i class="fas fa-terminal"></i> เทอร์มินัลแบบโต้ตอบ </div> </div> <pre id="log-viewer" class="log-viewer-container"></pre> <!-- Resize Handle --> <div class="resize-handle" id="resizeHandle"></div> </div>
<!-- Right Panel - Inspector Panel --> <div class="analysis-panel"> <div class="analysis-header"> <div class="analysis-title"> <i class="fas fa-search"></i> เครื่องมือตรวจสอบโปรเจค </div> </div> <div class="analysis-content"> <div class="inspector-panel"> <div class="inspector-header"> <div class="inspector-title"> <i class="fas fa-bug"></i> ตรวจสอบและวิเคราะห์ </div> <div class="inspector-controls"> <button class="terminal-btn dev-only" id="scanSelfBtn"> <i class="fas fa-user-secret"></i> สแกนตัวเอง (Dev) </button> <button class="terminal-btn" id="scanPluginsBtn"> <i class="fas fa-puzzle-piece"></i> สแกนปลั๊กอิน </button> <button class="terminal-btn dev-only" id="runE2eTestsBtn" style="color: var(--success-color) !important; border-color: var(--success-color) !important;"> <i class="fas fa-vial"></i> เริ่มการทดสอบ E2E (Dev) </button> <button class="terminal-btn dev-only" id="openTestReportBtn" style="color: var(--warning-color) !important; border-color: var(--warning-color) !important;"> <i class="fas fa-chart-line"></i> เปิดรายงานผลการทดสอบ (Dev) </button> <button class="terminal-btn export-btn" id="exportIssuesBtn" disabled style="display: none;"> <i class="fas fa-download"></i> ส่งออก JSON </button> </div> </div> <div class="inspector-content"> <div class="inspector-stats" id="inspectorStats" style="display: none;"> <div class="stats-row"> <div class="stat-item"> <div class="stat-label">ไฟล์ทั้งหมด</div> <div class="stat-value" id="totalFiles">0</div> </div> <div class="stat-item"> <div class="stat-label">ปัญหาทั้งหมด</div> <div class="stat-value" id="totalIssues">0</div> </div> <div class="stat-item"> <div class="stat-label">ข้อผิดพลาด</div> <div class="stat-value stat-error" id="totalErrors">0</div> </div> <div class="stat-item"> <div class="stat-label">คำเตือน</div> <div class="stat-value stat-warning" id="totalWarnings">0</div> </div> </div> </div> <div class="inspector-filters" id="inspectorFilters" style="display: none;"> <div class="filter-group"> <label>กรองตามประเภท:</label> <select id="typeFilter"> <option value="all">ทุกประเภท</option> <option value="SyntaxError">ข้อผิดพลาดไวยากรณ์</option> <option value="MissingFile">ไฟล์หายไป</option> <option value="UnusedFile">ไฟล์ไม่ได้ใช้</option> <option value="MissingDependency">การพึ่งพาหายไป</option> <option value="CircularDependency">การพึ่งพาแบบวนรอบ</option> <option value="DuplicateExport">การส่งออกซ้ำ</option> <option value="MissingExport">การนำเข้า/ส่งออกไม่ตรงกัน</option> </select> </div> <div class="filter-group"> <label>กรองตามความรุนแรง:</label> <select id="severityFilter"> <option value="all">ทุกระดับ</option> <option value="error">ข้อผิดพลาด</option> <option value="warning">คำเตือน</option> <option value="info">ข้อมูล</option> </select> </div> </div> <div class="inspector-results" id="inspectorResults"> <div class="no-selection"> <i class="fas fa-search"></i> <h3>เครื่องมือตรวจสอบโปรเจค</h3> <p>เครื่องมือวิเคราะห์โค้ดเพื่อหาปัญหาต่างๆ ก่อนการรัน</p> <div style="margin-top: 20px; text-align: left;"> <h4 style="color: var(--accent-color); margin-bottom: 10px;">ความสามารถ:</h4> <ul style="color: var(--secondary-text-color); line-height: 1.6;"> <li>ตรวจสอบไวยากรณ์ (ข้อผิดพลาดไวยากรณ์)</li> <li>หาไฟล์ที่ไม่มีอยู่จริง (ไฟล์หายไป)</li> <li>หาไฟล์ที่ไม่ได้ใช้งาน (ไฟล์ไม่ได้ใช้)</li> <li>ตรวจสอบการพึ่งพาที่ขาดหาย</li> <li>หาการพึ่งพาแบบวนรอบ</li> <li>หาการส่งออกซ้ำ</li> <li>หาการนำเข้า/ส่งออกไม่ตรงกัน (ข้อผิดพลาดรันไทม์)</li> </ul> </div> <div style="margin-top: 20px;"> <p style="color: var(--warning-color);">คลิก "สแกนปลั๊กอิน" เพื่อเริ่มวิเคราะห์</p> </div> </div> </div> </div> </div> </div> </div> </div>
<script src="debugger.js"></script> <script> // ================================= // PRODUCTION SECURITY SYSTEM // ================================= // ตรวจสอบโหมดการทำงาน const isDevelopmentMode = () => { // ตรวจสอบจาก URL parameters const urlParams = new URLSearchParams(window.location.search); const devParam = urlParams.get('dev'); // ตรวจสอบจาก localStorage const devStorage = localStorage.getItem('chahua_dev_mode'); // ตรวจสอบจาก environment variables (ถ้ามี) const isLocalhost = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1' || window.location.hostname === ''; return devParam === 'true' || devStorage === 'true' || isLocalhost; };
// ระบบป้องกัน Console และ Developer Tools const initProductionSecurity = () => { if (isDevelopmentMode()) { // เปิดใช้งาน dev mode document.body.classList.add('dev-mode'); console.log('%c Developer Mode Enabled', 'color: #28a745; font-weight: bold; font-size: 14px;'); return; }
// ปิดใช้งาน console ทั้งหมด const noop = () => {}; const consoleMethods = [ 'log', 'debug', 'info', 'warn', 'error', 'assert', 'dir', 'dirxml', 'group', 'groupEnd', 'time', 'timeEnd', 'count', 'trace', 'profile', 'profileEnd' ]; consoleMethods.forEach(method => { console[method] = noop; });
// ป้องกันการเปิด Developer Tools let devtools = {open: false, orientation: null}; const threshold = 160;
setInterval(() => { if (window.outerHeight - window.innerHeight > threshold || window.outerWidth - window.innerWidth > threshold) { if (!devtools.open) { devtools.open = true; // Redirect หรือ แสดงข้อความเตือน document.body.innerHTML = ` <div style=" position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: #f8f9fa; display: flex; align-items: center; justify-content: center; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; "> <div style="text-align: center; color: #212529;"> <h2 style="color: #dc3545; margin-bottom: 20px;"> การเข้าถึงถูกจำกัด</h2> <p>กรุณาปิด Developer Tools เพื่อดำเนินการต่อ</p> <p style="color: #6c757d; font-size: 0.9rem;">Developer Tools detected. Please close to continue.</p> </div> </div> `; } } else { devtools.open = false; } }, 500);
// ปิดใช้งานคำสั่งลัดของ Developer Tools document.addEventListener('keydown', (e) => { // ปิด F12 if (e.key === 'F12') { e.preventDefault(); return false; } // ปิด Ctrl+Shift+I, Ctrl+Shift+J, Ctrl+Shift+C if (e.ctrlKey && e.shiftKey && (e.key === 'I' || e.key === 'J' || e.key === 'C')) { e.preventDefault(); return false; } // ปิด Ctrl+U (View Source) if (e.ctrlKey && e.key === 'U') { e.preventDefault(); return false; } // ปิด Ctrl+S (Save Page) if (e.ctrlKey && e.key === 'S') { e.preventDefault(); return false; } });
// ป้องกัน Right Click Context Menu document.addEventListener('contextmenu', (e) => { e.preventDefault(); return false; });
// ป้องกัน Text Selection document.addEventListener('selectstart', (e) => { e.preventDefault(); return false; });
// ป้องกัน Drag and Drop document.addEventListener('dragstart', (e) => { e.preventDefault(); return false; }); };
// ================================= // RESIZE HANDLE FUNCTIONALITY // ================================= // Resize Handle Functionality class ResizeController { constructor() { this.container = document.querySelector('.dashboard-container'); this.terminalPanel = document.querySelector('.terminal-panel'); this.resizeHandle = document.getElementById('resizeHandle'); this.isResizing = false; this.resizeTimeout = null;
if (this.resizeHandle) { this.init(); } }
init() { // เพิ่ม throttled resize method this.boundThrottledResize = this.throttle(this.resizeTerminal.bind(this), 100); // Bound methods for proper event handling this.boundHandleResize = this.handleResize.bind(this); this.boundStopResize = this.stopResize.bind(this); this.boundKeydownHandler = this.handleKeydown.bind(this); this.emergencyCleanup = this.stopResize.bind(this);
// Mouse events this.resizeHandle.addEventListener('mousedown', this.startResize.bind(this)); // Log เฉพาะใน dev mode if (isDevelopmentMode()) { console.log(" Resize controller initialized for debugger"); } }
startResize(e) { e.preventDefault(); this.isResizing = true; // Add visual feedback this.container.classList.add('resizing'); this.resizeHandle.classList.add('resizing'); // Add event listeners document.addEventListener('mousemove', this.boundHandleResize); document.addEventListener('mouseup', this.boundStopResize); // Emergency cleanup listeners document.addEventListener('mouseleave', this.emergencyCleanup); window.addEventListener('blur', this.emergencyCleanup); document.addEventListener('keydown', this.boundKeydownHandler); // Log เฉพาะใน dev mode if (isDevelopmentMode()) { console.log(" Resize started"); } }
handleResize(e) { if (!this.isResizing) return; e.preventDefault(); const containerRect = this.container.getBoundingClientRect(); const newWidth = e.clientX - containerRect.left; const containerWidth = containerRect.width; const minWidth = 300; const maxWidth = containerWidth * 0.8; if (newWidth >= minWidth && newWidth <= maxWidth) { this.terminalPanel.style.width = `${newWidth}px`; this.terminalPanel.style.flex = 'none'; } }
handleKeydown(e) { if (e.key === 'Escape' && this.isResizing) { this.stopResize(); } }
stopResize() { if (!this.isResizing) return; this.isResizing = false; // Remove visual feedback this.container.classList.remove('resizing'); this.resizeHandle.classList.remove('resizing'); // Remove event listeners document.removeEventListener('mousemove', this.boundHandleResize); document.removeEventListener('mouseup', this.boundStopResize); // Remove emergency cleanup listeners document.removeEventListener('mouseleave', this.emergencyCleanup); window.removeEventListener('blur', this.emergencyCleanup); document.removeEventListener('keydown', this.boundKeydownHandler); // Clear timeout if (this.resizeTimeout) { clearTimeout(this.resizeTimeout); this.resizeTimeout = null; } // Log เฉพาะใน dev mode if (isDevelopmentMode()) { console.log(" Resize stopped and listeners cleaned up"); } }
// เพิ่มฟังก์ชัน throttle เข้าไปใน Class throttle(func, limit) { let inThrottle; return function() { const args = arguments; const context = this; if (!inThrottle) { func.apply(context, args); inThrottle = true; setTimeout(() => inThrottle = false, limit); } } }
// เพิ่มฟังก์ชัน resizeTerminal สำหรับการอ้างอิงใน boundThrottledResize resizeTerminal() { // ถ้ามี diagnostic dashboard ให้เรียกใช้ resizeTerminal ของมัน if (window.diagnosticDashboard && window.diagnosticDashboard.resizeTerminal) { window.diagnosticDashboard.resizeTerminal(); } } }
// ================================= // INITIALIZATION // =================================
// Initialize security system first initProductionSecurity();
// Initialize resize controller when DOM is loaded document.addEventListener('DOMContentLoaded', () => { window.resizeController = new ResizeController(); });
// Cleanup on page unload window.addEventListener('beforeunload', () => { if (window.resizeController) { window.resizeController.stopResize(); } }); </script></body></html> 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659/** * Chahuadev Hybrid Diagnostic Dashboard - Terminal + GUI */
class DiagnosticDashboard { constructor() { this.selectedLog = null; this.currentTab = 'details'; this.maxLogs = 1000; this.init(); }
async init() { console.log(' เริ่มต้น Hybrid Diagnostic Dashboard...'); // ตั้งค่า global reference สำหรับการเรียกใช้จาก HTML window.diagnosticDashboard = this;
// ตรวจสอบ DEV MODE try { // เรียก API จาก Backend เพื่อตรวจสอบโหมดการทำงาน const runMode = await window.electronAPI.getRunMode(); if (runMode && runMode.isDevMode) { console.log(' Running in Developer Mode'); document.body.classList.add('dev-mode'); } else { console.log(' Running in User Mode'); document.body.classList.remove('dev-mode'); } } catch (error) { console.warn(' ไม่สามารถตรวจสอบโหมดการทำงานได้', error); } this.setupTerminal(); this.setupEventListeners(); this.startRealTimeUpdates(); console.log(' Hybrid Diagnostic Dashboard พร้อมใช้งาน'); }
// [เวอร์ชันใหม่] ตั้งค่า Log Viewer ของเราเอง setupTerminal() { // เราจะเรียกใช้ฟังก์ชันนี้ใน init() เหมือนเดิม // แต่ตอนนี้มันแค่เตรียมพร้อม ไม่ได้สร้าง Terminal ที่ซับซ้อน this.logViewer = document.getElementById('log-viewer'); if (this.logViewer) { this.logViewer.innerHTML = ''; // ล้าง Log เก่าตอนเริ่มต้น this.writeLog({ message: '===== Chahuadev Diagnostic Log (Raw HTML) =====', type: 'debug' }); this.writeLog({ message: 'Real-time logs will appear here...', type: 'info' }); } else { console.error('Log viewer container not found!'); } }
// ไม่ต้องมี resizeTerminal() อีกต่อไป เพราะ CSS จัดการให้แล้ว!
/** * Throttle function เพื่อจำกัดการเรียกฟังก์ชัน */ throttle(func, limit) { let inThrottle; return function() { const args = arguments; const context = this; if (!inThrottle) { func.apply(context, args); inThrottle = true; setTimeout(() => inThrottle = false, limit); } } }
setupEventListeners() { // Tab buttons document.querySelectorAll('.tab-btn').forEach(btn => { btn.addEventListener('click', (e) => { this.setActiveTab(e.target.dataset.tab); }); });
// Project Inspector buttons document.getElementById('scanSelfBtn')?.addEventListener('click', async () => { await this.handleProjectScan('self'); });
document.getElementById('scanPluginsBtn')?.addEventListener('click', async () => { await this.handleProjectScan('plugins'); });
document.getElementById('exportIssuesBtn')?.addEventListener('click', async () => { await this.handleExportIssues(); });
// E2E Testing button document.getElementById('runE2eTestsBtn')?.addEventListener('click', async () => { this.writeln('\x1b[1;36m กำลังเริ่มการทดสอบ E2E ทั้งระบบ...\x1b[0m'); try { const result = await window.electronAPI.diagnostics.runE2eTests(); if (result.success) { this.writeln('\x1b[1;32m การทดสอบ E2E เสร็จสิ้น\x1b[0m'); if (result.message) { this.writeln(`\x1b[1;37m${result.message}\x1b[0m`); } } else { this.writeln(`\x1b[1;31m การทดสอบ E2E ล้มเหลว: ${result.error}\x1b[0m`); } } catch (error) { this.writeln(`\x1b[1;31m ไม่สามารถเริ่มการทดสอบได้: ${error.message}\x1b[0m`); } });
// Open Test Report button document.getElementById('openTestReportBtn')?.addEventListener('click', async () => { this.writeln('\x1b[1;33m กำลังเปิดรายงานผลการทดสอบ...\x1b[0m'); try { const result = await window.electronAPI.diagnostics.openTestReport(); if (result.success) { this.writeln('\x1b[1;32m เปิดรายงานผลการทดสอบแล้ว\x1b[0m'); if (result.message) { this.writeln(`\x1b[1;37m${result.message}\x1b[0m`); } } else { this.writeln(`\x1b[1;31m ไม่สามารถเปิดรายงานได้: ${result.error}\x1b[0m`); } } catch (error) { this.writeln(`\x1b[1;31m เกิดข้อผิดพลาด: ${error.message}\x1b[0m`); } }); }
/** * จัดการการสแกนโปรเจกต์ * @param {'self' | 'plugins'} target - เป้าหมายที่จะสแกน */ async handleProjectScan(target) { try { let projectPath = null; // เริ่มต้นเป็น null let targetName = '';
// ปรับปรุงตรรกะการเลือก Path if (target === 'self') { targetName = 'โปรเจกต์หลัก (Framework)'; // ขอ Path ของโปรแกรมปัจจุบันจาก Backend projectPath = await window.electronAPI.system.getCwd(); } else if (target === 'plugins') { targetName = 'ปลั๊กอินทั้งหมด'; // ไม่ต้องส่ง Path! เพื่อให้ main process ใช้ default path ของ plugins projectPath = undefined; // ให้ Backend เลือก plugins directory เอง } else { this.writeln(`\x1b[1;31m ข้อผิดพลาด: ไม่รู้จักเป้าหมายการสแกน '${target}'\x1b[0m`); return; }
this.writeln(`\x1b[1;33m กำลังเริ่มวิเคราะห์: ${targetName}...\x1b[0m`); if (projectPath) { this.writeln(`\x1b[1;36m Path: ${projectPath}\x1b[0m`); } else { this.writeln(`\x1b[1;36m ใช้ Path เริ่มต้นของปลั๊กอิน\x1b[0m`); }
// ปิดการใช้งานปุ่มขณะสแกน const scanSelfBtn = document.getElementById('scanSelfBtn'); const scanPluginsBtn = document.getElementById('scanPluginsBtn'); const exportBtn = document.getElementById('exportIssuesBtn'); if (scanSelfBtn) scanSelfBtn.disabled = true; if (scanPluginsBtn) scanPluginsBtn.disabled = true;
// ซ่อนปุ่ม export ขณะสแกน if (exportBtn) { exportBtn.style.display = 'none'; exportBtn.disabled = true; }
if (window.electronAPI && window.electronAPI.project) { // เรียก API โดยส่ง path ที่อาจจะเป็น undefined สำหรับ plugins const result = await window.electronAPI.project.analyze(projectPath);
if (result.success) { const scanInfo = result.scanTarget ? ` (${result.scanTarget})` : ''; this.writeln(`\x1b[1;32m วิเคราะห์สำเร็จ${scanInfo}: พบ ${result.analysis.totalIssues} ปัญหาใน ${result.analysis.totalFiles} ไฟล์\x1b[0m`); // แสดงรายละเอียดเพิ่มเติม if (result.analysis.totalFiles === 0) { this.writeln(`\x1b[1;33m ไม่พบไฟล์ในโฟลเดอร์นี้ หรือไฟล์ทั้งหมดถูกคัดกรองออกโดย exclusion rules\x1b[0m`); } // แสดงผลลัพธ์ใน Inspector tab this.displayAnalysisResults(result.analysis); } else { this.writeln(`\x1b[1;31m วิเคราะห์ล้มเหลว: ${result.error}\x1b[0m`); // แสดงปุ่ม export แม้ว่าจะล้มเหลว เผื่อมีข้อมูลบางส่วน if (exportBtn) { exportBtn.style.display = 'inline-block'; exportBtn.disabled = false; } } } else { this.writeln('\x1b[1;31m ข้อผิดพลาด: ไม่พบ Project Inspector API\x1b[0m'); } } catch (error) { this.writeln(`\x1b[1;31m ข้อผิดพลาดในการสแกน: ${error.message}\x1b[0m`); } finally { // คืนสถานะปุ่ม const scanSelfBtn = document.getElementById('scanSelfBtn'); const scanPluginsBtn = document.getElementById('scanPluginsBtn'); if (scanSelfBtn) scanSelfBtn.disabled = false; if (scanPluginsBtn) scanPluginsBtn.disabled = false; } }
/** * แสดงผลลัพธ์การวิเคราะห์ */ displayAnalysisResults(analysis) { // อัปเดตสถิติ document.getElementById('totalFiles').textContent = analysis.totalFiles || 0; document.getElementById('totalIssues').textContent = analysis.totalIssues || 0; document.getElementById('totalErrors').textContent = analysis.stats?.syntaxErrors || 0; document.getElementById('totalWarnings').textContent = (analysis.stats?.missingFiles || 0) + (analysis.stats?.unusedFiles || 0) + (analysis.stats?.circularDependencies || 0);
// แสดงส่วนสถิติและฟิลเตอร์ document.getElementById('inspectorStats').style.display = 'block'; document.getElementById('inspectorFilters').style.display = 'block';
// แสดงรายการปัญหา this.displayIssuesList(analysis.issues || []);
// เก็บข้อมูลสำหรับการ export this.currentAnalysis = analysis;
// แสดงปุ่ม Export JSON หลังจากมีผลลัพธ์ (ไม่ว่าจะพบปัญหาหรือไม่) const exportBtn = document.getElementById('exportIssuesBtn'); if (exportBtn) { exportBtn.style.display = 'inline-block'; exportBtn.disabled = false; // แจ้งเตือนเมื่อพบปัญหา if (analysis.issues && analysis.issues.length > 0) { this.writeln('\x1b[1;36m คลิกปุ่ม "ส่งออก JSON" เพื่อบันทึกผลการวิเคราะห์\x1b[0m'); } else { this.writeln('\x1b[1;36m ผลการวิเคราะห์พร้อมส่งออก (ไม่พบปัญหา)\x1b[0m'); } }
// แสดง notification แทนการเปลี่ยนแท็บอัตโนมัติ this.writeln('\x1b[1;33m ผลการวิเคราะห์พร้อมแล้ว! ไปดูในแท็บ "Inspector" ด้านบน\x1b[0m'); }
/** * แสดงรายการปัญหา */ displayIssuesList(issues) { const resultsContainer = document.getElementById('inspectorResults'); if (!issues || issues.length === 0) { resultsContainer.innerHTML = ` <div class="no-selection"> <i class="fas fa-check-circle" style="color: #10b981;"></i> <h3>ไม่พบปัญหา</h3> <p>โปรเจกต์ของคุณไม่มีปัญหาที่ตรวจพบ</p> </div> `; return; }
let html = '<div class="issues-list">'; issues.forEach((issue, index) => { const severityClass = issue.severity === 'error' ? 'stat-error' : 'stat-warning'; const severityIcon = issue.severity === 'error' ? 'fas fa-times-circle' : 'fas fa-exclamation-triangle'; const severityText = issue.severity === 'error' ? 'ข้อผิดพลาด' : 'คำเตือน'; const codeSnippetId = `code-snippet-${index}`; html += ` <div class="issue-item" style="background: #2a2a2a; border-radius: 6px; padding: 12px; margin-bottom: 10px; border-left: 3px solid ${issue.severity === 'error' ? '#ef4444' : '#f59e0b'};"> <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 8px;"> <div> <span class="${severityClass}" style="font-weight: bold;"> <i class="${severityIcon}"></i> ${issue.type} </span> <span style="color: #9ca3af; margin-left: 10px; font-size: 12px;"> ${issue.file}:${issue.line}:${issue.column} </span> </div> <span style="background: #1a1a1a; color: #9ca3af; padding: 2px 6px; border-radius: 3px; font-size: 11px;"> ${severityText.toUpperCase()} </span> </div> <div style="color: #e0e0e0; margin-bottom: 12px;">${issue.message}</div> ${issue.codeSnippet ? ` <div class="code-snippet-container" style="margin-bottom: 12px;"> <div style="display: flex; align-items: center; justify-content: space-between; background: #1a1a1a; padding: 6px 10px; border-radius: 4px 4px 0 0; border-bottom: 1px solid #3a3a3a;"> <span style="color: #9ca3af; font-size: 12px; font-weight: 500;"> <i class="fas fa-code" style="margin-right: 5px;"></i> บริบทของโค้ด </span> <button class="copy-code-btn" onclick="window.diagnosticDashboard.copyCodeSnippet('${codeSnippetId}')" style="background: none; border: none; color: #9ca3af; cursor: pointer; font-size: 12px; padding: 2px 5px; border-radius: 2px;"> <i class="fas fa-copy"></i> คัดลอก </button> </div> <pre id="${codeSnippetId}" class="code-snippet" style="background: #0d1117; color: #c9d1d9; margin: 0; padding: 12px; border-radius: 0 0 4px 4px; overflow-x: auto; font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; font-size: 13px; line-height: 1.4;"><code class="language-javascript">${this.escapeHtml(issue.codeSnippet)}</code></pre> </div> ` : ''} ${issue.suggestion ? `<div style="color: #4fc3f7; font-size: 13px; font-style: italic;"> ${issue.suggestion}</div>` : ''} </div> `; }); html += '</div>'; resultsContainer.innerHTML = html;
// เพิ่ม syntax highlighting this.applySyntaxHighlighting();
// เพิ่ม filter functionality this.setupIssueFilters(issues); }
/** * หลีกเลี่ยงการแสดง HTML tags ในโค้ด */ escapeHtml(text) { const div = document.createElement('div'); div.textContent = text; return div.innerHTML; }
/** * ใช้ syntax highlighting กับ code snippets */ applySyntaxHighlighting() { const codeBlocks = document.querySelectorAll('.code-snippet code'); codeBlocks.forEach(block => { this.highlightJavaScript(block); }); }
/** * Syntax highlighting สำหรับ JavaScript */ highlightJavaScript(codeElement) { let code = codeElement.textContent; // Keywords code = code.replace(/\b(const|let|var|function|class|if|else|for|while|return|import|export|from|require|try|catch|throw|async|await|new|this|super|extends|static|null|undefined|true|false)\b/g, '<span style="color: #ff7b72;">$1</span>'); // Strings code = code.replace(/(["'`])((?:\\.|(?!\1)[^\\])*?)\1/g, '<span style="color: #a5d6ff;">$1$2$1</span>'); // Numbers code = code.replace(/\b(\d+(?:\.\d+)?)\b/g, '<span style="color: #79c0ff;">$1</span>'); // Comments code = code.replace(/\/\/(.*$)/gm, '<span style="color: #8b949e; font-style: italic;">//$1</span>'); code = code.replace(/\/\*([\s\S]*?)\*\//g, '<span style="color: #8b949e; font-style: italic;">/*$1*/</span>'); // Function calls code = code.replace(/\b([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(/g, '<span style="color: #d2a8ff;">$1</span>('); // Problem line highlight (line starting with >) code = code.replace(/^(>\s*\d+\s*\|)(.*$)/gm, '<span style="background: rgba(248, 81, 73, 0.1); display: block; margin: 0 -12px; padding: 0 12px;"><span style="color: #f85149; font-weight: bold;">$1</span>$2</span>'); codeElement.innerHTML = code; }
/** * คัดลอกโค้ดไปยังคลิปบอร์ด */ copyCodeSnippet(snippetId) { const element = document.getElementById(snippetId); if (element) { const text = element.textContent; navigator.clipboard.writeText(text).then(() => { // แสดงการแจ้งเตือนสั้นๆ const copyBtn = element.parentElement.querySelector('.copy-code-btn'); const originalText = copyBtn.innerHTML; copyBtn.innerHTML = '<i class="fas fa-check"></i> คัดลอกแล้ว!'; copyBtn.style.color = '#10b981'; setTimeout(() => { copyBtn.innerHTML = originalText; copyBtn.style.color = '#9ca3af'; }, 2000); }).catch(err => { console.error('ไม่สามารถคัดลอกได้: ', err); }); } }
/** * ตั้งค่าระบบกรองปัญหา */ setupIssueFilters(issues) { const typeFilter = document.getElementById('typeFilter'); const severityFilter = document.getElementById('severityFilter');
if (typeFilter) { typeFilter.addEventListener('change', () => { this.filterIssues(issues); }); }
if (severityFilter) { severityFilter.addEventListener('change', () => { this.filterIssues(issues); }); } }
/** * กรองปัญหาตามเงื่อนไข */ filterIssues(allIssues) { const typeFilter = document.getElementById('typeFilter')?.value || 'all'; const severityFilter = document.getElementById('severityFilter')?.value || 'all';
let filteredIssues = allIssues;
if (typeFilter !== 'all') { filteredIssues = filteredIssues.filter(issue => issue.type === typeFilter); }
if (severityFilter !== 'all') { filteredIssues = filteredIssues.filter(issue => issue.severity === severityFilter); }
this.displayIssuesList(filteredIssues); }
/** * จัดการการ export ปัญหา */ async handleExportIssues() { if (!this.currentAnalysis) { this.writeln('\x1b[1;33m ไม่มีข้อมูลการวิเคราะห์สำหรับส่งออก\x1b[0m'); return; }
try { const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); const filename = `การวิเคราะห์โปรเจกต์-${timestamp}.json`; // ใช้ Electron dialog API เพื่อให้ผู้ใช้เลือกที่บันทึก if (window.electronAPI && window.electronAPI.dialog) { const result = await window.electronAPI.dialog.showSaveDialog({ defaultPath: filename, filters: [ { name: 'ไฟล์ JSON', extensions: ['json'] }, { name: 'ไฟล์ทั้งหมด', extensions: ['*'] } ] });
if (!result.canceled && result.filePath) { await window.electronAPI.file.write(result.filePath, JSON.stringify(this.currentAnalysis, null, 2)); this.writeln(`\x1b[1;32m ส่งออกการวิเคราะห์เรียบร้อย: ${result.filePath}\x1b[0m`); } else { this.writeln('\x1b[1;33m ยกเลิกการส่งออก\x1b[0m'); } } else { // Fallback: สร้างลิงก์ดาวน์โหลด const dataStr = JSON.stringify(this.currentAnalysis, null, 2); const dataBlob = new Blob([dataStr], {type:'application/json'}); const url = URL.createObjectURL(dataBlob); const link = document.createElement('a'); link.href = url; link.download = filename; link.click(); URL.revokeObjectURL(url); this.writeln(`\x1b[1;32m เริ่มดาวน์โหลดไฟล์: ${filename}\x1b[0m`); } } catch (error) { this.writeln(`\x1b[1;31m ข้อผิดพลาดในการส่งออก: ${error.message}\x1b[0m`); } }
setActiveTab(tab) { this.currentTab = tab; // อัปเดต tab buttons document.querySelectorAll('.tab-btn').forEach(btn => { btn.classList.toggle('active', btn.dataset.tab === tab); });
// อัปเดต tab content document.querySelectorAll('.tab-content').forEach(content => { content.classList.toggle('active', content.id === tab + 'Tab'); });
// โหลดข้อมูลเฉพาะ tab if (tab === 'workflows') { this.requestWorkflowsUpdate(); } }
// [เวอร์ชันใหม่] ฟังก์ชันสำหรับเขียน Log ที่เราควบคุมได้ 100% writeLog(logData) { if (!this.logViewer) return;
const timestamp = logData.timestamp ? new Date(logData.timestamp) : new Date(); const time = timestamp.toLocaleTimeString('th-TH', { hour12: false }); // สร้าง Element ใหม่สำหรับแต่ละบรรทัด Log const logLine = document.createElement('span'); logLine.className = `log-line log-${logData.type || 'info'}`; // สร้างข้อความ Log logLine.textContent = `[${time}] ${logData.message}\n`;
// เพิ่มบรรทัดใหม่ลงใน Log Viewer this.logViewer.appendChild(logLine);
// เลื่อนหน้าจอไปที่บรรทัดล่าสุดเสมอ this.logViewer.scrollTop = this.logViewer.scrollHeight; }
// Helper function เพื่อความง่ายในการแทนที่ terminal.writeln() writeln(message, type = 'info') { // ลบ ANSI color codes ออกจากข้อความ const cleanMessage = message.replace(/\x1b\[[0-9;]*m/g, ''); // แปลงสีจาก ANSI codes เป็นประเภท Log let messageType = type; if (message.includes('\x1b[1;32m')) messageType = 'success'; // เขียว else if (message.includes('\x1b[1;31m')) messageType = 'error'; // แดง else if (message.includes('\x1b[1;33m')) messageType = 'warning'; // เหลือง else if (message.includes('\x1b[1;36m')) messageType = 'debug'; // ฟ้า this.writeLog({ message: cleanMessage, type: messageType, timestamp: new Date().toISOString() }); }
// [เวอร์ชันใหม่] อัปเดต Event Listener ให้เรียกใช้ฟังก์ชันใหม่ startRealTimeUpdates() { if (window.electronAPI && window.electronAPI.onTerminalMessage) { window.electronAPI.onTerminalMessage((logData) => { // logData คือ { message, type, timestamp } ที่ส่งมาจาก Backend // เรียกใช้ฟังก์ชันเขียน Log ใหม่ของเราโดยตรง this.writeLog(logData); }); console.log(' Raw HTML Log listener enabled.'); } else { console.error(' Could not set up real-time log listener.'); } }
updateRunningWorkflows(workflowsData) { const container = document.getElementById('runningWorkflows'); if (!container) return; if (!workflowsData || workflowsData.length === 0) { container.innerHTML = ` <div class="no-selection"> <i class="fas fa-pause-circle"></i> <h3>ไม่มีเวิร์กโฟลว์ที่กำลังทำงาน</h3> <p>ใช้คำสั่ง <code>workflows</code> ในเทอร์มินัลเพื่อดูข้อมูลล่าสุด</p> </div> `; return; }
container.innerHTML = ''; workflowsData.forEach(workflow => { const workflowElement = this.createWorkflowElement(workflow); container.appendChild(workflowElement); }); }
createWorkflowElement(workflow) { const div = document.createElement('div'); div.className = 'workflow-item'; const statusClass = `status-${workflow.status}`; const progress = workflow.completedNodes || 0; const total = workflow.totalNodes || 0; const percentage = total > 0 ? Math.round((progress / total) * 100) : 0;
div.innerHTML = ` <div class="workflow-header"> <span class="workflow-name">${workflow.name}</span> <span class="workflow-status ${statusClass}">${workflow.status}</span> </div> <div class="workflow-progress"> <span>${progress}/${total} nodes</span> <span>${percentage}% complete</span> </div> `;
return div; }
updateWorkflowsTab(workflowsData) { this.updateRunningWorkflows(workflowsData); }
formatUptime(seconds) { const hours = Math.floor(seconds / 3600); const minutes = Math.floor((seconds % 3600) / 60); const secs = Math.floor(seconds % 60); if (hours > 0) { return `${hours}h ${minutes}m ${secs}s`; } else if (minutes > 0) { return `${minutes}m ${secs}s`; } else { return `${secs}s`; } }
async requestWorkflowsUpdate() { try { if (window.electronAPI && window.electronAPI.diagnostics) { const workflows = await window.electronAPI.diagnostics.getWorkflows(); this.updateRunningWorkflows(workflows); } } catch (error) { console.error('ไม่สามารถดึงข้อมูล workflows ได้:', error); } }}
// เริ่มต้น Dashboard เมื่อ DOM พร้อมdocument.addEventListener('DOMContentLoaded', () => { window.diagnosticDashboard = new DiagnosticDashboard();});
// Export สำหรับใช้ใน consolewindow.DiagnosticDashboard = DiagnosticDashboard; 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273const fs = require('fs');const path = require('path');const crypto = require('crypto');
// รายชื่อไฟล์ที่สำคัญที่เราไม่ต้องการให้ใครแก้ไขconst criticalFiles = [ 'main.js', 'preload.js', 'validation_gateway.js', 'generate-manifests.js', 'modules/error-handler.js', 'modules/security-logger.js', 'modules/system-detector.js', 'modules/button-generator.js', 'modules/plugin-manager.js', 'modules/executor.js', 'modules/context-manager.js'];
const checksums = {};
console.log(' Generating checksums for critical files...');
criticalFiles.forEach(filePath => { try { const fullPath = path.join(__dirname, filePath); if (fs.existsSync(fullPath)) { const fileContent = fs.readFileSync(fullPath); const hash = crypto.createHash('sha256').update(fileContent).digest('hex'); checksums[filePath] = hash; console.log(` ${filePath} -> ${hash.substring(0, 20)}...`); } else { console.error(` ERROR: File not found at ${fullPath}`); } } catch (error) { console.error(` ERROR: Could not process file ${filePath}: ${error.message}`); }});
// เขียนผลลัพธ์ลงในไฟล์ checksums.jsonconst checksumsJson = JSON.stringify(checksums, null, 2);fs.writeFileSync(path.join(__dirname, 'checksums.json'), checksumsJson);
console.log('\n Checksums generated and saved to checksums.json');
// ส่วนที่เพิ่มเข้ามา: สร้าง Signature try { const privateKeyPath = path.join(__dirname, 'private_key.pem'); if (!fs.existsSync(privateKeyPath)) { console.error('\n FATAL ERROR: private_key.pem not found!'); console.error(' Please run "node generate-keys.js" first to generate key pair.'); console.error(' Or ensure private_key.pem is in the project root directory.'); process.exit(1); } const privateKey = fs.readFileSync(privateKeyPath, 'utf8'); const signer = crypto.createSign('sha256'); signer.update(checksumsJson); signer.end(); const signature = signer.sign(privateKey, 'hex'); fs.writeFileSync(path.join(__dirname, 'checksums.sig'), signature); console.log(' Checksums successfully signed -> checksums.sig'); console.log(' Signature:', signature.substring(0, 40) + '...'); } catch (error) { console.error('\n FATAL ERROR: Could not sign checksums:', error.message); console.error(' Please ensure private_key.pem is valid and accessible.'); console.error(' You may need to regenerate keys by running "node generate-keys.js"'); process.exit(1);} 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124// generate-manifests.js (v2 - Final)const fs = require('fs');const path = require('path');const SystemDetector = require('./modules/system-detector.js');
// รับ pluginsDir เป็นพารามิเตอร์async function generateManifests(pluginsDir) { console.log(' Starting Intelligent Manifest Generator...'); console.log(` Scanning target directory: ${pluginsDir}`); // Log path ที่ได้รับมา const systemDetector = new SystemDetector();
if (!fs.existsSync(pluginsDir)) { console.error(' Plugins directory not found.'); return; }
const items = fs.readdirSync(pluginsDir, { withFileTypes: true }); let generated = 0, skipped = 0;
for (const item of items) { if (!item.isDirectory() || item.name.startsWith('.')) continue;
const projectPath = path.join(pluginsDir, item.name); const manifestPath = path.join(projectPath, 'chahua.json');
if (fs.existsSync(manifestPath)) { console.log(`- Skipping ${item.name}: Manifest already exists.`); skipped++; continue; }
console.log(`+ Analyzing ${item.name}...`); try { const detectionResult = await systemDetector.detect(projectPath); const { type, confidence } = detectionResult;
const manifestData = { name: item.name.replace(/_/g, ' ').replace(/[.-]/g, ' '), description: `Auto-generated manifest for ${type} project.`, type: type, icon: getIconForType(type), buttons: generateButtonsForType(type, projectPath, item.name), publisher: 'Chahua Development Thailand' // เพิ่มบรรทัดนี้ };
fs.writeFileSync(manifestPath, JSON.stringify(manifestData, null, 2)); console.log(` -> Successfully generated chahua.json for [${type}] project: ${item.name}`); generated++; } catch (error) { console.error(` -> Failed to analyze ${item.name}: ${error.message}`); } } console.log(`\n Manifest generation complete! (${generated} generated, ${skipped} skipped)`);}
function getIconForType(projectType) { const icons = { 'node': '', 'python': '', 'batch_project': '', 'executable_project': '', 'standalone_js': '', 'html': '' }; return icons[projectType] || '';}
function generateButtonsForType(projectType, projectPath, folderName) { const buttons = []; const rootFiles = fs.readdirSync(projectPath).map(f => f.toLowerCase());
switch (projectType) { case 'node': const pkgPath = path.join(projectPath, 'package.json'); try { const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8')); buttons.push({ id: 'install', name: 'Install', command: 'npm install', icon: '' }); if (pkg.scripts?.start) buttons.push({ id: 'start', name: 'Start', command: 'npm start', icon: '' }); // ลบปุ่ม Dev ออก: if (pkg.scripts?.dev) buttons.push({ id: 'dev', name: 'Dev', command: 'npm run dev', icon: '' }); } catch { console.warn(`Could not parse package.json for ${folderName}`); } break;
case 'batch_project': const batFile = rootFiles.find(f => f === `${folderName.toLowerCase()}.bat`) || rootFiles.find(f => f.endsWith('.bat')); if (batFile) { buttons.push({ id: 'run-batch', name: 'Run Script', command: 'run-batch', icon: '' }); buttons.push({ id: 'edit-batch', name: 'Edit Script', command: 'edit-batch', icon: '' }); } break;
case 'executable_project': const exeFile = rootFiles.find(f => f === `${folderName.toLowerCase()}.exe`) || rootFiles.find(f => f.endsWith('.exe')); if (exeFile) { buttons.push({ id: 'launch-exe', name: 'Launch App', command: 'launch-exe', icon: '' }); buttons.push({ id: 'run-as-admin', name: 'Run as Admin', command: 'run-as-admin', icon: '' }); } break; case 'python': if (rootFiles.includes('requirements.txt')) { buttons.push({ id: 'pip-install', name: 'Install', command: 'pip install -r requirements.txt', icon: '' }); } const pyFile = ['app.py', 'main.py'].find(f => rootFiles.includes(f)) || rootFiles.find(f => f.endsWith('.py')); if (pyFile) { buttons.push({ id: 'run-python', name: 'Run', command: `python ${pyFile}`, icon: '' }); } break;
case 'standalone_js': const jsFile = rootFiles.find(f => f.endsWith('.js')); if (jsFile) { buttons.push({ id: 'run-js', name: 'Run Script', command: `node ${jsFile}`, icon: '' }); } break; }
buttons.push({ id: 'open-folder', name: 'Open Folder', command: 'open_explorer', icon: '' }); return buttons;}
// Export the function for use in other modules (e.g., main.js)module.exports = { generateManifests };
if (require.main === module) { // เมื่อรันโดยตรง ให้ใช้ path แบบเดิม (สำหรับ development) const pluginsDir = path.join(__dirname, 'plugins'); generateManifests(pluginsDir).catch(console.error);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242{ "ApiTraceDebugger.js": { "x": 0, "y": 0 }, "auth-dialog.js": { "x": 280, "y": 0 }, "backend/utils/inspector-worker.js": { "x": 560, "y": 0 }, "backend/utils/project-inspector.js": { "x": 840, "y": 0 }, "backend/utils/project-inspector-ipc.js": { "x": 1120, "y": 0 }, "checksums.json": { "x": 1400, "y": 0 }, "config/default.json": { "x": 1680, "y": 0 }, "config/obfuscator.config.js": { "x": 1960, "y": 0 }, "config/production.json": { "x": 2240, "y": 0 }, "debug-manager.js": { "x": 2520, "y": 0 }, "debugger.html": { "x": 0, "y": 130 }, "debugger.js": { "x": 280, "y": 130 }, "generate-checksums.js": { "x": 560, "y": 130 }, "generate-manifests.js": { "x": 840, "y": 130 }, "modules/system-detector.js": { "x": 1120, "y": 130 }, "index.html": { "x": 1400, "y": 130 }, "main.js": { "x": 1680, "y": 130 }, "validation_gateway.js": { "x": 1960, "y": 130 }, "modules/tamper-detector.js": { "x": 2240, "y": 130 }, "utils/project-inspector.js": { "x": 2520, "y": 130 }, "strategies/NodeStrategy.js": { "x": 0, "y": 260 }, "modules/button-generator.js": { "x": 280, "y": 260 }, "modules/cache-manager.js": { "x": 560, "y": 260 }, "modules/callback-hub.js": { "x": 840, "y": 260 }, "modules/callback-logger.js": { "x": 1120, "y": 260 }, "modules/cli.js": { "x": 1400, "y": 260 }, "modules/validation_gateway.js": { "x": 1680, "y": 260 }, "modules/modules/context-manager.js": { "x": 1960, "y": 260 }, "modules/modules/error-handler.js": { "x": 2240, "y": 260 }, "modules/modules/executor.js": { "x": 2520, "y": 260 }, "modules/modules/system-detector.js": { "x": 0, "y": 390 }, "modules/modules/plugin-manager.js": { "x": 280, "y": 390 }, "modules/context-manager.js": { "x": 560, "y": 390 }, "modules/error-handler.js": { "x": 840, "y": 390 }, "modules/executor.js": { "x": 1120, "y": 390 }, "modules/health-monitor.js": { "x": 1400, "y": 390 }, "modules/key-system.js": { "x": 1680, "y": 390 }, "modules/plugin-manager.js": { "x": 1960, "y": 390 }, "modules/retry-controller.js": { "x": 2240, "y": 390 }, "modules/rollback-manager.js": { "x": 2520, "y": 390 }, "modules/security-logger.js": { "x": 0, "y": 520 }, "modules/svg-icons.js": { "x": 280, "y": 520 }, "strategies/PythonStrategy.js": { "x": 560, "y": 520 }, "strategies/JavaStrategy.js": { "x": 840, "y": 520 }, "strategies/ApiStrategy.js": { "x": 1120, "y": 520 }, "package-lock.json": { "x": 1400, "y": 520 }, "package.json": { "x": 1680, "y": 520 }, "packages/@chahuadev/framework/index.js": { "x": 1960, "y": 520 }, "packages/@chahuadev/framework/install.js": { "x": 2240, "y": 520 }, "packages/@chahuadev/framework/package-lock.json": { "x": 2520, "y": 520 }, "packages/@chahuadev/framework/package.json": { "x": 0, "y": 650 }, "playwright.config.js": { "x": 280, "y": 650 }, "preload-webview.js": { "x": 560, "y": 650 }, "preload.js": { "x": 840, "y": 650 }, "scripts/copy-user-guides.js": { "x": 1120, "y": 650 }, "scripts/main.js": { "x": 1400, "y": 650 }, "scripts/project-manager.js": { "x": 1680, "y": 650 }, "scripts/secure-build.js": { "x": 1960, "y": 650 }, "scripts/setup-npm-token.js": { "x": 2240, "y": 650 }, "splash.html": { "x": 2520, "y": 650 }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464
const { app, BrowserWindow, ipcMain, dialog, Menu, shell } = require('electron'); // เพิ่ม Menu และ shellconst path = require('path');const fs = require('fs');const os = require('os'); // เพิ่ม osconst crypto = require('crypto'); // เพิ่ม cryptoconst https = require('https'); // เพิ่มสำหรับ OAuth Device Flowconst { spawn, exec } = require('child_process'); // เพิ่มสำหรับ manifest generator และ terminal
// Ignore dev flags in packaged builds so distributed binaries cannot be forced into dev mode.if (app.isPackaged) { process.argv = process.argv.filter(arg => arg !== '--dev-mode' && arg !== '--dev');}
// ======================================================================// ขั้นตอนที่ 1: เตรียมระบบติดตาม API (ไม่เริ่มทันที)// ======================================================================
// ตรวจสอบ Dev Mode ให้เร็วที่สุดconst isDevMode = !app.isPackaged || process.argv.includes('--dev-mode');console.log(` Developer Mode: ${isDevMode ? 'ENABLED' : 'DISABLED'} (${!app.isPackaged ? 'Development' : process.argv.includes('--dev-mode') ? '--dev-mode flag' : 'Production'})`);
// [COMMENTED] โหลด ApiTraceDebugger แต่ยังไม่เริ่มทำงาน (จะเริ่มใน app.whenReady())// [REASON] ออฟไลน์ Auth System ใช้อยู่แล้ว - คอมเมนท์ไว้ เผื่อต้องใช้ในอนาคต// const ApiTraceDebugger = require('./ApiTraceDebugger');// console.log('[API TRACE] ระบบติดตาม API พร้อมใช้งาน (จะเริ่มหลัง app.whenReady())');
// Stub ApiTraceDebugger เพื่อป้องกัน errorconst ApiTraceDebugger = { start: () => console.log('[API TRACE] (Disabled - using Offline Auth)'), stop: () => console.log('[API TRACE] (Disabled)')};
// ======================================================================// ขั้นตอนที่ 2: โหลดโมดูลอื่นๆ ของแอปพลิเคชันตามปกติ// ======================================================================// โมดูลเหล่านี้จะถูกโหลดก่อน แต่ยังไม่ได้ใช้งาน API มากนัก
// Direct Integration - ไม่ต้อง spawn app.js แล้ว!const ValidationGateway = require('./validation_gateway');// ========== FORT-KNOX LEVEL SECURITY SYSTEM ==========
// เพิ่ม Tamper Detectorconst TamperDetector = require('./modules/tamper-detector');
/** * OFFLINE DEMO AUTHENTICATION CLIENT (ปิด OAuth Device Flow ชั่วคราว) * สำหรับการทดสอบและการพัฒนาโดยไม่ต้องเชื่อมต่อ chahuadev.com */class OfflineAuthClient { constructor() { this.storagePath = path.join(os.homedir(), '.chahuadev', 'auth.json'); this.demoUsers = { 'admin': { username: 'admin', password: 'demo123', userId: 'usr_admin_001', email: 'admin@chahuadev.local', role: 'Administrator', avatar: '[ADMIN]', permissions: ['read', 'write', 'admin'] }, 'developer': { username: 'developer', password: 'demo123', userId: 'usr_dev_001', email: 'dev@chahuadev.local', role: 'Developer', avatar: '[DEV]', permissions: ['read', 'write'] }, 'user': { username: 'user', password: 'demo123', userId: 'usr_user_001', email: 'user@chahuadev.local', role: 'User', avatar: '[USER]', permissions: ['read'] } };
this.ensureStorageDirectory(); console.log('[OFFLINE AUTH] [SUCCESS] OFFLINE AUTH MODE (เดโมสำหรับการพัฒนา) - ไม่ต้องเชื่อมต่อ chahuadev.com'); }
/** * สร้าง directory สำหรับเก็บข้อมูล authentication */ ensureStorageDirectory() { const dir = path.dirname(this.storagePath); if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); } }
/** * OFFLINE: เริ่มต้นการล็อคอินแบบออฟไลน์ (จำลองแบบ Device Flow) */ async startDeviceFlow() { console.log(' [OFFLINE AUTH] Device Flow simulation started'); // จำลองการสร้าง device code const deviceCode = 'OFFLINE-' + crypto.randomBytes(16).toString('hex').toUpperCase(); const userCode = 'DEMO-' + Math.random().toString(36).substring(2, 8).toUpperCase();
const mockResponse = { success: true, deviceCode: deviceCode, userCode: userCode, expiresIn: 600, interval: 5, message: ' กรุณาป้อน User Code: ' + userCode, instruction: 'ใช้ชื่อผู้ใช้: admin/developer/user พร้อม password: demo123' };
console.log(' [OFFLINE AUTH] Mock Device Code:', deviceCode); console.log(' [OFFLINE AUTH] Mock User Code:', userCode);
return mockResponse; }
/** * OFFLINE: การยืนยันการล็อคอินแบบออฟไลน์ */ async authenticateOffline(username, password) { console.log(` [OFFLINE AUTH] Attempting login: ${username}`);
// ตรวจสอบ username และ password const user = this.demoUsers[username]; if (!user || user.password !== password) { console.error(' [OFFLINE AUTH] Invalid credentials'); return { success: false, error: 'ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง' }; }
// สร้าง mock tokens const mockTokens = { accessToken: 'mock_access_' + crypto.randomBytes(32).toString('hex'), refreshToken: 'mock_refresh_' + crypto.randomBytes(32).toString('hex'), expiresIn: 86400, // 24 hours user: { username: user.username, userId: user.userId, email: user.email, role: user.role, avatar: user.avatar, permissions: user.permissions }, authenticated: true, authenticatedAt: new Date().toISOString() };
// บันทึก tokens await this.saveTokens(mockTokens);
console.log(' [OFFLINE AUTH] Login successful:', user.username); return { success: true, status: 'approved', data: mockTokens }; }
/** * OFFLINE: จำลอง polling device status */ async pollDeviceStatus(deviceCode) { console.log(' [OFFLINE AUTH] Polling device status (offline mode)'); // ในโหมดออฟไลน์ เราจะรีเทิร์นสถานะรอการยืนยัน return { success: true, status: 'pending', message: 'รอการใส่ชื่อผู้ใช้และรหัสผ่าน' }; }
/** * บันทึก tokens ลงไฟล์ */ async saveTokens(tokens) { try { const authData = { accessToken: tokens.accessToken, refreshToken: tokens.refreshToken, expiresAt: Date.now() + (tokens.expiresIn * 1000), user: tokens.user, savedAt: new Date().toISOString(), authMode: 'offline-demo' };
fs.writeFileSync(this.storagePath, JSON.stringify(authData, null, 2), 'utf8'); console.log(' [OFFLINE AUTH] Tokens saved:', this.storagePath); return { success: true }; } catch (error) { console.error(' [OFFLINE AUTH] Failed to save tokens:', error); return { success: false, error: error.message }; } }
/** * โหลด tokens จากไฟล์ */ async loadTokens() { try { if (!fs.existsSync(this.storagePath)) { return { success: false, error: 'No saved tokens found' }; }
const authData = JSON.parse(fs.readFileSync(this.storagePath, 'utf8'));
// ตรวจสอบว่า token หมดอายุหรือไม่ if (authData.expiresAt && Date.now() > authData.expiresAt) { console.log(' [OFFLINE AUTH] Token expired'); return { success: false, error: 'Token expired' }; }
console.log(' [OFFLINE AUTH] Tokens loaded:', authData.user.username); return { success: true, data: authData }; } catch (error) { console.error(' [OFFLINE AUTH] Failed to load tokens:', error); return { success: false, error: error.message }; } }
/** * ลบ tokens (logout) */ async removeTokens() { try { if (fs.existsSync(this.storagePath)) { fs.unlinkSync(this.storagePath); } console.log(' [OFFLINE AUTH] Logged out successfully'); return { success: true }; } catch (error) { console.error(' [OFFLINE AUTH] Failed to remove tokens:', error); return { success: false, error: error.message }; } }}
/** * Anti-Debugging Protection System * ป้องกันการใช้เครื่องมือดีบักและ reverse engineering */class AntiDebuggingSystem { constructor() { this.checkInterval = null; // ปรับปรุงการตรวจสอบ developer mode ให้ครอบคลุมมากขึ้น this.isDevMode = this.detectDeveloperMode(); this.suspiciousActivityCount = 0; this.maxSuspiciousActivity = 3;
// เริ่มต้นระบบตรวจจับการแก้ไข this.tamperDetector = new TamperDetector();
console.log(this.isDevMode ? ' Anti-Debugging: Development mode detected' : ' Anti-Debugging: Production mode active'); }
/** * ระบบตรวจสอบ Developer Mode ที่ครอบคลุม * ตรวจสอบจากหลายแหล่งเพื่อความแม่นยำ */ detectDeveloperMode() { const indicators = { // 1. Process arguments hasDevArgs: process.argv.includes('--dev-mode') || process.argv.includes('--dev'),
// 2. Application packaging status isUnpackaged: !app.isPackaged,
// 3. Environment variables hasDevEnv: process.env.NODE_ENV === 'development' || process.env.CHAHUA_DEV === 'true',
// 4. Development port detection hasDevPort: process.env.PORT && (process.env.PORT === '3000' || process.env.PORT === '8080'),
// 5. Debug mode flags hasDebugFlag: process.execArgv.some(arg => arg.includes('--inspect') || arg.includes('--debug')),
// 6. Development dependencies hasDevDeps: false // จะตรวจสอบเพิ่มเติมใน package.json ถ้าจำเป็น };
// Log detection results for debugging console.log(' Developer Mode Detection Results:', indicators);
// Return true if any indicator suggests development mode return Object.values(indicators).some(Boolean); }
/** * เริ่มระบบป้องกันการดีบัก */ start(mainWindow) { if (this.isDevMode) { console.log(' Anti-Debugging: Disabled in development mode'); return; }
console.log(' Starting Anti-Debugging protection...'); this.mainWindow = mainWindow;
// เริ่มระบบตรวจจับการแก้ไขไฟล์ this.tamperDetector.startMonitoring();
// ตรวจสอบทุกๆ 2 วินาที this.checkInterval = setInterval(() => { this.performSecurityChecks(); }, 2000);
// ตรวจสอบ DevTools events if (mainWindow && mainWindow.webContents) { mainWindow.webContents.on('devtools-opened', () => { this.handleSuspiciousActivity('DevTools opened'); });
mainWindow.webContents.on('devtools-focused', () => { this.handleSuspiciousActivity('DevTools focused'); }); } }
/** * ทำการตรวจสอบความปลอดภัย */ performSecurityChecks() { try { // ตรวจสอบ DevTools if (this.mainWindow && this.mainWindow.webContents && this.mainWindow.webContents.isDevToolsOpened()) { this.handleSuspiciousActivity('DevTools detected as open'); return; }
// ตรวจสอบ debugging tools ใน process list (Windows) if (process.platform === 'win32') { this.checkForDebuggingProcesses(); }
// ตรวจสอบ performance timing anomalies (อาจมี debugger ทำให้ช้า) this.checkPerformanceAnomalies();
} catch (error) { console.warn(' Anti-Debugging check error:', error.message); } }
/** * ตรวจสอบ process ที่น่าสงสัย */ checkForDebuggingProcesses() { const suspiciousProcesses = [ 'cheatengine', 'x64dbg', 'x32dbg', 'ollydbg', 'windbg', 'processhacker', 'pestudio', 'ida64', 'ida32', 'ghidra' ];
// ใช้ tasklist command เพื่อดู running processes exec('tasklist', (error, stdout) => { if (error) return;
const runningProcesses = stdout.toLowerCase(); for (const suspiciousProcess of suspiciousProcesses) { if (runningProcesses.includes(suspiciousProcess)) { this.handleSuspiciousActivity(`Debugging tool detected: ${suspiciousProcess}`); return; } } }); }
/** * ตรวจสอบ performance anomalies */ checkPerformanceAnomalies() { const start = Date.now();
// สร้าง simple computation let sum = 0; for (let i = 0; i < 10000; i++) { sum += Math.random(); }
const duration = Date.now() - start;
// ถ้าใช้เวลานานกว่าปกติมาก อาจมี debugger if (duration > 100) { // ปกติควรใช้เวลาไม่เกิน 10-20ms this.handleSuspiciousActivity(`Performance anomaly detected: ${duration}ms`); } }
/** * จัดการเมื่อพบกิจกรรมน่าสงสัย */ handleSuspiciousActivity(reason) { this.suspiciousActivityCount++; console.warn(` Security Alert [${this.suspiciousActivityCount}/${this.maxSuspiciousActivity}]: ${reason}`);
if (this.suspiciousActivityCount >= this.maxSuspiciousActivity) { console.error(' Security breach detected! Shutting down application...');
// แสดง warning dialog ก่อนปิด if (this.mainWindow) { dialog.showErrorBox( 'Security Alert', 'Security violation detected. Application will now close for protection.' ); }
// ปิดแอปทันที process.exit(1); } }
/** * หยุดระบบป้องกัน */ stop() { if (this.checkInterval) { clearInterval(this.checkInterval); this.checkInterval = null; console.log(' Anti-Debugging protection stopped'); }
// หยุดระบบตรวจจับการแก้ไข if (this.tamperDetector) { this.tamperDetector.stopMonitoring(); } }}
/** * IPC Command Sanitization System * ป้องกันการโจมตีแบบ Command Injection ผ่าน IPC */class IPCSecuritySystem { constructor() { // รายการคำสั่งที่อนุญาตให้รันผ่าน child_process this.allowedCommands = new Set([ 'node', 'npm', 'git', 'where', 'which', 'echo', 'dir', 'ls', 'cd', 'pwd', 'whoami', 'hostname', 'ipconfig', 'ping', 'powershell', // สำหรับ Run as Admin 'explorer' // สำหรับ Open Folder ]);
// Pattern ที่อันตราย this.dangerousPatterns = [ /rm\s+-rf/i, // ลบไฟล์ /del\s+\/[sq]/i, // Windows delete /format\s+[cd]:/i, // Format drive /shutdown/i, // Shutdown /reboot/i, // Reboot />\s*nul/i, // Redirect อันตราย /`[^`]*`/, // Command substitution /\$\([^)]*\)/, // Command substitution /eval\s*\(/i, // Eval /exec\s*\(/i // Exec ];
console.log(' IPC Security System initialized'); }
/** * ตรวจสอบและทำความสะอาดคำสั่ง */ sanitizeCommand(command, options = {}) { if (!command || typeof command !== 'string') { throw new Error('Invalid command: Command must be a non-empty string'); }
const trimmedCommand = command.trim();
// เพิ่ม: ยกเว้นสำหรับ powershell ที่มี -Command และ Start-Process (ปลอดภัยสำหรับ Run as Admin) if (trimmedCommand.startsWith('powershell -Command "Start-Process')) { console.log(' Allowed safe powershell command for admin mode'); return { original: command, sanitized: trimmedCommand, baseCommand: 'powershell', isAllowed: true }; }
// ตรวจสอบ dangerous patterns for (const pattern of this.dangerousPatterns) { if (pattern.test(trimmedCommand)) { throw new Error(`Dangerous command pattern detected: ${pattern.source}`); } }
// แยกคำสั่งหลักออกมา const commandParts = trimmedCommand.split(/\s+/); const baseCommand = commandParts[0].toLowerCase();
// ตรวจสอบว่าคำสั่งหลักอยู่ใน whitelist หรือไม่ if (!this.allowedCommands.has(baseCommand)) { throw new Error(`Command not allowed: ${baseCommand}`); }
// ตรวจสอบ path traversal if (trimmedCommand.includes('../') || trimmedCommand.includes('..\\')) { throw new Error('Path traversal detected in command'); }
// จำกัดความยาวคำสั่ง if (trimmedCommand.length > 500) { throw new Error('Command too long (max 500 characters)'); }
console.log(` Command sanitized: ${baseCommand}`); return { original: command, sanitized: trimmedCommand, baseCommand: baseCommand, isAllowed: true }; }
/** * เพิ่มคำสั่งที่อนุญาต */ addAllowedCommand(command) { this.allowedCommands.add(command.toLowerCase()); console.log(` Added allowed command: ${command}`); }
/** * ลบคำสั่งที่อนุญาต */ removeAllowedCommand(command) { this.allowedCommands.delete(command.toLowerCase()); console.log(` Removed allowed command: ${command}`); }
/** * ดูรายการคำสั่งที่อนุญาต */ getAllowedCommands() { return Array.from(this.allowedCommands); }}
// สร้าง instance ของระบบป้องกันconst antiDebugging = new AntiDebuggingSystem();const ipcSecurity = new IPCSecuritySystem();
// Import generate-manifests function for production buildsconst { generateManifests } = require('./generate-manifests.js');
// ฟังก์ชันตรวจสอบ Digital Signature และ Integrityfunction checkAppIntegrity() { console.log(' Verifying application integrity & signature...');
// ข้าม checksum verification ในโหมด development if (!app.isPackaged || process.argv.includes('--dev-mode')) { console.log(' Development mode detected - skipping checksum verification'); return true; }
try { // --- 1. อ่านไฟล์ทั้งหมดที่จำเป็น --- // Security files are now stored inside ASAR for better protection let checksumsPath, signaturePath, publicKeyPath;
if (app.isPackaged) { // Production: อ่านจากใน ASAR (ปลอดภัย) checksumsPath = path.join(__dirname, 'checksums.json'); signaturePath = path.join(__dirname, 'checksums.sig'); publicKeyPath = path.join(__dirname, 'public_key.pem'); console.log(' Production mode: Reading security files from ASAR'); } else { // Development: อ่านจาก project root checksumsPath = path.join(__dirname, 'checksums.json'); signaturePath = path.join(__dirname, 'checksums.sig'); publicKeyPath = path.join(__dirname, 'public_key.pem'); console.log(' Development mode: Reading security files from project root'); }
// ตรวจสอบว่าไฟล์ security มีอยู่หรือไม่ if (!fs.existsSync(checksumsPath) || !fs.existsSync(signaturePath) || !fs.existsSync(publicKeyPath)) { console.log(' Security files not found - skipping integrity check (Development mode?)'); return true; // ในโหมดพัฒนาหรือไม่มีไฟล์ security ให้ผ่าน }
const storedChecksumsJson = fs.readFileSync(checksumsPath, 'utf8'); const signature = fs.readFileSync(signaturePath, 'utf8'); const publicKey = fs.readFileSync(publicKeyPath, 'utf8');
// --- 2. ตรวจสอบลายเซ็นก่อน (Verify Signature) --- const verifier = crypto.createVerify('sha256'); verifier.update(storedChecksumsJson); verifier.end();
if (!verifier.verify(publicKey, signature, 'hex')) { // ถ้าลายเซ็นไม่ถูกต้อง แสดงว่า checksums.json ถูกแก้ไข! dialog.showErrorBox('Security Alert', 'Checksum file signature is invalid. The application has been tampered with.'); return false; } console.log(' Signature verification passed.');
// --- 3. ถ้าลายเซ็นถูกต้อง ค่อยตรวจสอบ Integrity ของไฟล์ --- const storedChecksums = JSON.parse(storedChecksumsJson);
for (const filePath in storedChecksums) { const fullPath = path.join(__dirname, filePath); if (!fs.existsSync(fullPath)) { console.log(` Security file missing: ${filePath} - skipping check`); continue; // ข้ามไฟล์ที่ไม่มี แทนที่จะ error }
const fileContent = fs.readFileSync(fullPath); const currentHash = crypto.createHash('sha256').update(fileContent).digest('hex');
if (currentHash !== storedChecksums[filePath]) { // ถ้า Hash ไม่ตรงกัน แสดงว่าไฟล์ถูกแก้ไข! dialog.showErrorBox('Security Alert', `File tampering detected: ${filePath}. The program will now exit.`); return false; } }
console.log(' All file integrity checks passed.'); return true;
} catch (error) { console.error(' Security check error:', error.message); // ในกรณีที่เกิดข้อผิดพลาดในการตรวจสอบ ให้ผ่านในโหมดพัฒนา if (!app.isPackaged) { console.log(' Development mode: Skipping security check due to error'); return true; } dialog.showErrorBox('Fatal Error', `A critical error occurred during security check: ${error.message}`); return false; }}
const isPackaged = app.isPackaged;
// เก็บ isDev ไว้เพื่อ backward compatibilityconst isDev = isDevMode;
// Build Dashboard - เฉพาะโหมดพัฒนา (Removed - Use builder.html separately)
// ฟังก์ชันสำหรับหาตำแหน่ง node.exe และ npm-cli.js ที่ถูกต้อง (เวอร์ชันอัปเดต)function getBundledNpmPaths() { if (isPackaged) { // เมื่อ Pack แอปแล้ว: ชี้ไปที่ไฟล์ที่เราฝังไว้ใน resources const nodeDir = path.join(process.resourcesPath, 'node'); return { nodePath: path.join(nodeDir, 'node.exe'), npmCliPath: path.join(nodeDir, 'node_modules', 'npm', 'bin', 'npm-cli.js') }; } else { // ตอนพัฒนา: ใช้ npm ของเครื่องตามปกติ return { nodePath: 'node', // ใช้ node ของระบบ npmCliPath: 'npm' // ใช้ npm ของระบบ (วิธีนี้จะเปลี่ยนไปเล็กน้อย) }; }}
let mainWindow;// [CLEANED] Removed authentication window variables and functionslet splashWindow; // เพิ่มตัวแปรสำหรับ splash windowlet debugWindow; // เพิ่มตัวแปรสำหรับ debug window
// --- CMD Logger สำหรับแสดงผล Log ใน CMD Window --- const cmdLogger = { info: (message, ...args) => { // แสดงผลข้อความเป็นสีเขียวใน CMD console.log('\x1b[32m%s\x1b[0m', `[INFO] ${message}`, ...args); }, warn: (message, ...args) => { // แสดงผลข้อความเป็นสีเหลือง console.warn('\x1b[33m%s\x1b[0m', `[WARN] ${message}`, ...args); }, error: (message, ...args) => { // แสดงผลข้อความเป็นสีแดง console.error('\x1b[31m%s\x1b[0m', `[ERROR] ${message}`, ...args); }, debug: (message, ...args) => { // แสดงผลเฉพาะใน Dev Mode const isDevMode = process.argv.includes('--dev-mode') || process.argv.includes('--dev') || !app.isPackaged; if (isDevMode) { console.log('\x1b[36m%s\x1b[0m', `[DEBUG] ${message}`, ...args); } }};
// Initialize Core Components - Simplified for ValidationGateway-centric architectureconst validationGateway = new ValidationGateway();
// ASAR-Safe Path Helper Functionsfunction getAppBasePath() { if (app.isPackaged) { // Production: ใช้ path ข้างนอก app.asar return path.dirname(app.getPath('exe')); } else { // Development: ใช้ __dirname ปกติ return __dirname; }}
function getUnpackedPath(relativePath) { if (app.isPackaged) { // Production: ไฟล์ที่ unpack อยู่ใน app.asar.unpacked const appPath = app.getAppPath(); return path.join(path.dirname(appPath), 'app.asar.unpacked', relativePath); } else { // Development: ใช้ path ปกติ return path.join(__dirname, relativePath); }}
function getResourcePath(relativePath) { if (app.isPackaged) { // Production: resources อยู่ใน app.asar (สำหรับไฟล์ที่ไม่ต้อง unpack) return path.join(app.getAppPath(), relativePath); } else { // Development: ใช้ path ปกติ return path.join(__dirname, relativePath); }}
// Create splash screen window firstfunction createSplashWindow() { // เส้นทางไฟล์ที่ถูกต้องสำหรับ icon.png (extraFiles) const iconPath = isPackaged ? path.join(getAppBasePath(), 'icon.png') : getResourcePath('icon.png');
// เส้นทางไฟล์ที่ถูกต้องสำหรับ splash.html (extraFiles) const splashPath = isPackaged ? path.join(getAppBasePath(), 'splash.html') : path.join(__dirname, 'splash.html');
splashWindow = new BrowserWindow({ width: 600, height: 500, frame: false, alwaysOnTop: true, transparent: false, resizable: false, center: true, webPreferences: { nodeIntegration: false, contextIsolation: true }, icon: iconPath });
splashWindow.loadFile(splashPath);
splashWindow.show();
console.log(' Splash screen created and shown'); console.log(` Icon path: ${iconPath}`); console.log(` Splash path: ${splashPath}`);
// Close splash and create main window after loading completes setTimeout(() => { createMainWindow(); if (splashWindow && !splashWindow.isDestroyed()) { splashWindow.close(); splashWindow = null; console.log(' Splash closed, main window created'); } }, 4000); // Slightly longer to match progress animation
return splashWindow;}
function createMainWindow() { // เส้นทางไฟล์ที่ถูกต้องสำหรับ icon.png (extraFiles) const iconPath = isPackaged ? path.join(getAppBasePath(), 'icon.png') : getResourcePath('icon.png');
mainWindow = new BrowserWindow({ width: 1400, height: 900, minWidth: 800, minHeight: 600, title: 'Chahuadev Framework - Plugin Management System', icon: iconPath, autoHideMenuBar: true, webPreferences: { nodeIntegration: false, contextIsolation: true, enableRemoteModule: false, preload: getResourcePath('preload.js'), webSecurity: true, sandbox: true, webviewTag: true // เพิ่มบรรทัดนี้เพื่อเปิดใช้งาน <webview> }, show: false });
// Load the framework interface mainWindow.loadFile('app.html');
console.log(` Main window icon path: ${iconPath}`);
// Show when ready mainWindow.once('ready-to-show', () => { mainWindow.show(); console.log(' Chahuadev Framework Desktop App ready!');
// เริ่มระบบป้องกันการดีบัก (Fort-Knox Level Security) antiDebugging.start(mainWindow); });
// Handle window closed mainWindow.on('closed', () => { mainWindow = null; // หยุดระบบป้องกัน antiDebugging.stop(); // Cleanup all plugins cleanupAllPlugins(); });
// Development tools if (process.env.NODE_ENV === 'development') { mainWindow.webContents.openDevTools(); }}
// Build Dashboard Functions - เฉพาะโหมดพัฒนา (Removed - Use builder.html separately)
// Create Developer Menu - เฉพาะโหมดพัฒนาfunction createDeveloperMenu() { if (!isDevMode) return; // เฉพาะโหมดพัฒนาเท่านั้น
const mainMenu = Menu.buildFromTemplate([ { label: 'เครื่องมือนักพัฒนา', submenu: [ { role: 'toggleDevTools', label: 'เปิด/ปิด DevTools' }, { role: 'reload', label: 'โหลดใหม่' }, { role: 'forceReload', label: 'บังคับโหลดใหม่' }, { type: 'separator' } ] }, { label: 'มุมมอง', submenu: [ { role: 'resetZoom', label: 'รีเซ็ตการซูม' }, { role: 'zoomIn', label: 'ซูมเข้า' }, { role: 'zoomOut', label: 'ซูมออก' }, { type: 'separator' }, { role: 'togglefullscreen', label: 'เปิด/ปิดเต็มจอ' } ] } ]);
Menu.setApplicationMenu(mainMenu); console.log(' Developer menu created');}
// Cleanup All Plugins - Now handled by ValidationGatewayasync function cleanupAllPlugins() { console.log(' Cleaning up all plugins...'); try { // ValidationGateway will handle plugin cleanup console.log(' Plugin cleanup delegated to ValidationGateway'); } catch (error) { console.error(' Plugin cleanup failed:', error.message); }}
// ระบบ��รวจสอบ Runtime Integrity เป็นระยะๆlet runtimeIntegrityInterval = null;let integrityCheckCount = 0;const MAX_INTEGRITY_CHECKS = 10; // จำกัดจำนวนครั้งเพื่อไม่ให้กินทรัพยากรมากเกินไป
function startRuntimeIntegrityChecks() { // ข้ามในโหมดพัฒนา if (!app.isPackaged || process.argv.includes('--dev-mode')) { console.log(' Development mode: Skipping runtime integrity checks'); return; }
console.log(' Starting periodic runtime integrity checks...');
runtimeIntegrityInterval = setInterval(() => { integrityCheckCount++;
if (integrityCheckCount > MAX_INTEGRITY_CHECKS) { console.log(' Runtime integrity check limit reached, stopping periodic checks'); stopRuntimeIntegrityChecks(); return; }
console.log(` Runtime integrity check #${integrityCheckCount}...`);
try { // ตรวจสอบไฟล์สำคัญ const criticalFiles = [ 'main.js', 'preload.js', 'package.json' ];
const storedChecksumsPath = path.join(__dirname, 'checksums.json'); if (!fs.existsSync(storedChecksumsPath)) { console.log(' Checksums file not found for runtime check'); return; }
const storedChecksums = JSON.parse(fs.readFileSync(storedChecksumsPath, 'utf8'));
for (const fileName of criticalFiles) { if (!storedChecksums[fileName]) continue;
const filePath = path.join(__dirname, fileName); if (!fs.existsSync(filePath)) continue;
const fileContent = fs.readFileSync(filePath); const currentHash = crypto.createHash('sha256').update(fileContent).digest('hex');
if (currentHash !== storedChecksums[fileName]) { console.error(` RUNTIME TAMPERING DETECTED: ${fileName}`); handleRuntimeTampering(fileName); return; } }
console.log(` Runtime integrity check #${integrityCheckCount} passed`);
} catch (error) { console.warn(` Runtime integrity check #${integrityCheckCount} failed:`, error.message); }
}, 30000); // ตรวจสอบทุก 30 วินาที}
function stopRuntimeIntegrityChecks() { if (runtimeIntegrityInterval) { clearInterval(runtimeIntegrityInterval); runtimeIntegrityInterval = null; console.log(' Runtime integrity checks stopped'); }}
function handleRuntimeTampering(fileName) { console.error(` CRITICAL SECURITY ALERT: Runtime tampering detected in ${fileName}`);
// แสดงแจ้งเตือนและปิดโปรแกรม dialog.showErrorBox( 'Security Alert', `Runtime tampering detected in ${fileName}. The application will now exit for security reasons.` );
// ล็อกเหตุการณ์ const logEntry = { timestamp: new Date().toISOString(), event: 'RUNTIME_TAMPERING_DETECTED', file: fileName, checkNumber: integrityCheckCount };
try { const securityLogPath = path.join(app.getPath('userData'), 'security-events.log'); fs.appendFileSync(securityLogPath, JSON.stringify(logEntry) + '\n'); } catch (error) { console.error('Failed to log security event:', error); }
// ปิดโปรแกรมทันที app.quit();}
// เพิ่มฟังก์ชันตรวจสอบการเปลี่ยนแปลงในหน่วยความจำ (Memory Protection)function enableMemoryProtection() { // ข้ามในโหมดพัฒนา if (!app.isPackaged || process.argv.includes('--dev-mode')) { return; }
console.log(' Enabling memory protection...');
// ตรวจสอบการเปลี่ยนแปลง critical functions const originalFunctions = { require: typeof global.require === 'function' ? global.require.toString() : '', eval: typeof global.eval === 'function' ? global.eval.toString() : '', Function: typeof global.Function === 'function' ? global.Function.toString() : '' };
setInterval(() => { try { // ตรวจสอบว่า critical functions ถูกแก้ไขหรือไม่ const currentRequire = typeof global.require === 'function' ? global.require.toString() : ''; const currentEval = typeof global.eval === 'function' ? global.eval.toString() : ''; const currentFunction = typeof global.Function === 'function' ? global.Function.toString() : '';
if (originalFunctions.require && currentRequire !== originalFunctions.require || originalFunctions.eval && currentEval !== originalFunctions.eval || originalFunctions.Function && currentFunction !== originalFunctions.Function) {
console.error(' MEMORY TAMPERING DETECTED: Critical functions modified'); handleRuntimeTampering('critical-functions'); } } catch (error) { console.warn('Memory protection check failed:', error.message); } }, 60000); // ตรวจสอบทุก 1 นาที}
// Supply Chain Security - ตรวจสอบ Dependenciesasync function checkSupplyChainSecurity() { // ข้ามในโหมดพัฒนา if (!app.isPackaged || process.argv.includes('--dev-mode')) { console.log(' Development mode: Skipping supply chain security check'); return true; }
console.log(' Checking supply chain security...');
try { const packageJsonPath = path.join(__dirname, 'package.json'); const packageLockPath = path.join(__dirname, 'package-lock.json');
if (!fs.existsSync(packageJsonPath) || !fs.existsSync(packageLockPath)) { console.log(' Package files not found for supply chain check'); return true; }
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')); const packageLock = JSON.parse(fs.readFileSync(packageLockPath, 'utf8'));
// ตรวจสอบ Critical Dependencies const criticalDependencies = [ 'electron', 'express', 'crypto', 'fs-extra', 'archiver' ];
for (const dep of criticalDependencies) { if (packageJson.dependencies[dep]) { const installedVersion = packageLock.packages[`node_modules/${dep}`]?.version; if (!installedVersion) { console.warn(` Critical dependency ${dep} not found in package-lock.json`); continue; }
// ตรวจสอบ known vulnerabilities (simplified check) if (await checkKnownVulnerabilities(dep, installedVersion)) { console.error(` Known vulnerability detected in ${dep}@${installedVersion}`); return false; } } }
// ตรวจสอบ Package Integrity const lockFileHash = crypto.createHash('sha256') .update(fs.readFileSync(packageLockPath)) .digest('hex');
const expectedLockHashPath = path.join(__dirname, 'package-lock.hash'); if (fs.existsSync(expectedLockHashPath)) { const expectedHash = fs.readFileSync(expectedLockHashPath, 'utf8').trim(); if (lockFileHash !== expectedHash) { console.error(' Package-lock.json integrity check failed'); return false; } } else { // สร้าง hash file สำหรับครั้งแรก fs.writeFileSync(expectedLockHashPath, lockFileHash); console.log(' Created package-lock.hash for future integrity checks'); }
console.log(' Supply chain security check passed'); return true;
} catch (error) { console.error(' Supply chain security check failed:', error.message); return false; }}
// ตรวจสอบ known vulnerabilities (simplified implementation)async function checkKnownVulnerabilities(packageName, version) { // รายการ packages ที่มี known issues (อัปเดตตามความเป็นจริง) const knownVulnerablePackages = { 'electron': { '<28.0.0': 'CVE-2023-xxxxx' }, 'express': { '<4.18.0': 'CVE-2022-xxxxx' } // เพิ่มรายการตามความจำเป็น };
const vulnInfo = knownVulnerablePackages[packageName]; if (!vulnInfo) return false;
// ตรวจสอบเวอร์ชันที่มีปัญหา (simplified version comparison) for (const [vulnerableVersion, cve] of Object.entries(vulnInfo)) { if (vulnerableVersion.startsWith('<')) { const targetVersion = vulnerableVersion.slice(1); if (compareVersions(version, targetVersion) < 0) { console.error(` ${packageName}@${version} has ${cve}`); return true; } } }
return false;}
// เปรียบเทียบเวอร์ชัน (simplified)function compareVersions(version1, version2) { const v1parts = version1.split('.').map(Number); const v2parts = version2.split('.').map(Number);
for (let i = 0; i < Math.max(v1parts.length, v2parts.length); i++) { const v1part = v1parts[i] || 0; const v2part = v2parts[i] || 0;
if (v1part < v2part) return -1; if (v1part > v2part) return 1; }
return 0;}
// App event handlersapp.whenReady().then(async () => { console.log(' Electron app ready, performing security checks...');
// ขั้นตอนที่ 1: ตรวจสอบ Digital Signature และ Integrity ก่อน const integrityOk = checkAppIntegrity(); if (!integrityOk) { console.log(' App integrity check failed. Shutting down.'); app.quit(); return; }
// ขั้นตอนที่ 2: ตรวจสอบ Supply Chain Security const supplyChainOk = await checkSupplyChainSecurity(); if (!supplyChainOk) { console.log(' Supply chain security check failed. Shutting down.'); dialog.showErrorBox('Security Alert', 'Supply chain security check failed. Please contact support.'); app.quit(); return; }
// เริ่มระบบตรวจสอบ Runtime Integrity startRuntimeIntegrityChecks();
// เปิดใช้งาน Memory Protection enableMemoryProtection();
// เพิ่ม: เริ่มการทำงานของระบบดีบั๊กเฉพาะใน Dev Mode (ปิดชั่วคราว) if (isDevMode && false) { // ปิดชั่วคราวเพื่อแก้ปัญหาการค้าง try { ApiTraceDebugger.start(); console.log('[API TRACE] ระบบติดตาม API เริ่มทำงานแล้ว (Real-time Logging)'); } catch (error) { console.error('[API TRACE] ไม่สามารถเริ่มระบบติดตาม API ได้:', error.message); } } else if (isDevMode) { console.log('[API TRACE] ระบบติดตาม API ถูกปิดชั่วคราว (กำลังแก้ไขปัญหา)'); }
// ขั้นตอนที่ 3: Initialize Plugins via Gateway try { await validationGateway.initializePlugins(); console.log(' Plugins initialized via Gateway'); } catch (error) { console.warn(' Plugin initialization skipped:', error.message); }
// Auto-scan projects on startup try { await handleScanProjects(); console.log(' Auto project scan completed'); } catch (error) { console.warn(' Auto project scan failed:', error.message); }
// Create UI createSplashWindow();
// แก้ไขตรงนี้: เรียกใช้ createDeveloperMenu() เฉพาะใน Dev Mode if (isDevMode) { createDeveloperMenu(); } else { // ในโหมดผู้ใช้ ให้ตั้งค่าเมนูเป็น null เพื่อลบเมนูทั้งหมด Menu.setApplicationMenu(null); }
app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { createSplashWindow(); } });});
app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); }});
app.on('before-quit', async () => { console.log(' App shutting down...'); if (isDevMode) { ApiTraceDebugger.stop(); } await cleanupAllPlugins(); stopRuntimeIntegrityChecks();});
// IPC handlers for desktop app functionalityipcMain.handle('get-app-version', () => { return app.getVersion();});
// ========== OFFLINE DEMO AUTH IPC HANDLERS ==========
// สร้าง OfflineAuthClient instance (แทนที่ DeviceAuthClient)let offlineAuthClient = null;
/** * Initialize Offline Auth Client */function getOfflineAuthClient() { if (!offlineAuthClient) { offlineAuthClient = new OfflineAuthClient(); } return offlineAuthClient;}
/** * IPC Handler: เริ่มต้น Offline Auth (Dashboard) */ipcMain.handle('auth:start-device-flow', async () => { try { console.log(' [OFFLINE AUTH] Initializing demo auth screen...'); const client = getOfflineAuthClient(); const result = await client.startDeviceFlow();
return { success: true, data: result }; } catch (error) { console.error(' [OFFLINE AUTH] Failed to initialize:', error); return { success: false, error: error.message }; }});
/** * IPC Handler: Offline Authentication (ล็อคอินแบบออฟไลน์) */ipcMain.handle('auth:offline-login', async (event, { username, password }) => { try { if (!username || !password) { throw new Error('ชื่อผู้ใช้และรหัสผ่านจำเป็น'); }
const client = getOfflineAuthClient(); const result = await client.authenticateOffline(username, password);
if (result.success && result.data) { console.log(' [OFFLINE AUTH] User authenticated successfully');
// Inject tokens to webview try { await injectTokensToWebview(result.data); console.log(' [OFFLINE AUTH] Tokens injected to webviews'); } catch (injectError) { console.warn(' [OFFLINE AUTH] Token injection failed:', injectError.message); } }
return result; } catch (error) { console.error(' [OFFLINE AUTH] Login failed:', error); return { success: false, error: error.message }; }});
/** * IPC Handler: Polling Device Status (รอ user approve) - Offline Mode */ipcMain.handle('auth:poll-device', async (event, deviceCode) => { try { if (!deviceCode) { throw new Error('Device code is required'); }
const client = getOfflineAuthClient(); const result = await client.pollDeviceStatus(deviceCode);
return { success: true, data: result }; } catch (error) { console.error(' [OFFLINE AUTH] Failed to poll device status:', error); return { success: false, error: error.message }; }});
/** * IPC Handler: ดึงข้อมูล User ปัจจุบัน */ipcMain.handle('auth:get-current-user', async () => { try { const client = getOfflineAuthClient(); const tokenData = await client.loadTokens();
if (tokenData.success) { return { success: true, data: tokenData.data.user, authenticated: true }; } else { return { success: true, data: null, authenticated: false, error: tokenData.error }; } } catch (error) { console.error(' [OFFLINE AUTH] Failed to get current user:', error); return { success: false, error: error.message, authenticated: false }; }});
/** * IPC Handler: Logout (ลบ tokens) */ipcMain.handle('auth:logout', async () => { try { console.log(' [OFFLINE AUTH] Logging out...'); const client = getOfflineAuthClient(); await client.removeTokens();
return { success: true, message: 'Logged out successfully' }; } catch (error) { console.error(' [OFFLINE AUTH] Failed to logout:', error); return { success: false, error: error.message }; }});
/** * IPC Handler: ตรวจสอบสถานะ Authentication */ipcMain.handle('auth:check-status', async () => { try { const client = getOfflineAuthClient(); const tokenData = await client.loadTokens();
return { success: true, authenticated: tokenData.success, user: tokenData.success ? tokenData.data.user : null, tokenExists: tokenData.success, error: tokenData.success ? null : tokenData.error }; } catch (error) { console.error(' [OFFLINE AUTH] Failed to check auth status:', error); return { success: false, authenticated: false, error: error.message }; }});
/** * Inject authentication tokens to webview * @param {Object} tokens - Token data to inject */async function injectTokensToWebview(tokens) { console.log(' [Webview] Injecting tokens to active webviews');
try { if (!mainWindow || !mainWindow.webContents) { throw new Error('Main window not available'); }
// Send tokens to all webviews through the main window mainWindow.webContents.send('auth:inject-to-webviews', tokens);
console.log(' [Webview] Tokens sent to webviews'); return { success: true }; } catch (error) { console.error(' [Webview] Token injection failed:', error); throw error; }}
// [CLEANED] Removed old authentication IPC handlers - replaced with new Device Flow handlers above
ipcMain.handle('webview:inject-tokens', async (event, { webviewId, tokens }) => { console.log(`[WEBVIEW] Injecting tokens to webview ${webviewId}...`); try { await injectTokensToWebview(tokens); return { success: true }; } catch (error) { return { success: false, error: error.message }; }});
// Handle webview request for auth tokensipcMain.handle('webview:request-auth-tokens', async (event) => { console.log(' [Webview] Webview requesting auth tokens'); try { const client = getDeviceAuthClient(); const tokenData = await client.loadTokens();
if (tokenData.success) { // Send tokens back to the requesting webview event.sender.send('auth:inject-tokens', tokenData.data); console.log(' [Webview] Tokens sent to requesting webview'); return { success: true }; } else { console.log(' [Webview] No valid tokens found'); return { success: false, error: 'No authentication tokens found' }; } } catch (error) { console.error(' [Webview] Failed to retrieve tokens:', error); return { success: false, error: error.message }; }});
ipcMain.handle('show-message-box', async (event, options) => { const { dialog } = require('electron'); return await dialog.showMessageBox(mainWindow, options);});
ipcMain.handle('open-external', async (event, url) => { if (!url || typeof url !== 'string') { console.warn('Invalid URL provided to open-external:', url); return false; }
try { console.log('Opening external URL:', url); await shell.openExternal(url); return true; } catch (error) { console.error('Failed to open external URL:', error); return false; }});
const API_BASE_URL = 'https://chahuadev.com';
// [เพิ่มใหม่] IPC Handler สำหรับส่ง Path ของ preload-webview.jsipcMain.handle('get-preload-webview-path', () => { try { const preloadPath = path.join(__dirname, 'preload-webview.js'); console.log(`[IPC] Providing webview preload path: ${preloadPath}`); return preloadPath; } catch (error) { console.error(' Error getting webview preload path:', error); return null; }});
ipcMain.handle('get-preload-path', () => { try { const preloadPath = path.join(__dirname, 'preload-webview.js'); console.log(`[IPC] Providing preload path: ${preloadPath}`); return preloadPath; } catch (error) { console.error(' Error getting preload path:', error); return null; }});
ipcMain.handle('get-system-info', async () => { const os = require('os'); return { platform: os.platform(), arch: os.arch(), release: os.release(), hostname: os.hostname(), userInfo: os.userInfo(), cpus: os.cpus().length, totalMemory: os.totalmem(), freeMemory: os.freemem() };});
// --- WebView Action Handler ---ipcMain.handle('handle-webview-action', async (event, message) => { console.log(`[Main] Received action from WebView: ${message.action}`);
if (message.action === 'install-plugin') { const pluginData = message.payload; console.log(`[Main] Starting Framework installation for:`, pluginData);
try { const pluginId = pluginData.id || pluginData.pluginId || pluginData.name; console.log(`[Main] Installing Framework with NPM for plugin: ${pluginId}`);
// ติดตั้ง Framework ผ่าน NPM const { execSync } = require('child_process');
console.log(`[Framework Install] Running: npm install -g @chahuadev/framework`);
// รัน npm install command const result = execSync('npm install -g @chahuadev/framework', { encoding: 'utf8', stdio: 'pipe' });
console.log(` [Framework Install] NPM Output:`, result); console.log(` [Framework Install] Framework installed successfully`);
// แจ้งให้ UI ทราบผลลัพธ์ if (mainWindow && mainWindow.webContents) { mainWindow.webContents.send('show-notification', ` ติดตั้ง Chahua Framework สำเร็จ`); mainWindow.webContents.send('refresh-plugins'); }
return { success: true, installMethod: 'npm' };
} catch (error) { console.error('[Main] Framework installation error:', error);
// แจ้งข้อผิดพลาดให้ UI if (mainWindow && mainWindow.webContents) { mainWindow.webContents.send('show-notification', ` เกิดข้อผิดพลาดในการติดตั้ง Framework: ${error.message}`); }
return { success: false, error: error.message }; } }
return { success: false, error: 'Unknown action' };});
// SECURE NPM COMMAND EXECUTION - ผ่าน ValidationGatewayipcMain.handle('execute-npm-command', async (event, command) => { try { console.log(`[Main] NPM Command Request: ${command}`);
// ส่งคำขอไปยัง ValidationGateway เพื่อตรวจสอบความปลอดภัย const result = await validationGateway.processCommand({ action: 'execute-npm-command', command: command, userAgent: 'Electron-App', timestamp: new Date().toISOString() });
// แจ้งผลลัพธ์ให้ UI if (mainWindow && mainWindow.webContents) { if (result.success) { // ดึงชื่อแอปจากคำสั่งเพื่อแสดงใน notification const appMatch = command.match(/@chahuadev\/([\w-]+)/); const appName = appMatch ? appMatch[1] : 'Chahua App'; const actionMatch = command.match(/^npm\s+(install|update|uninstall)/); const action = actionMatch ? actionMatch[1] : 'process';
let message = ' ดำเนินการสำเร็จ'; if (action === 'install') message = ` ติดตั้ง ${appName} สำเร็จ`; else if (action === 'update') message = ` อัปเดต ${appName} สำเร็จ`; else if (action === 'uninstall') message = ` ถอนการติดตั้ง ${appName} สำเร็จ`;
mainWindow.webContents.send('show-notification', message); } else { mainWindow.webContents.send('show-notification', ` เกิดข้อผิดพลาด: ${result.error}`); } }
return result;
} catch (error) { console.error(`[Main] NPM Command Handler Failed:`, error.message);
// แจ้งข้อผิดพลาดให้ UI if (mainWindow && mainWindow.webContents) { mainWindow.webContents.send('show-notification', ` เกิดข้อผิดพลาดภายใน: ${error.message}`); }
return { success: false, error: error.message, command: command, securityLevel: 'SYSTEM_ERROR' }; }});
// IPC Handler: Run Manifest Generator (Production-Safe) ipcMain.handle('run-manifest-generator', async () => { try { console.log(' [IPC] Running manifest generator function directly...');
// 1. คำนวณ Path ของโฟลเดอร์ plugins ที่ถูกต้อง - FIX: ใช้ app.isPackaged let pluginsDir; if (app.isPackaged) { pluginsDir = path.join(path.dirname(app.getPath('exe')), 'plugins'); } else { pluginsDir = path.join(app.getPath('userData'), 'plugins'); }
// ตรวจสอบและสร้างโฟลเดอร์หากยังไม่มี if (!fs.existsSync(pluginsDir)) { fs.mkdirSync(pluginsDir, { recursive: true }); }
console.log(` [IPC] Using plugins directory: ${pluginsDir}`);
// 2. ส่ง Path ที่ถูกต้องเข้าไปในฟังก์ชัน await generateManifests(pluginsDir);
// 3. สั่งให้ ValidationGateway โหลดปลั๊กอินใหม่! try { await validationGateway.initializePlugins(); // สั่งให้ Gateway โหลดปลั๊กอินใหม่! console.log(' Plugins reloaded via Gateway'); } catch (error) { console.warn(' Plugin reload skipped:', error.message); }
console.log(' Manifest generation and plugin reload completed.'); return { success: true, output: `Manifest generation completed successfully in:\n${pluginsDir}`, message: 'Manifests generated successfully and plugin list reloaded.' };
} catch (error) { console.error(` Manifest generator failed during direct call: ${error.message}`); return { success: false, error: error.message }; }});
// IPC Handler: System Check for In-App Diagnostics ipcMain.handle('run-system-check', async () => { try { console.log(' [IPC] Running system check and auto-repair...');
// คำนวณ Path ของโฟลเดอร์ plugins let pluginsDir; if (app.isPackaged) { pluginsDir = path.join(path.dirname(app.getPath('exe')), 'plugins'); } else { pluginsDir = path.join(app.getPath('userData'), 'plugins'); }
// ใช้ Project Inspector เพื่อวิเคราะห์ปลั๊กอิน const projectInspector = require('./utils/project-inspector'); const analysis = await projectInspector.analyzeProject(pluginsDir);
let repairResults = [];
// การซ่อมแซมอัตโนมัติ if (analysis.totalIssues > 0) { console.log(` Found ${analysis.totalIssues} issues, attempting auto-repair...`);
// ลองซ่อมแซมด้วยการสร้าง manifest ใหม่ try { await generateManifests(pluginsDir); repairResults.push('Generated missing manifest files'); } catch (error) { console.warn(' Auto-repair failed:', error.message); }
// ลองรีโหลดปลั๊กอิน try { await validationGateway.initializePlugins(); repairResults.push('Reloaded plugin registry'); } catch (error) { console.warn(' Plugin reload failed:', error.message); } }
const message = analysis.totalIssues === 0 ? 'ไม่พบปัญหาในระบบ ทุกอย่างทำงานปกติ' : `พบปัญหา ${analysis.totalIssues} รายการ - ระบบได้ทำการซ่อมแซมแล้ว`;
console.log(' System check completed successfully'); return { success: true, message: message, fixed: repairResults.length > 0, repairActions: repairResults, analysis: analysis };
} catch (error) { console.error(` System check failed: ${error.message}`); return { success: false, error: error.message }; }});
// IPC Handler: Parameterized System Check ipcMain.handle('run-parameterized-system-check', async (event, params) => { try { console.log(' [IPC] Running parameterized system check...', params);
const { scope, plugins } = params;
// คำนวณ Path ของโฟลเดอร์ plugins let pluginsDir; if (app.isPackaged) { pluginsDir = path.join(path.dirname(app.getPath('exe')), 'plugins'); } else { pluginsDir = path.join(app.getPath('userData'), 'plugins'); }
let analysisResult; let repairResults = []; let recommendations = [];
switch (scope) { case 'all': // วิเคราะห์ทั้งระบบ (เหมือนเดิม) const projectInspector = require('./utils/project-inspector'); analysisResult = await projectInspector.analyzeProject(pluginsDir);
if (analysisResult.totalIssues > 0) { // ซ่อมแซมอัตโนมัติ try { await generateManifests(pluginsDir); repairResults.push('Generated missing manifest files'); } catch (error) { console.warn(' Auto-repair failed:', error.message); } } break;
case 'plugins': // วิเคราะห์เฉพาะปลั๊กอิน const projectInspector2 = require('./utils/project-inspector'); analysisResult = await projectInspector2.analyzeProject(pluginsDir);
// เน้นที่ข้อมูล type analysis if (analysisResult.typeAnalysis) { recommendations.push(...analysisResult.typeAnalysis.recommendations); } break;
case 'core': // วิเคราะห์เฉพาะระบบหลัก analysisResult = { totalIssues: 0, message: 'ตรวจสอบระบบหลักเสร็จสิ้น - ไม่พบปัญหา' }; break;
case 'dependencies': // วิเคราะห์ dependencies analysisResult = await analyzeDependencies(pluginsDir); break;
case 'specific': // วิเคราะห์ปลั๊กอินที่เลือก if (plugins && plugins.length > 0) { analysisResult = await analyzeSpecificPlugins(plugins); } else { return { success: false, error: 'กรุณาเลือกปลั๊กอินที่ต้องการตรวจสอบ' }; } break;
default: return { success: false, error: 'ประเภทการวินิจฉัยไม่ถูกต้อง' }; }
const message = analysisResult.totalIssues === 0 ? `ไม่พบปัญหาใน${getScopeText(scope)}` : `พบปัญหา ${analysisResult.totalIssues} รายการใน${getScopeText(scope)}`;
console.log(' Parameterized system check completed successfully'); return { success: true, message: message, fixed: repairResults.length > 0, repairActions: repairResults, recommendations: recommendations, analysis: analysisResult, scope: scope };
} catch (error) { console.error(` Parameterized system check failed: ${error.message}`); return { success: false, error: error.message }; }});
// Helper functions for parameterized diagnosticsfunction getScopeText(scope) { const texts = { 'all': 'ทั้งระบบ', 'plugins': 'ปลั๊กอิน', 'core': 'ระบบหลัก', 'dependencies': 'Dependencies', 'specific': 'ปลั๊กอินที่เลือก' }; return texts[scope] || 'ส่วนที่ระบุ';}
async function analyzeDependencies(pluginsDir) { // ตรวจสอบ dependencies ของปลั๊กอินต่างๆ const issues = [];
try { const plugins = fs.readdirSync(pluginsDir); for (const plugin of plugins) { const pluginPath = path.join(pluginsDir, plugin); const stat = fs.statSync(pluginPath);
if (stat.isDirectory()) { // ตรวจสอบ package.json const packageJsonPath = path.join(pluginPath, 'package.json'); if (fs.existsSync(packageJsonPath)) { try { const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')); if (!packageJson.dependencies && !packageJson.devDependencies) { issues.push(`ปลั๊กอิน ${plugin} ไม่มี dependencies`); } } catch (error) { issues.push(`ปลั๊กอิน ${plugin} มี package.json ที่ไม่ถูกต้อง`); } } } } } catch (error) { issues.push(`ไม่สามารถตรวจสอบ dependencies ได้: ${error.message}`); }
return { totalIssues: issues.length, issues: issues, message: issues.length === 0 ? 'Dependencies ทั้งหมดปกติ' : `พบปัญหา dependencies ${issues.length} รายการ` };}
async function analyzeSpecificPlugins(pluginPaths) { const projectInspector = require('./utils/project-inspector'); let totalIssues = 0; const results = [];
for (const pluginPath of pluginPaths) { try { const analysis = await projectInspector.analyzeProject(pluginPath); totalIssues += analysis.totalIssues; results.push({ path: pluginPath, analysis: analysis }); } catch (error) { totalIssues++; results.push({ path: pluginPath, error: error.message }); } }
return { totalIssues: totalIssues, results: results, message: `ตรวจสอบปลั๊กอิน ${pluginPaths.length} รายการเสร็จสิ้น` };}
// Removed duplicate 'get-available-plugins' handler - using ValidationGateway version instead
// IPC Handler: Open Plugins Folder (NEW - สำหรับเปิดโฟลเดอร์ plugins) - FIX: ใช้ app.isPackagedipcMain.handle('open-plugins-folder', () => { // FIX: ใช้ app.isPackaged เพื่อจัดการ plugins directory path let pluginsDir; if (app.isPackaged) { pluginsDir = path.join(path.dirname(app.getPath('exe')), 'plugins'); } else { pluginsDir = path.join(app.getPath('userData'), 'plugins'); }
// สร้างโฟลเดอร์ถ้ายังไม่มี if (!fs.existsSync(pluginsDir)) { try { fs.mkdirSync(pluginsDir, { recursive: true }); console.log(` Created plugins directory at: ${pluginsDir}`); } catch (error) { console.error(` Failed to create plugins directory:`, error); return { success: false, error: error.message }; } }
// เปิดโฟลเดอร์ใน File Explorer shell.openPath(pluginsDir); console.log(` Opened plugins folder: ${pluginsDir}`);
return { success: true, path: pluginsDir };});
// IPC Handler: Get All Available Plugins (via ValidationGateway)ipcMain.handle('get-available-plugins', async () => { try { // ValidationGateway's PluginManager will handle this const result = await validationGateway.processCommand({ action: 'list-plugins' }); console.log(` Returning available plugins via Gateway`); return result; } catch (error) { console.error(' Failed to get plugins:', error.message); return { success: false, error: error.message }; }});
// Plugin-specific IPC handlers removed - all commands now go through execute-command -> ValidationGateway
// Plugin command handling functions removed - now handled by ValidationGateway
// IPC Handler: Run NPM Project Commands (for HTML plugins)ipcMain.handle('run-npm-project', async (event, payload) => { console.log(' [IPC] NPM Project command received:', payload);
try { // Check if this comes from an HTML plugin window const senderWebContentsId = event.sender.id; const htmlPluginInfo = global.htmlPluginWindows?.get(senderWebContentsId);
if (!htmlPluginInfo || !htmlPluginInfo.isProjectManager) { throw new Error('This command can only be executed from HTML project management plugins'); }
console.log(` [IPC] Running command from ${htmlPluginInfo.pluginName}`);
// Security validation const context = { pipelineId: 'html_plugin_' + Date.now(), type: 'html_plugin_request', request: payload, htmlPlugin: htmlPluginInfo.pluginName };
const securityResult = await validationGateway.validate(payload, context);
if (!securityResult.valid) { console.log(' [IPC] Security validation failed for HTML plugin:', securityResult.message); return { success: false, error: securityResult.message || 'Security validation failed' }; }
// Execute based on action type switch (payload.action) { case 'scan-projects': return await handleScanProjects();
case 'scan-project': return await handleScanProject(payload.project, payload.path);
default: // Regular command execution const NodeStrategy = require('./strategies/NodeStrategy'); const nodeStrategy = new NodeStrategy();
let projectPath = payload.path || payload.cwd; if (!projectPath) { projectPath = path.join(__dirname, 'plugins', 'Chahuadev_Studio_V.10.0.0'); }
const commandContext = { command: payload.command || payload.action, projectPath: projectPath, options: { timeout: 60000, env: {} } };
const result = await nodeStrategy.execute(commandContext);
return { success: result.success, data: result.success ? { success: true, output: result.output, message: `Command executed successfully`, command: commandContext.command, exitCode: result.exitCode, duration: result.duration } : null, error: result.success ? null : result.error, timestamp: new Date().toISOString(), source: 'html_plugin_npm' }; }
} catch (error) { console.error(' [IPC] HTML Plugin NPM command error:', error.message);
return { success: false, error: error.message, timestamp: new Date().toISOString() }; }});
// Project analysis functions removed - now handled by ValidationGateway's SystemDetector
// Handler: Scan Projects (NEW!)async function handleScanProjects() { console.log(' [Scan] Starting project scan...');
try { // ใช้ SystemDetector ในการสแกน const SystemDetector = require('./modules/system-detector'); const systemDetector = new SystemDetector();
// เรียกใช้ scanProjects ที่ SystemDetector const result = await systemDetector.scanProjects();
console.log(` [Scan] Scan complete: ${result.count} projects found`);
return { success: true, data: result, timestamp: new Date().toISOString() };
} catch (error) { console.error(' [Scan] Error during project scan:', error.message); return { success: false, error: error.message, timestamp: new Date().toISOString() }; }}
// Handler: Scan Single Project (NEW!)async function handleScanProject(projectName, projectPath) { console.log(` [Scan] Scanning single project: ${projectName} at ${projectPath}`);
try { // ใช้ SystemDetector ในการสแกน const SystemDetector = require('./modules/system-detector'); const systemDetector = new SystemDetector();
// เรียกใช้ detect สำหรับโปรเจกต์เดียว const result = await systemDetector.detect(projectPath);
console.log(` [Scan] Single project scan complete: ${result.type} (${result.confidence}%)`);
return { success: true, data: result, timestamp: new Date().toISOString() };
} catch (error) { console.error(' [Scan] Error during single project scan:', error.message); return { success: false, error: error.message, timestamp: new Date().toISOString() }; }}
// IPC Handler: Execute Quick Commands (NEW!) - with Fort-Knox SecurityipcMain.handle('execute-quick-command', async (event, command) => { console.log(' [IPC] Quick command received:', command);
try { // SECURITY: ตรวจสอบและทำความสะอาดคำสั่งก่อนรัน let sanitizedResult; try { sanitizedResult = ipcSecurity.sanitizeCommand(command); } catch (securityError) { console.error(' [Security] Command blocked:', securityError.message); return { success: false, error: `Security violation: ${securityError.message}`, securityAlert: true }; }
// Parse --cwd= parameter if present let workingDir = null; let cleanCommand = sanitizedResult.sanitized;
if (cleanCommand.includes('--cwd=')) { const cwdMatch = cleanCommand.match(/--cwd=([^\s]+)/); if (cwdMatch) { workingDir = cwdMatch[1]; cleanCommand = cleanCommand.replace(/--cwd=[^\s]+\s*/, '').trim(); console.log(` [IPC] Working directory: ${workingDir}`);
// ตรวจสอบ working directory path if (workingDir.includes('../') || workingDir.includes('..\\')) { throw new Error('Path traversal detected in working directory'); } } }
// Execute using NodeStrategy const NodeStrategy = require('./strategies/NodeStrategy'); const nodeStrategy = new NodeStrategy();
const commandContext = { command: cleanCommand, projectPath: workingDir || getUnpackedPath('plugins/Chahuadev_Studio_V.10.0.0'), options: { timeout: 60000, env: {} } };
const result = await nodeStrategy.execute(commandContext);
return { success: result.success, data: result.success ? { output: result.output, message: `Quick command executed: ${cleanCommand}`, exitCode: result.exitCode, securityInfo: `Command sanitized and executed safely (${sanitizedResult.baseCommand})` } : null, error: result.success ? null : result.error };
} catch (error) { console.error(' [IPC] Quick command error:', error.message); return { success: false, error: error.message }; }});
// IPC Handler: Execute Plugin Commands (NEW - to bridge UI buttons)ipcMain.handle('execute-plugin-command', async (event, pluginName, command, data) => { console.log(` [IPC] Received command: [${command}] on [${pluginName}]`); if (!validationGateway) { return { success: false, error: 'Validation Gateway not initialized' }; }
try { // หา Path ของโปรเจกต์ (ปลั๊กอิน) ก่อน const projectPath = await validationGateway.getPluginPath(pluginName);
// สร้าง request object ที่สมบูรณ์เพื่อส่งให้ Gateway const request = { action: command, // action คือคำสั่งที่ได้จากปุ่มโดยตรง เช่น 'launch-exe' pluginName: pluginName, projectPath: projectPath, // ส่ง Path ที่ถูกต้องไปด้วย data: data || {} };
console.log(`Forwarding to Gateway processCommand:`, request);
// ส่งให้ processCommand ใน Gateway จัดการ ซึ่งมี switch-case รองรับทุก action const result = await validationGateway.processCommand(request);
return result;
} catch (error) { console.error(` [IPC] Error processing command "${command}" for "${pluginName}":`, error); return { success: false, error: error.message }; }});
// MAIN IPC HANDLER: Execute Commands via ValidationGateway ipcMain.handle('execute-command', async (event, payload) => { console.log(' [IPC] Received command, forwarding to Validation Gateway:', payload); try { // ส่งต่อไปให้ Gateway จัดการทั้งหมด return await validationGateway.processCommand(payload); } catch (error) { console.error(' [IPC] Error forwarding to ValidationGateway:', error.message); return { success: false, error: error.message, timestamp: new Date().toISOString() }; }});
// IPC Handler: Get Run Mode (Development vs Production)ipcMain.handle('get-run-mode', () => { console.log(` [IPC] Checking run mode - isDevMode: ${isDevMode}`); return { isDevMode: isDevMode };});
// IPC Handler: Build App Process (NEW!)ipcMain.handle('start-build', async (event) => { console.log(' [IPC] Starting build process...');
// ใช้ child_process เพื่อรันคำสั่ง electron-builder const { exec } = require('child_process');
// คำสั่ง build สำหรับ Windows const command = 'npx electron-builder --win --x64';
// ได้ project root จากฟังก์ชันที่มีอยู่แล้ว const projectRoot = getAppBasePath();
console.log(` Starting build with command: ${command}`); console.log(` Project root: ${projectRoot}`);
try { // รันคำสั่ง build const buildProcess = exec(command, { cwd: projectRoot });
// ส่ง Log กลับไปที่ UI แบบ Real-time buildProcess.stdout.on('data', (data) => { console.log(` [STDOUT] ${data}`); // ส่ง Log กลับไปที่หน้าต่างหลักผ่านช่องทาง 'build-log' if (mainWindow && !mainWindow.isDestroyed()) { mainWindow.webContents.send('build-log', data.toString()); } });
// ส่ง Error Log กลับไป buildProcess.stderr.on('data', (data) => { console.log(` [STDERR] ${data}`); if (mainWindow && !mainWindow.isDestroyed()) { // ส่ง Error Log กลับไปในรูปแบบที่แตกต่าง mainWindow.webContents.send('build-log', `[ERROR] ${data.toString()}`); } });
// เมื่อกระบวนการ Build สิ้นสุดลง buildProcess.on('close', (code) => { const message = code === 0 ? ' กระบวนการ Build เสร็จสมบูรณ์!' : ` กระบวนการ Build ล้มเหลว (Exit Code: ${code})`;
console.log(` Build process finished with code: ${code}`);
if (mainWindow && !mainWindow.isDestroyed()) { mainWindow.webContents.send('build-log', `\n ${message}`);
if (code === 0) { // ส่งข้อมูลเพิ่มเติมเมื่อ Build สำเร็จ mainWindow.webContents.send('build-log', ' ไฟล์ Build สำเร็จแล้ว สามารถดูได้ในโฟลเดอร์ dist/'); mainWindow.webContents.send('build-log', ' ไฟล์ที่สร้าง: *.exe, *.msi, *.zip'); mainWindow.webContents.send('build-log', ' สามารถนำไปติดตั้งบนเครื่องอื่นได้แล้ว!'); } } });
// เมื่อมี error ในการ start process buildProcess.on('error', (error) => { console.error(` Build process error:`, error); if (mainWindow && !mainWindow.isDestroyed()) { mainWindow.webContents.send('build-log', `[ERROR] ไม่สามารถเริ่ม Build ได้: ${error.message}`); } });
return { success: true };
} catch (error) { console.error(` Build command failed to start:`, error); return { success: false, error: error.message }; }});
// System Information API Handlers - สำหรับ debugger.jsipcMain.handle('system:get-info', async () => { try { const info = { platform: os.platform(), arch: os.arch(), version: os.version(), uptime: os.uptime(), totalmem: os.totalmem(), freemem: os.freemem(), cpus: os.cpus().length, networkInterfaces: Object.keys(os.networkInterfaces()).length }; return info; } catch (error) { console.error(' [System] Get info error:', error); throw error; }});
ipcMain.handle('system:get-cwd', async () => { try { return process.cwd(); } catch (error) { console.error(' [System] Get CWD error:', error); throw error; }});
ipcMain.handle('system:get-version', async () => { try { return app.getVersion(); } catch (error) { console.error(' [System] Get version error:', error); throw error; }});
ipcMain.handle('system:get-memory-usage', async () => { try { return process.memoryUsage(); } catch (error) { console.error(' [System] Get memory usage error:', error); throw error; }});
ipcMain.handle('system:get-cpu-usage', async () => { try { return os.cpus(); } catch (error) { console.error(' [System] Get CPU usage error:', error); throw error; }});
ipcMain.handle('system:get-platform', async () => { try { return { platform: process.platform, arch: process.arch, version: process.version }; } catch (error) { console.error(' [System] Get platform error:', error); throw error; }});
ipcMain.handle('system:get-plugins-path', async () => { try { let pluginsDir; if (app.isPackaged) { // โหมดใช้งานจริง: อยู่ข้างไฟล์ .exe pluginsDir = path.join(path.dirname(app.getPath('exe')), 'plugins'); } else { // โหมดพัฒนา: อยู่ใน AppData pluginsDir = path.join(app.getPath('userData'), 'plugins'); } return pluginsDir; } catch (error) { console.error(' [System] Get plugins path error:', error); throw error; }});
// ========== FORT-KNOX SECURITY IPC HANDLERS ==========ipcMain.handle('process-command', async (event, request) => { try { console.log(' [Main] Processing command:', request.command || request.action); const result = await validationGateway.processCommand(request); return result; } catch (error) { console.error(' [Main] Process command error:', error); return { success: false, error: error.message }; }});
// ========== FORT-KNOX SECURITY IPC HANDLERS ==========
// IPC Handler: ตรวจสอบโหมด Developer ModeipcMain.handle('security:get-dev-mode', async () => { try { return { success: true, data: { isDevMode: antiDebugging.isDevMode, detectionMethod: antiDebugging.detectDeveloperMode ? 'enhanced' : 'legacy', timestamp: Date.now() } }; } catch (error) { console.error(' Error getting dev mode status:', error); return { success: false, error: error.message, data: { isDevMode: false } // Default to production mode on error }; }});
// IPC Handler: ตรวจสอบสถานะความปลอดภัยipcMain.handle('security:get-status', async () => { try { return { success: true, data: { antiDebugging: { enabled: !antiDebugging.isDevMode, mode: antiDebugging.isDevMode ? 'development' : 'production', suspiciousActivityCount: antiDebugging.suspiciousActivityCount, maxSuspiciousActivity: antiDebugging.maxSuspiciousActivity }, ipcSecurity: { enabled: true, allowedCommands: ipcSecurity.getAllowedCommands(), commandCount: ipcSecurity.getAllowedCommands().length }, buildMode: app.isPackaged ? 'production' : 'development', version: app.getVersion(), securityLevel: 'Fort-Knox' } }; } catch (error) { return { success: false, error: error.message }; }});
// IPC Handler: ทดสอบการทำงานของระบบความปลอดภัยipcMain.handle('security:test-command-sanitization', async (event, testCommand) => { try { const result = ipcSecurity.sanitizeCommand(testCommand); return { success: true, data: { original: result.original, sanitized: result.sanitized, baseCommand: result.baseCommand, isAllowed: result.isAllowed, testResult: 'Command passed security validation' } }; } catch (error) { return { success: false, error: error.message, data: { original: testCommand, testResult: 'Command blocked by security system', reason: error.message } }; }});
module.exports = { mainWindow }; 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621/** * Button Generator - Smart Button Creation System * Chahua Development Thailand * CEO: Saharath C. * * Purpose: สร้างปุ่มแบบอัจฉริยะตามการทำงานของโปรเจค */
const fs = require('fs');const path = require('path');
class ButtonGenerator { constructor(language = 'en') { this.buttonRegistry = new Map(); this.language = language; // ภาษาปัจจุบัน: 'en' หรือ 'th' this.templateLibrary = this.initializeTemplateLibrary(); this.actionHandlers = new Map(); this.translations = this.initializeTranslations(); console.log(` Button Generator initialized (Language: ${language})`); }
// ระบบแปลหลายภาษา initializeTranslations() { return { 'en': { // Node.js 'npm-install': 'Install', 'npm-start': 'Start', 'npm-test': 'Test', 'npm-build': 'Build', 'npm-lint': 'Lint', 'npm-dev': 'Dev', 'npm-serve': 'Serve', // Python 'pip-install': 'Install', 'python-run': 'Run Main', 'python-test': 'Test', 'python-format': 'Format', // Executable 'launch-exe': 'Launch App', 'run-as-admin': 'Run as Admin', // Batch 'run-batch': 'Run Script', 'edit-batch': 'Edit Script', // Utility 'open-terminal': 'Terminal', 'file-explorer': 'Open Folder', 'refresh': 'Refresh', 'settings': 'Settings', // Web 'npm-watch': 'Watch', 'deploy': 'Deploy', // Categories 'Node.js Basic': 'Node.js Basic', 'Node.js Advanced': 'Node.js Advanced', 'Python Basic': 'Python Basic', 'Python Advanced': 'Python Advanced', 'Application': 'Application', 'Batch Scripts': 'Batch Scripts', 'Utility': 'Utility', 'Web Development': 'Web Development' }, 'th': { // Node.js 'npm-install': 'ติดตั้ง', 'npm-start': 'เริ่มต้น', 'npm-test': 'ทดสอบ', 'npm-build': 'สร้าง', 'npm-lint': 'ตรวจสอบ', 'npm-dev': 'พัฒนา', 'npm-serve': 'เรียกใช้', // Python 'pip-install': 'ติดตั้ง', 'python-run': 'รันหลัก', 'python-test': 'ทดสอบ', 'python-format': 'จัดรูป', // Executable 'launch-exe': 'เปิดแอป', 'run-as-admin': 'รันเป็นผู้ดูแลระบบ', // Batch 'run-batch': 'รันสคริปต์', 'edit-batch': 'แก้ไขสคริปต์', // Utility 'open-terminal': 'เทอร์มินัล', 'file-explorer': 'เปิดโฟลเดอร์', 'refresh': 'รีเฟรช', 'settings': 'ตั้งค่า', // Web 'npm-watch': 'เฝ้าดู', 'deploy': 'ปรับใช้', // Categories 'Node.js Basic': 'Node.js พื้นฐาน', 'Node.js Advanced': 'Node.js ขั้นสูง', 'Python Basic': 'Python พื้นฐาน', 'Python Advanced': 'Python ขั้นสูง', 'Application': 'แอปพลิเคชัน', 'Batch Scripts': 'สคริปต์ Batch', 'Utility': 'เครื่องมือ', 'Web Development': 'พัฒนา Web' } }; }
// ฟังก์ชันแปลข้อความ translate(key) { const trans = this.translations[this.language] || this.translations['en']; return trans[key] || key; }
// ตั้งภาษา setLanguage(language) { if (this.translations[language]) { this.language = language; console.log(` Button language changed to: ${language}`); } else { console.warn(` Unsupported language: ${language}, using English`); this.language = 'en'; } }
// ไลบรารีเทมเพลตปุ่มสำหรับโปรเจคต่างๆ initializeTemplateLibrary() { return { // Node.js Project Templates 'node-basic': { category: 'Node.js Basic', buttons: [ { id: 'npm-install', nameKey: 'npm-install', command: 'npm-install', icon: '' }, { id: 'npm-start', nameKey: 'npm-start', command: 'npm-start', icon: '' } ] }, 'node-advanced': { category: 'Node.js Advanced', buttons: [ { id: 'npm-test', nameKey: 'npm-test', command: 'npm-test', icon: '' }, { id: 'npm-build', nameKey: 'npm-build', command: 'npm-build', icon: '' }, { id: 'npm-lint', nameKey: 'npm-lint', command: 'npm-lint', icon: '' } ] },
// Python Project Templates 'python-basic': { category: 'Python Basic', buttons: [ { id: 'pip-install', nameKey: 'pip-install', command: 'pip-install', icon: '' }, { id: 'python-run', nameKey: 'python-run', command: 'python-run', icon: '' } ] },
// เพิ่ม Template ใหม่สำหรับ EXE 'executable-runner': { category: 'Application', buttons: [ { id: 'launch-exe', nameKey: 'launch-exe', command: 'launch-exe', icon: '' }, { id: 'run-as-admin', nameKey: 'run-as-admin', command: 'run-as-admin', icon: '' } ] },
// เพิ่ม Template ใหม่สำหรับ BAT 'batch-runner': { category: 'Batch Scripts', buttons: [ { id: 'run-batch', nameKey: 'run-batch', command: 'run-batch', icon: '' }, { id: 'edit-batch', nameKey: 'edit-batch', command: 'edit-batch', icon: '' } ] },
// Utility Templates (ปุ่มพื้นฐาน) 'utility': { category: 'Utility', buttons: [ { id: 'open-terminal', nameKey: 'open-terminal', command: 'open_terminal', icon: '' }, { id: 'file-explorer', nameKey: 'file-explorer', command: 'open_explorer', icon: '' } ] } }; }
// สร้างปุ่มตามข้อมูลโปรเจค generateProjectButtons(projectInfo, features) { const { name, type, path: projectPath, previewImage } = projectInfo; // เพิ่ม previewImage let buttons = []; console.log(` Generating buttons for project: ${name} (Type: ${type})`);
// เพิ่ม fallback สำหรับ unknown type let projectType = type; if (projectType === 'unknown') { projectType = 'executable_project'; // fallback เป็น executable_project console.log(` -> [Fallback] Using executable_project type instead of unknown`); projectInfo.type = projectType; // อัปเดต type ใน object }
// --- อัปเกรดตรรกะการตัดสินใจเป็นแบบ 3 ทาง ---
if (features.hasBatchRunner) { // 1. ทางพิเศษสำหรับ .bat console.log(` -> Using Batch Runner strategy`); const batchTemplate = this.templateLibrary['batch-runner']; if (batchTemplate) { const batchButtons = this.customizeButtons(batchTemplate.buttons, projectInfo, features); buttons.push(...this.customizeBatchButtons(batchButtons, projectInfo)); }
} else if (projectType === 'executable_project') { // 2. ทางพิเศษสำหรับ .exe console.log(` -> Using Executable Runner strategy`); const exeTemplate = this.templateLibrary['executable-runner']; if (exeTemplate) { const exeButtons = this.customizeButtons(exeTemplate.buttons, projectInfo, features); buttons.push(...this.customizeExecutableButtons(exeButtons, projectInfo)); }
} else { // 3. ทางปกติสำหรับ npm และอื่นๆ console.log(` -> Using standard template strategy`); const templates = this.selectTemplates(projectType, features); for (const template of templates) { const templateButtons = this.templateLibrary[template]; if (templateButtons) { buttons.push(...this.customizeButtons(templateButtons.buttons, projectInfo, features)); } } } // --- จบส่วนตรรกะ ---
// เพิ่มปุ่มพิเศษตามฟีเจอร��� (เฉพาะโปรเจคธรรมดา) if (!features.hasBatchRunner && projectType !== 'executable_project') { buttons.push(...this.generateConditionalButtons(features, projectInfo)); }
// เพิ่มปุ่มยูทิลิตี้พื้นฐาน buttons.push(...this.generateUtilityButtons(projectInfo));
// เพิ่มข้อมูลภาพตัวอย่างในปุ่มทุกปุ่ม buttons = buttons.map(button => ({ ...button, previewImage: previewImage, // เพิ่มภาพตัวอย่าง projectPreview: previewImage // เก็บ reference เพิ่มเติม }));
// ลงทะเบียนปุ่ม this.buttonRegistry.set(name, { projectInfo, buttons, previewImage, // เก็บ previewImage ใน registry generated: new Date().toISOString() });
console.log(` Generated ${buttons.length} buttons for ${name} with preview: ${previewImage || 'none'}`); return buttons; }
// เลือกเทมเพลตตามประเภทและฟีเจอร์ selectTemplates(projectType, features) { const templates = [];
switch (projectType) { case 'node': templates.push('node-basic'); if (features.hasLinter || features.hasTests || features.hasTypeScript) { templates.push('node-advanced'); } break;
case 'python': templates.push('python-basic'); if (features.hasFlask || features.hasDjango || features.hasJupyter) { templates.push('python-web'); } break;
case 'html': templates.push('web-basic'); break;
case 'studio': templates.push('studio'); break;
// เพิ่มการรองรับ executable และ batch projects case 'executable_project': templates.push('executable-runner'); break;
case 'batch_project': templates.push('batch-runner'); break;
default: templates.push('utility'); break; }
return templates; }
// ปรับแต่งปุ่มตามโปรเจค customizeButtons(templateButtons, projectInfo, features) { return templateButtons.map(btn => ({ ...btn, name: this.translate(btn.nameKey), // แปลชื่อปุ่ม projectName: projectInfo.name, projectPath: projectInfo.path, projectType: projectInfo.type, enabled: this.checkButtonCompatibility(btn, features), tooltip: `${this.translate(btn.nameKey)} for ${projectInfo.name}`, lastUsed: null })); }
// สร้างปุ่มแบบมีเงื่อนไข generateConditionalButtons(features, projectInfo) { const conditionalButtons = [];
// Electron specific buttons - ลบปุ่ม Dev ออก // if (features.hasElectron) { // conditionalButtons.push({ // id: 'electron-dev', // name: 'Electron Dev', // command: 'electron-dev', // icon: '', // color: '#9F7AEA', // category: 'electron', // projectName: projectInfo.name, // projectPath: projectInfo.path, // enabled: true // }); // }
// TypeScript specific buttons if (features.hasTypeScript) { conditionalButtons.push({ id: 'tsc-check', nameKey: 'npm-build', // ใช้ key ที่เป็น static name: this.translate(features.hasTypeScript ? 'npm-build' : 'npm-lint'), // FIX: เปลี่ยน command จาก 'npx tsc --noEmit' เป็น 'tsc-check' command: 'tsc-check', icon: '', color: '#3182CE', category: 'typescript', projectName: projectInfo.name, projectPath: projectInfo.path, enabled: true }); }
return conditionalButtons; }
// สร้างปุ่มยูทิลิตี้ generateUtilityButtons(projectInfo) { const utilityTemplate = this.templateLibrary['utility']; return this.customizeButtons(utilityTemplate.buttons, projectInfo, {}); }
// ตรวจสอบความเข้ากันได้ของปุ่ม checkButtonCompatibility(button, features) { // ตรวจสอบเงื่อนไขเฉพาะ if (button.requires) { return button.requires.every(req => features[req]); }
// ปุ่มพื้นฐานใช้ได้เสมอ return true; }
// ปรับแต่งปุ่มสำหรับ Batch Scripts (เวอร์ชันแก้ไข) customizeBatchButtons(batchButtons, projectInfo) { const fs = require('fs'); const path = require('path'); const { path: projectPath, name } = projectInfo; const customizedButtons = [];
try { const files = fs.readdirSync(projectPath); const batchFiles = files.filter(file => file.endsWith('.bat') || file.endsWith('.cmd') );
console.log(` -> Found ${batchFiles.length} batch files: ${batchFiles.join(', ')}`);
// ถ้าไม่เจอไฟล์ batch เลย ก็ไม่ต้องสร้างปุ่ม if (batchFiles.length === 0) return [];
// ใช้ไฟล์ .bat แรกที่เจอ หรือหาตัวที่ชื่อตรงกับโฟลเดอร์ const targetBatch = batchFiles.find(file => file.toLowerCase().includes(name.toLowerCase()) ) || batchFiles[0];
for (const button of batchButtons) { const customButton = { ...button };
// **จุดแก้ไข:** ให้ command เป็น action name ไม่ใช่ชื่อไฟล์ if (button.id === 'run-batch') { customButton.command = 'run-batch'; // <--- แก้ไขตรงนี้ customButton.name = `Run ${path.parse(targetBatch).name}`; customButton.tooltip = `Execute ${targetBatch}`; } else if (button.id === 'edit-batch') { customButton.command = 'edit-batch'; // <--- แก้ไขตรงนี้ customButton.name = `Edit ${path.parse(targetBatch).name}`; customButton.tooltip = `Edit ${targetBatch} in Notepad`; }
if (customButton.command) { customizedButtons.push(customButton); } }
console.log(` -> Customized ${customizedButtons.length} batch buttons`); return customizedButtons;
} catch (error) { console.log(` -> Error customizing batch buttons: ${error.message}`); return []; } }
// ปรับแต่งปุ่มสำหรับ Executable Files (เวอร์ชันแก้ไข) customizeExecutableButtons(exeButtons, projectInfo) { const fs = require('fs'); const path = require('path'); const { path: projectPath, name } = projectInfo; const customizedButtons = [];
try { const files = fs.readdirSync(projectPath); const exeFiles = files.filter(file => file.endsWith('.exe'));
console.log(` -> Found ${exeFiles.length} executable files: ${exeFiles.join(', ')}`); // ถ้าไม่เจอไฟล์ .exe เลย ก็ไม่ต้องสร้างปุ่ม if (exeFiles.length === 0) return [];
// ใช้ไฟล์ .exe แรกที่เจอ หรือหาตัวที่ชื่อตรงกับโฟลเดอร์ const targetExe = exeFiles.find(file => file.toLowerCase().includes(name.toLowerCase()) ) || exeFiles[0];
for (const button of exeButtons) { const customButton = { ...button };
// **จุดแก้ไข:** ให้ command เป็น action name ที่ Gateway รู้จัก if (button.id === 'launch-exe') { customButton.command = 'launch-exe'; // <--- แก้ไขตรงนี้ customButton.name = `Launch ${path.parse(targetExe).name}`; customButton.tooltip = `Execute ${targetExe}`; } else if (button.id === 'run-as-admin') { customButton.command = 'run-as-admin'; // <--- แก้ไขตรงนี้ customButton.name = `Admin ${path.parse(targetExe).name}`; customButton.tooltip = `Run ${targetExe} as Administrator`; }
if (customButton.command) { customizedButtons.push(customButton); } }
console.log(` -> Customized ${customizedButtons.length} executable buttons`); return customizedButtons;
} catch (error) { console.log(` -> Error customizing executable buttons: ${error.message}`); return []; } }
// สร้าง HTML สำหรับปุ่ม generateButtonHTML(button) { const hotkey = button.hotkey ? `title="${button.tooltip || button.name} (${button.hotkey})"` : `title="${button.tooltip || button.name}"`; // เพิ่ม preview image ถ้ามี const previewImageHTML = button.previewImage ? `<div class="button-preview" style="background-image: url('${button.previewImage}'); background-size: cover; background-position: center; width: 40px; height: 30px; border-radius: 4px; margin-right: 8px;"></div>` : ''; return ` <button class="project-button" data-button-id="${button.id}" data-project="${button.projectName}" data-command="${button.command}" style="background-color: ${button.color || '#718096'}; margin: 4px; padding: 8px 12px; border: none; border-radius: 6px; color: white; cursor: pointer; font-size: 14px; display: inline-flex; align-items: center; gap: 6px;" ${hotkey} ${!button.enabled ? 'disabled' : ''} > ${previewImageHTML} <span>${button.icon || ''}</span> <span>${button.name}</span> </button> `; }
// สร้างภาพตัวอย่างแบบ SVG สำหรับปุ่ม generateButtonPreviewSVG(projectType, projectName) { const previewConfigs = { 'executable_project': { color: '#4A5568', icon: '', label: 'EXE' }, 'batch_project': { color: '#38A169', icon: '', label: 'BAT' }, 'node': { color: '#68D391', icon: '', label: 'NODE' }, 'python': { color: '#4FD1C7', icon: '', label: 'PY' }, 'html': { color: '#90CDF4', icon: '', label: 'WEB' }, 'default': { color: '#718096', icon: '', label: 'PLUGIN' } };
const config = previewConfigs[projectType] || previewConfigs['default']; const svgContent = ` <svg width="100" height="80" xmlns="http://www.w3.org/2000/svg"> <rect width="100" height="80" fill="${config.color}" rx="4"/> <text x="50" y="35" font-family="Arial" font-size="20" fill="white" text-anchor="middle">${config.icon}</text> <text x="50" y="55" font-family="Arial" font-size="10" fill="#E2E8F0" text-anchor="middle">${config.label}</text> <text x="50" y="70" font-family="Arial" font-size="8" fill="#CBD5E0" text-anchor="middle">${projectName.substring(0, 12)}</text> </svg> `;
return `data:image/svg+xml;base64,${Buffer.from(svgContent).toString('base64')}`; }
// สร้างภาพตัวอย่างสำหรับปุ่มเก่าที่ยังไม่มี generateMissingPreviews() { const updated = []; for (const [projectName, projectData] of this.buttonRegistry.entries()) { if (!projectData.previewImage) { const { projectInfo } = projectData; const previewImage = this.generateButtonPreviewSVG(projectInfo.type, projectInfo.name); // อัปเดตข้อมูลใน registry projectData.previewImage = previewImage; projectData.projectInfo.previewImage = previewImage; // อัปเดตปุ่มทั้งหมด projectData.buttons = projectData.buttons.map(button => ({ ...button, previewImage: previewImage, projectPreview: previewImage })); updated.push(projectName); console.log(` Generated missing preview for: ${projectName}`); } } if (updated.length > 0) { console.log(` Updated ${updated.length} projects with missing previews`); } return updated; }
// สร้าง HTML การ์ดโปรเจคแบบเต็ม (รวมภาพตัวอย่าง) generateProjectCardHTML(projectData) { const { projectInfo, buttons, previewImage } = projectData; const cardPreviewImage = previewImage || this.generateButtonPreviewSVG(projectInfo.type, projectInfo.name); const buttonsHTML = buttons.map(button => this.generateButtonHTML(button)).join(''); return ` <div class="project-card" data-project="${projectInfo.name}"> <div class="project-header"> <div class="project-preview"> <img src="${cardPreviewImage}" alt="Preview for ${projectInfo.name}" class="preview-image"> </div> <div class="project-info"> <h3 class="project-title">${projectInfo.name}</h3> <p class="project-type">${projectInfo.type}</p> <p class="project-path">${projectInfo.path}</p> </div> </div> <div class="project-buttons"> ${buttonsHTML} </div> </div> `; }
// ดึงข้อมูลปุ่มทั้งหมด getAllButtons() { return Array.from(this.buttonRegistry.values()); }
// ดึงปุ่มสำหรับโปรเจคเฉพาะ getProjectButtons(projectName) { const projectData = this.buttonRegistry.get(projectName); return projectData ? projectData.buttons : []; }
// รีเซ็ตระบบปุ่ม reset() { this.buttonRegistry.clear(); console.log(' Button registry reset'); }}
module.exports = ButtonGenerator; 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350/** * Cache Manager - ระบบจัดการ Cache * Chahua Development Thailand * CEO: Saharath C. * * Purpose: จัดการการ cache ข้อมูลเพื่อประสิทธิภาพ */
const fs = require('fs');const path = require('path');
class CacheManager { constructor(options = {}) { this.config = { defaultTTL: options.defaultTTL || 300, // 5 minutes maxSize: options.maxSize || 1000, // Max 1000 items persistPath: options.persistPath || './logs/cache', enablePersistence: options.enablePersistence || false, cleanupInterval: options.cleanupInterval || 60000, // 1 minute compressionEnabled: options.compressionEnabled || false }; this.cache = new Map(); this.accessTimes = new Map(); this.stats = { hits: 0, misses: 0, sets: 0, deletes: 0, cleanups: 0 }; this.setupCleanupTimer(); if (this.config.enablePersistence) { this.loadFromDisk(); } console.log('Cache Manager initialized'); }
async set(key, value, options = {}) { try { const ttl = options.ttl || this.config.defaultTTL; const expiry = Date.now() + (ttl * 1000); const cacheItem = { key, value, expiry, size: this.calculateSize(value), created: Date.now(), accessed: Date.now(), hits: 0 }; // Check if we need to make space if (this.cache.size >= this.config.maxSize) { this.evictLRU(); } this.cache.set(key, cacheItem); this.accessTimes.set(key, Date.now()); this.stats.sets++; if (this.config.enablePersistence) { await this.persistToDisk(); } console.log(`Cache SET: ${key} (TTL: ${ttl}s)`); return true; } catch (error) { console.error('Cache set error:', error.message); return false; } }
async get(key) { try { const item = this.cache.get(key); if (!item) { this.stats.misses++; console.log(`Cache MISS: ${key}`); return null; } // Check if expired if (Date.now() > item.expiry) { this.cache.delete(key); this.accessTimes.delete(key); this.stats.misses++; console.log(`Cache EXPIRED: ${key}`); return null; } // Update access info item.accessed = Date.now(); item.hits++; this.accessTimes.set(key, Date.now()); this.stats.hits++; console.log(`Cache HIT: ${key}`); return item.value; } catch (error) { console.error('Cache get error:', error.message); this.stats.misses++; return null; } }
async delete(key) { try { const deleted = this.cache.delete(key); this.accessTimes.delete(key); if (deleted) { this.stats.deletes++; console.log(`Cache DELETE: ${key}`); if (this.config.enablePersistence) { await this.persistToDisk(); } } return deleted; } catch (error) { console.error('Cache delete error:', error.message); return false; } }
async clear() { try { const size = this.cache.size; this.cache.clear(); this.accessTimes.clear(); if (this.config.enablePersistence) { await this.persistToDisk(); } console.log(`Cache CLEARED: ${size} items removed`); return true; } catch (error) { console.error('Cache clear error:', error.message); return false; } }
has(key) { const item = this.cache.get(key); if (!item) return false; // Check if expired if (Date.now() > item.expiry) { this.cache.delete(key); this.accessTimes.delete(key); return false; } return true; }
keys() { const validKeys = []; const now = Date.now(); for (const [key, item] of this.cache.entries()) { if (now <= item.expiry) { validKeys.push(key); } } return validKeys; }
size() { this.cleanup(); // Clean expired items first return this.cache.size; }
evictLRU() { // Find least recently used item let oldestKey = null; let oldestTime = Date.now(); for (const [key, time] of this.accessTimes.entries()) { if (time < oldestTime) { oldestTime = time; oldestKey = key; } } if (oldestKey) { this.cache.delete(oldestKey); this.accessTimes.delete(oldestKey); console.log(`Cache LRU EVICTED: ${oldestKey}`); } }
cleanup() { const now = Date.now(); let cleanedCount = 0; for (const [key, item] of this.cache.entries()) { if (now > item.expiry) { this.cache.delete(key); this.accessTimes.delete(key); cleanedCount++; } } if (cleanedCount > 0) { this.stats.cleanups++; console.log(`Cache CLEANUP: ${cleanedCount} expired items removed`); } return cleanedCount; }
setupCleanupTimer() { this.cleanupTimer = setInterval(() => { this.cleanup(); }, this.config.cleanupInterval); }
stopCleanupTimer() { if (this.cleanupTimer) { clearInterval(this.cleanupTimer); this.cleanupTimer = null; } }
calculateSize(value) { try { return JSON.stringify(value).length; } catch (error) { return 0; } }
async persistToDisk() { try { const cacheDir = path.dirname(this.config.persistPath); if (!fs.existsSync(cacheDir)) { fs.mkdirSync(cacheDir, { recursive: true }); } const cacheData = { timestamp: Date.now(), cache: Array.from(this.cache.entries()), accessTimes: Array.from(this.accessTimes.entries()), stats: this.stats }; fs.writeFileSync(this.config.persistPath, JSON.stringify(cacheData)); } catch (error) { console.error('Cache persist error:', error.message); } }
loadFromDisk() { try { if (!fs.existsSync(this.config.persistPath)) { return; } const data = JSON.parse(fs.readFileSync(this.config.persistPath, 'utf8')); // Restore cache this.cache = new Map(data.cache || []); this.accessTimes = new Map(data.accessTimes || []); this.stats = { ...this.stats, ...data.stats }; // Clean expired items this.cleanup(); console.log('Cache loaded from disk'); } catch (error) { console.error('Cache load error:', error.message); } }
getStats() { const totalRequests = this.stats.hits + this.stats.misses; const hitRate = totalRequests > 0 ? Math.round((this.stats.hits / totalRequests) * 100) : 0; return { size: this.cache.size, hitRate: `${hitRate}%`, totalHits: this.stats.hits, totalMisses: this.stats.misses, totalSets: this.stats.sets, totalDeletes: this.stats.deletes, totalCleanups: this.stats.cleanups, totalRequests }; }
getDetailedStats() { const stats = this.getStats(); const items = []; for (const [key, item] of this.cache.entries()) { items.push({ key, size: item.size, hits: item.hits, created: new Date(item.created).toISOString(), accessed: new Date(item.accessed).toISOString(), expiresIn: Math.max(0, Math.round((item.expiry - Date.now()) / 1000)) }); } // Sort by most accessed items.sort((a, b) => b.hits - a.hits); return { ...stats, items: items.slice(0, 10) // Top 10 most accessed }; }
exportCache() { const exportData = { exportTime: new Date().toISOString(), config: this.config, stats: this.getStats(), items: Array.from(this.cache.entries()).map(([key, item]) => ({ key, value: item.value, created: new Date(item.created).toISOString(), accessed: new Date(item.accessed).toISOString(), hits: item.hits, size: item.size })) }; return exportData; }}
module.exports = CacheManager; 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202/** * Chahua Development Thailand * บริษัทชาหัวประเทศไทย * CEO: Saharath C. * www.chahuadev.com * chahuadev@gmail.com * * /** * HUB - Central Event Hub (Pub/Sub System) V.11.0.0 * * ศูนย์กลางการสื่อสารระหว่างโมดูลทั้งหมดในแอปพลิเคชัน * ทำงานในรูปแบบ Publish/Subscribe เพื่อลดการพึ่งพากัน (Decoupling) * * Features: * on(event, fn): ลงทะเบียนเพื่อ "ฟัง" เหตุการณ์ * emit(event, data): "ส่ง" เหตุการณ์ออกไปให้ผู้ฟังทั้งหมด * once(event, fn): ลงทะเบียนฟังเหตุการณ์แค่ครั้งเดียวแล้วลบออก * off(event, fn): ยกเลิกการฟังเหตุการณ์ * emitAsync(event, data): emit แบบรอให้ callback ที่เป็น async ทำงานจนเสร็จ * Wildcard Listener ('*'): ดักฟังทุกเหตุการณ์ที่เกิดขึ้นใน Hub * * by Chahuadev Studio V.11.0.0 Enterprise Architecture */
class CallbackHub { constructor() { this.handlers = {}; this.debug_mode = process.env.HUB_DEBUG === 'true' || false; console.log(' Event Hub initialized - Pub/Sub System V.11.0.0'); }
/** * ลงทะเบียนฟังก์ชัน (callback) เพื่อรอฟังเหตุการณ์ (event) * @param {string} eventName - ชื่อเหตุการณ์ที่ต้องการฟัง (เช่น 'license.loaded' หรือ '*' เพื่อฟังทุกอย่าง) * @param {Function} callback - ฟังก์ชันที่จะถูกเรียกใช้เมื่อมีเหตุการณ์เกิดขึ้น */ on(eventName, callback) { if (!this.handlers[eventName]) { this.handlers[eventName] = []; } this.handlers[eventName].push(callback); if (this.debug_mode) { console.log(` Hub: Listener registered for "${eventName}" (${this.handlers[eventName].length} total)`); } }
/** * ลงทะเบียนฟังก์ชันเพื่อรอฟังเหตุการณ์แค่ "ครั้งเดียว" * หลังจากทำงานเสร็จ callback จะถูกลบออกไปโดยอัตโนมัติ * @param {string} eventName - ชื่อเหตุการณ์ * @param {Function} callback - ฟังก์ชันที่จะถูกเรียกใช้ */ once(eventName, callback) { const onceWrapper = (data) => { callback(data); this.off(eventName, onceWrapper); if (this.debug_mode) { console.log(` Hub: Once listener for "${eventName}" executed and removed`); } }; this.on(eventName, onceWrapper); }
/** * ยกเลิกการลงทะเบียน callback * @param {string} eventName - ชื่อเหตุการณ์ * @param {Function} callback - ฟังก์ชันที่ต้องการยกเลิก */ off(eventName, callback) { if (this.handlers[eventName]) { const initialLength = this.handlers[eventName].length; this.handlers[eventName] = this.handlers[eventName].filter(cb => cb !== callback); if (this.debug_mode && this.handlers[eventName].length < initialLength) { console.log(` Hub: Listener removed from "${eventName}" (${this.handlers[eventName].length} remaining)`); } } }
/** * ส่งสัญญาณ (emit) เหตุการณ์ออกไป * จะเรียก callback ทุกตัวที่ลงทะเบียนไว้กับ event นี้แบบ non-blocking * @param {string} eventName - ชื่อเหตุการณ์ * @param {*} [data] - ข้อมูลที่ต้องการส่งไปกับเหตุการณ์ */ emit(eventName, data) { let listenersNotified = 0; // ส่งให้ผู้ฟังที่เจาะจง event นี้ if (this.handlers[eventName]) { this.handlers[eventName].forEach(fn => { try { fn(data); listenersNotified++; } catch (err) { console.error(` Hub: Callback error on "${eventName}":`, err); } }); }
// ส่งให้ผู้ฟังแบบ Wildcard ('*') ด้วย if (this.handlers['*']) { this.handlers['*'].forEach(fn => { try { fn({ event: eventName, data: data }); listenersNotified++; } catch (err) { console.error(` Hub: Wildcard callback error on "${eventName}":`, err); } }); }
if (this.debug_mode) { console.log(` Hub: Event "${eventName}" emitted to ${listenersNotified} listener(s)`); } }
/** * ส่งสัญญาณ (emit) เหตุการณ์และรอให้ callback ที่เป็น async ทำงานจนเสร็จ * @param {string} eventName - ชื่อเหตุการณ์ * @param {*} [data] - ข้อมูลที่ต้องการส่งไปกับเหตุการณ์ * @returns {Promise<void>} */ async emitAsync(eventName, data) { const promises = [];
// ผู้ฟังที่เจาะจง event if (this.handlers[eventName]) { this.handlers[eventName].forEach(fn => { promises.push(Promise.resolve().then(() => fn(data)).catch(err => { console.error(` Hub: Async callback error on "${eventName}":`, err); })); }); } // ผู้ฟังแบบ Wildcard ('*') if (this.handlers['*']) { this.handlers['*'].forEach(fn => { promises.push(Promise.resolve().then(() => fn({ event: eventName, data: data })).catch(err => { console.error(` Hub: Async wildcard callback error on "${eventName}":`, err); })); }); } if (this.debug_mode) { console.log(` Hub: Async event "${eventName}" emitted to ${promises.length} listener(s)`); } await Promise.all(promises); }
/** * แสดงรายชื่อ event ทั้งหมดที่มีการลงทะเบียนไว้ */ debug() { console.log(' Hub: Registered Event Handlers:'); for (const eventName in this.handlers) { console.log(` - ${eventName} (${this.handlers[eventName].length} listener(s))`); } const totalEvents = Object.keys(this.handlers).length; const totalListeners = Object.values(this.handlers).reduce((sum, handlers) => sum + handlers.length, 0); console.log(` Hub: Total ${totalEvents} events, ${totalListeners} listeners`); }
/** * เปิด/ปิด debug mode * @param {boolean} enabled - เปิดหรือปิด debug mode */ setDebugMode(enabled) { this.debug_mode = enabled; console.log(` Hub: Debug mode ${enabled ? 'ENABLED' : 'DISABLED'}`); }
/** * ลบ listeners ทั้งหมดของ event หนึ่งๆ * @param {string} eventName - ชื่อเหตุการณ์ที่ต้องการลบ listeners */ removeAllListeners(eventName) { if (this.handlers[eventName]) { const count = this.handlers[eventName].length; delete this.handlers[eventName]; if (this.debug_mode) { console.log(` Hub: Removed all ${count} listeners for "${eventName}"`); } } }
/** * ลบ listeners ทั้งหมด */ removeAll() { const eventCount = Object.keys(this.handlers).length; this.handlers = {}; console.log(` Hub: Removed all listeners (${eventCount} events cleared)`); }}
// สร้างและ Export เป็น Singleton Instance เพื่อให้ทุกไฟล์ได้ใช้ตัวเดียวกันmodule.exports = new CallbackHub(); 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147/* Chahua Development Thailand บริษัทชาหัวประเทศไทย CEO: Saharath C. www.chahuadev.com chahuadev@gmail.com
/** * Centralized Callback Logger V.11.0.0 * * ระบบจัดการ Log และ Event กลางแบบ Non-Blocking * * Features: * Log Levels (info, warn, error, debug) * Console Output with Colors (เพื่อง่ายต่อการอ่าน) * File Logging (บันทึก Log ลงไฟล์ logs/system.log) * Non-Blocking (ไม่รบกวนการทำงานหลักของแอปพลิเคชัน) * Singleton Pattern (ทุกโมดูลใช้ instance เดียวกัน) * Timestamp & Standardized Formatting * * by Chahuadev Studio V.11.0.0 Enterprise Architecture */
const fs = require('fs');const path = require('path');const util = require('util');
class CallbackLogger { constructor() { this.logDirectory = path.join(__dirname, '../logs'); this.logFilePath = path.join(this.logDirectory, 'system.log'); this.inMemoryLogs = []; this.maxMemoryLogs = 200; // เก็บ Log ในหน่วยความจำสูงสุด 200 รายการ
this.ensureLogDirectory(); // สร้าง Stream สำหรับเขียนไฟล์แบบ Append (เขียนต่อท้าย) this.logStream = fs.createWriteStream(this.logFilePath, { flags: 'a' });
// สีสำหรับ Console Log this.colors = { info: '\x1b[36m', // Cyan warn: '\x1b[33m', // Yellow error: '\x1b[31m', // Red debug: '\x1b[35m', // Magenta reset: '\x1b[0m' // Reset color }; this.info('logger.init', { message: 'CallbackLogger has started successfully.' }); }
/** * ตรวจสอบว่าโฟลเดอร์ logs มีอยู่จริงหรือไม่ ถ้าไม่มีให้สร้างใหม่ */ ensureLogDirectory() { if (!fs.existsSync(this.logDirectory)) { try { fs.mkdirSync(this.logDirectory, { recursive: true }); console.log(`[Logger] Created log directory at: ${this.logDirectory}`); } catch (error) { console.error(`[Logger] Failed to create log directory:`, error); } } }
/** * ฟังก์ชันหลักในการ Log (เป็น private) * @param {'info' | 'warn' | 'error' | 'debug'} level ระดับของ Log * @param {string} eventName ชื่อของ Event * @param {object | string} data ข้อมูลที่ต้องการ Log */ _log(level, eventName, data) { const timestamp = new Date().toISOString(); const icons = { info: '', warn: '', error: '', debug: '' }; const icon = icons[level] || '';
// จัดรูปแบบข้อมูลให้สวยงาม const formattedData = typeof data === 'object' ? util.inspect(data, { depth: null, colors: false }) : data; const formattedDataColor = typeof data === 'object' ? util.inspect(data, { depth: null, colors: true }) : data;
// สร้างข้อความ Log const logMessageForFile = `[${timestamp}] [${level.toUpperCase()}] [${eventName}] ${formattedData}`; const logMessageForConsole = `${this.colors[level]}[${timestamp}] ${icon} [${level.toUpperCase()}] [${eventName}]${this.colors.reset} ${formattedDataColor}`;
// 1. แสดงผลใน Console console.log(logMessageForConsole);
// 2. เขียนลงไฟล์ this.logStream.write(logMessageForFile + '\n', (err) => { if (err) console.error('[Logger] Failed to write to log file:', err); });
// 3. เก็บในหน่วยความจำ (สำหรับเรียกดูย้อนหลัง) this.inMemoryLogs.push(logMessageForFile); if (this.inMemoryLogs.length > this.maxMemoryLogs) { this.inMemoryLogs.shift(); // ลบอันเก่าสุดออก } }
/** * Log ข้อมูลทั่วไป * @param {string} eventName ชื่อ Event (เช่น 'i18n.loaded') * @param {object|string} data ข้อมูล */ info(eventName, data) { this._log('info', eventName, data); }
/** * Log คำเตือน * @param {string} eventName ชื่อ Event (เช่น 'license.expiring') * @param {object|string} data ข้อมูล */ warn(eventName, data) { this._log('warn', eventName, data); }
/** * Log ข้อผิดพลาด * @param {string} eventName ชื่อ Event (เช่น 'database.connection.failed') * @param {object|string} data ข้อมูล */ error(eventName, data) { this._log('error', eventName, data); } /** * Log ข้อมูลสำหรับการดีบัก * @param {string} eventName ชื่อ Event (เช่น 'user.data.raw') * @param {object|string} data ข้อมูล */ debug(eventName, data) { this._log('debug', eventName, data); }
/** * ดึง Log ล่าสุดจากหน่วยความจำ * @param {number} limit จำนวนที่ต้องการ * @returns {string[]} */ getRecentLogs(limit = 20) { return this.inMemoryLogs.slice(-limit); }}
// สร้างและ Export เป็น Singleton Instance เพื่อให้ทุกไฟล์ได้ใช้ตัวเดียวกันmodule.exports = new CallbackLogger();123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301#!/usr/bin/env node
/** * Chahuadev Framework - CLI Interface * Chahua Development Thailand * CEO: Saharath C. * * Purpose: Command Line Interface สำหรับ automation และ integration */
const { program } = require('commander');const path = require('path');const fs = require('fs');
// Import core modules (same as app.js)const ValidationGateway = require('./validation_gateway');const ContextManager = require('./modules/context-manager');const ErrorHandler = require('./modules/error-handler');const Executor = require('./modules/executor');const SystemDetector = require('./modules/system-detector');const PluginManager = require('./modules/plugin-manager');
class ChahuadevCLI { constructor() { this.validationGateway = new ValidationGateway(); this.contextManager = new ContextManager(); this.errorHandler = new ErrorHandler(); this.executor = new Executor(); this.systemDetector = new SystemDetector(); this.pluginManager = new PluginManager(); console.log(' Chahuadev CLI initialized'); }
async initialize() { try { // Load plugins await this.pluginManager.loadPlugins(); console.log(' CLI ready with all modules loaded'); } catch (error) { console.error(' CLI initialization failed:', error.message); process.exit(1); } }
async executeCommand(command, options = {}) { const context = this.contextManager.create('cli-execution', { command, options, timestamp: new Date().toISOString(), cwd: process.cwd() });
try { // Validate request const validation = await this.validationGateway.validateRequest({ command, ...options });
if (!validation.success) { throw new Error(`Security validation failed: ${validation.error}`); }
// Execute through executor const result = await this.executor.execute({ command, project: options.project || process.cwd(), strategy: options.strategy }, context);
return result;
} catch (error) { this.errorHandler.handle(error, context.id); throw error; } }
async scanProject(projectPath) { try { const fullPath = path.resolve(projectPath); if (!fs.existsSync(fullPath)) { throw new Error(`Project path does not exist: ${fullPath}`); }
const detection = await this.systemDetector.detectProject(fullPath); console.log('\n Project Scan Results:'); console.log('========================'); console.log('Project Path:', fullPath); console.log('Detected Type:', detection.type); console.log('Confidence:', `${(detection.confidence * 100).toFixed(1)}%`); console.log('Strategy:', detection.strategy); if (detection.details) { console.log('\n Details:'); Object.entries(detection.details).forEach(([key, value]) => { console.log(` ${key}: ${value}`); }); }
return detection;
} catch (error) { console.error(' Project scan failed:', error.message); throw error; } }
async listPlugins() { try { const plugins = this.pluginManager.getAvailablePlugins(); console.log('\n Available Plugins:'); console.log('===================='); if (plugins.length === 0) { console.log('No plugins loaded'); return; }
plugins.forEach(plugin => { console.log(` ${plugin.name}`); console.log(` File: ${plugin.filename}`); console.log(` Status: ${plugin.status}`); console.log(` Loaded: ${plugin.loadedAt.toISOString()}`); if (plugin.metadata.description) { console.log(` Description: ${plugin.metadata.description}`); } console.log(''); });
return plugins;
} catch (error) { console.error(' Failed to list plugins:', error.message); throw error; } }
async executePlugin(pluginName, data) { try { const result = await this.pluginManager.executePlugin(pluginName, data); if (result.success) { console.log(` Plugin ${pluginName} executed successfully`); console.log('Result:', JSON.stringify(result.result, null, 2)); } else { console.error(` Plugin ${pluginName} failed: ${result.error}`); }
return result;
} catch (error) { console.error(' Plugin execution failed:', error.message); throw error; } }
async getStatus() { const status = { framework: 'Chahuadev Framework', version: '1.0.0', interface: 'CLI', timestamp: new Date().toISOString(), modules: { validationGateway: !!this.validationGateway, contextManager: !!this.contextManager, errorHandler: !!this.errorHandler, executor: !!this.executor, systemDetector: !!this.systemDetector, pluginManager: !!this.pluginManager }, plugins: this.pluginManager.getPluginStats() };
console.log('\n System Status:'); console.log('================'); console.log(JSON.stringify(status, null, 2));
return status; }}
// CLI Commands Setupasync function setupCommands() { const cli = new ChahuadevCLI(); await cli.initialize();
program .name('chahuadev') .description('Chahuadev Framework CLI') .version('1.0.0');
// Execute command program .command('execute <command>') .description('Execute a command through the framework') .option('-p, --project <path>', 'Project path', process.cwd()) .option('-s, --strategy <strategy>', 'Force specific strategy') .action(async (command, options) => { try { console.log(` Executing: ${command}`); const result = await cli.executeCommand(command, options); console.log(' Execution completed'); console.log(JSON.stringify(result, null, 2)); } catch (error) { console.error(' Execution failed:', error.message); process.exit(1); } });
// Scan project program .command('scan <path>') .description('Scan project and detect type') .action(async (projectPath) => { try { await cli.scanProject(projectPath); } catch (error) { console.error(' Scan failed:', error.message); process.exit(1); } });
// Plugin management program .command('plugins') .description('List available plugins') .action(async () => { try { await cli.listPlugins(); } catch (error) { console.error(' Failed to list plugins:', error.message); process.exit(1); } });
program .command('plugin <name>') .description('Execute a plugin') .option('-d, --data <data>', 'JSON data to pass to plugin', '{}') .action(async (name, options) => { try { const data = JSON.parse(options.data); await cli.executePlugin(name, data); } catch (error) { console.error(' Plugin execution failed:', error.message); process.exit(1); } });
// Status program .command('status') .description('Show system status') .action(async () => { try { await cli.getStatus(); } catch (error) { console.error(' Failed to get status:', error.message); process.exit(1); } });
// Help command program .command('help') .description('Show help information') .action(() => { console.log('\n Chahuadev Framework CLI'); console.log('==========================='); console.log('Usage examples:'); console.log(''); console.log(' chahuadev execute "npm test" # Execute npm test'); console.log(' chahuadev execute "node app.js" -p ./src # Execute in specific project'); console.log(' chahuadev scan ./my-project # Scan project type'); console.log(' chahuadev plugins # List available plugins'); console.log(' chahuadev plugin zip-compressor # Execute plugin'); console.log(' chahuadev status # Show system status'); console.log(''); program.help(); });
return { cli, program };}
// Main executionif (require.main === module) { setupCommands().then(({ program }) => { // Parse command line arguments program.parse(); }).catch(error => { console.error(' CLI setup failed:', error.message); process.exit(1); });}
module.exports = { ChahuadevCLI, setupCommands }; 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368/** * Chahuadev Framework - Context Manager Module * Pipeline Context Object Management & Data Flow Tracking * * Chahua Development Thailand * CEO: Saharath C. * www.chahuadev.com */
const crypto = require('crypto');
class ContextManager { constructor() { this.contexts = new Map(); // Store active contexts console.log(' Context Manager initialized'); }
/** * Create new pipeline context * @param {string} pipelineType - Type of pipeline (e.g., 'execution', 'api', 'validation') * @param {Object} initialData - Initial request data * @returns {Object} Pipeline context object */ create(pipelineType = 'execution', initialData = {}) { const pipelineId = this.generatePipelineId(); const timestamp = new Date().toISOString();
const context = { // Pipeline identification pipelineId: pipelineId, pipelineType: pipelineType, timestamp: timestamp, // Request information request: { command: initialData.command || '', originalData: initialData || {}, parameters: this.parseParameters(initialData), source: initialData.source || 'unknown' },
// System information (will be populated by system-detector) systemInfo: { detectedType: null, projectPath: null, strategy: null, dependencies: [], environment: process.env.NODE_ENV || 'development' },
// Security context security: { keyHash: null, permissionLevel: 'basic', userSession: null, securityChecks: [], validatedAt: null },
// Execution tracking execution: { strategy: null, startTime: null, endTime: null, status: 'pending', // 'pending', 'running', 'completed', 'failed' exitCode: null, output: null },
// Step tracking steps: [],
// Performance metrics performance: { totalTime: null, memoryUsage: process.memoryUsage(), cacheHit: false, stepTimings: {} },
// Error tracking error: null,
// Metadata metadata: { createdAt: timestamp, updatedAt: timestamp, version: '1.0.0', framework: 'chahuadev' } };
// Store context for tracking this.contexts.set(pipelineId, context); console.log(` Context created: ${pipelineId} (${pipelineType})`); return context; }
/** * Add step result to context * @param {Object} context - Pipeline context * @param {string} stepName - Name of the step * @param {string} status - Step status ('started', 'completed', 'failed') * @param {*} result - Step result data * @returns {Object} Updated context */ addStep(context, stepName, status, result = null) { if (!context || !context.pipelineId) { throw new Error('Invalid context provided'); }
const step = { stepName: stepName, timestamp: new Date().toISOString(), status: status, result: result, duration: null };
// Calculate duration if completing a step if (status === 'completed' || status === 'failed') { const startStep = context.steps.find(s => s.stepName === stepName && s.status === 'started' ); if (startStep) { step.duration = Date.now() - new Date(startStep.timestamp).getTime(); context.performance.stepTimings[stepName] = step.duration; } }
context.steps.push(step); context.metadata.updatedAt = new Date().toISOString();
console.log(` Step added: ${stepName} (${status}) to ${context.pipelineId}`); return context; }
/** * Update context security information * @param {Object} context - Pipeline context * @param {Object} securityData - Security validation data * @returns {Object} Updated context */ updateSecurity(context, securityData) { if (!context || !context.pipelineId) { throw new Error('Invalid context provided'); }
context.security = { ...context.security, ...securityData, validatedAt: new Date().toISOString() };
context.metadata.updatedAt = new Date().toISOString(); console.log(` Security updated for: ${context.pipelineId}`); return context; }
/** * Update system information * @param {Object} context - Pipeline context * @param {Object} systemData - System detection data * @returns {Object} Updated context */ updateSystemInfo(context, systemData) { if (!context || !context.pipelineId) { throw new Error('Invalid context provided'); }
context.systemInfo = { ...context.systemInfo, ...systemData };
context.metadata.updatedAt = new Date().toISOString(); console.log(` System info updated for: ${context.pipelineId}`); return context; }
/** * Update execution status * @param {Object} context - Pipeline context * @param {string} status - Execution status * @param {*} output - Execution output * @param {number} exitCode - Exit code * @returns {Object} Updated context */ updateExecution(context, status, output = null, exitCode = null) { if (!context || !context.pipelineId) { throw new Error('Invalid context provided'); }
// Set start time when execution begins if (status === 'running' && !context.execution.startTime) { context.execution.startTime = new Date().toISOString(); }
// Set end time when execution completes or fails if ((status === 'completed' || status === 'failed') && !context.execution.endTime) { context.execution.endTime = new Date().toISOString(); // Calculate total time if (context.execution.startTime) { const startTime = new Date(context.execution.startTime).getTime(); const endTime = new Date(context.execution.endTime).getTime(); context.performance.totalTime = endTime - startTime; } }
context.execution.status = status; if (output !== null) context.execution.output = output; if (exitCode !== null) context.execution.exitCode = exitCode; context.metadata.updatedAt = new Date().toISOString(); console.log(` Execution updated: ${status} for ${context.pipelineId}`); return context; }
/** * Set error in context * @param {Object} context - Pipeline context * @param {Error|string} error - Error object or message * @returns {Object} Updated context */ setError(context, error) { if (!context || !context.pipelineId) { throw new Error('Invalid context provided'); }
const errorInfo = { message: error.message || error, stack: error.stack || null, timestamp: new Date().toISOString(), step: context.steps.length > 0 ? context.steps[context.steps.length - 1].stepName : 'unknown' };
context.error = errorInfo; context.execution.status = 'failed'; context.metadata.updatedAt = new Date().toISOString(); console.error(` Error set for ${context.pipelineId}:`, errorInfo.message); return context; }
/** * Get context by pipeline ID * @param {string} pipelineId - Pipeline ID * @returns {Object|null} Context object or null if not found */ get(pipelineId) { return this.contexts.get(pipelineId) || null; }
/** * Remove context (cleanup) * @param {string} pipelineId - Pipeline ID * @returns {boolean} True if removed */ remove(pipelineId) { const removed = this.contexts.delete(pipelineId); if (removed) { console.log(` Context removed: ${pipelineId}`); } return removed; }
/** * Clear context by execution ID (alias for remove) * @param {string} executionId - Execution ID * @returns {boolean} True if removed */ clearContext(executionId) { return this.remove(executionId); }
/** * Create context object (for BaseStrategy compatibility) * @param {Object} data - Context data * @returns {Object} Context object */ createContext(data) { return data; // Return as-is since BaseStrategy creates its own context }
/** * Generate unique pipeline ID * @private * @returns {string} Pipeline ID */ generatePipelineId() { const timestamp = Date.now(); const random = crypto.randomBytes(4).toString('hex'); return `pipe_${timestamp}_${random}`; }
/** * Parse parameters from initial data * @private * @param {Object} data - Initial data * @returns {Object} Parsed parameters */ parseParameters(data) { if (!data || typeof data !== 'object') { return {}; }
// Extract common parameters return { timeout: data.timeout || 30000, retry: data.retry || false, maxRetries: data.maxRetries || 3, silent: data.silent || false, workingDir: data.workingDir || process.cwd() }; }
/** * Get all active contexts (for monitoring) * @returns {Array} Array of context objects */ getAll() { return Array.from(this.contexts.values()); }
/** * Clean up old contexts (older than specified minutes) * @param {number} maxAgeMinutes - Maximum age in minutes * @returns {number} Number of cleaned contexts */ cleanup(maxAgeMinutes = 60) { const cutoffTime = Date.now() - (maxAgeMinutes * 60 * 1000); let cleaned = 0;
for (const [pipelineId, context] of this.contexts.entries()) { const contextTime = new Date(context.metadata.createdAt).getTime(); if (contextTime < cutoffTime) { this.contexts.delete(pipelineId); cleaned++; } }
if (cleaned > 0) { console.log(` Cleaned up ${cleaned} old contexts`); }
return cleaned; }
/** * Get context manager status * @returns {Object} Status information */ getStatus() { return { activeContexts: this.contexts.size, memoryUsage: process.memoryUsage(), ready: true }; }}
// Export class (not singleton)module.exports = ContextManager; 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380/** * Chahuadev Framework - Error Handler Module * Error Detection, Logging & Debugging Support * * Chahua Development Thailand * CEO: Saharath C. * www.chahuadev.com */
const fs = require('fs');const path = require('path');
class ErrorHandler { constructor() { this.errorTypes = { VALIDATION: 'validation', SECURITY: 'security', EXECUTION: 'execution', SYSTEM: 'system', NETWORK: 'network', BRIDGE: 'bridge', CONTEXT: 'context' };
this.logFile = path.join(process.cwd(), 'logs', 'errors.log'); this.debugMode = process.env.DEBUG === 'true' || process.env.NODE_ENV === 'development'; this.ensureLogDirectory(); console.log(' Error Handler initialized'); }
/** * Handle and log error * @param {Error|string} error - Error object or message * @param {string} type - Error type * @param {Object} context - Pipeline context * @param {Object} metadata - Additional metadata * @returns {Object} Processed error info */ handle(error, type = this.errorTypes.SYSTEM, context = null, metadata = {}) { const errorInfo = this.processError(error, type, context, metadata); // Log error this.log(errorInfo); // Console output based on debug mode if (this.debugMode) { this.debugOutput(errorInfo); } else { console.error(` ${errorInfo.type}: ${errorInfo.message}`); }
return errorInfo; }
/** * Process error into standardized format * @private * @param {Error|string} error - Error object or message * @param {string} type - Error type * @param {Object} context - Pipeline context * @param {Object} metadata - Additional metadata * @returns {Object} Processed error info */ processError(error, type, context, metadata) { const timestamp = new Date().toISOString(); const errorId = this.generateErrorId();
let errorInfo = { id: errorId, timestamp: timestamp, type: type, message: '', stack: null, code: null, details: {}, context: null, metadata: metadata || {} };
// Extract error information if (error instanceof Error) { errorInfo.message = error.message; errorInfo.stack = error.stack; errorInfo.code = error.code || null; // Extract additional error properties if (error.errno) errorInfo.details.errno = error.errno; if (error.syscall) errorInfo.details.syscall = error.syscall; if (error.path) errorInfo.details.path = error.path; } else { errorInfo.message = String(error); }
// Add context information if (context) { errorInfo.context = { pipelineId: context.pipelineId, pipelineType: context.pipelineType, currentStep: context.steps.length > 0 ? context.steps[context.steps.length - 1].stepName : 'unknown', executionStatus: context.execution.status, systemType: context.systemInfo.detectedType }; }
// Add environment information errorInfo.environment = { nodeVersion: process.version, platform: process.platform, arch: process.arch, memory: process.memoryUsage(), uptime: process.uptime() };
return errorInfo; }
/** * Log error to file * @private * @param {Object} errorInfo - Processed error information */ log(errorInfo) { try { const logEntry = JSON.stringify(errorInfo) + '\n'; fs.appendFileSync(this.logFile, logEntry, 'utf8'); } catch (logError) { console.error('Failed to write error log:', logError.message); } }
/** * Debug output to console * @private * @param {Object} errorInfo - Processed error information */ debugOutput(errorInfo) { console.error('\n=== CHAHUADEV ERROR DEBUG ==='); console.error(` Error ID: ${errorInfo.id}`); console.error(` Timestamp: ${errorInfo.timestamp}`); console.error(` Type: ${errorInfo.type}`); console.error(` Message: ${errorInfo.message}`); if (errorInfo.context) { console.error(` Pipeline: ${errorInfo.context.pipelineId}`); console.error(` Step: ${errorInfo.context.currentStep}`); } if (errorInfo.stack && this.debugMode) { console.error(` Stack Trace:\n${errorInfo.stack}`); } if (Object.keys(errorInfo.details).length > 0) { console.error(' Details:', errorInfo.details); } console.error('========================\n'); }
/** * Create validation error * @param {string} message - Error message * @param {Object} context - Pipeline context * @param {Object} validationData - Validation specific data * @returns {Object} Error info */ validation(message, context = null, validationData = {}) { return this.handle( new Error(message), this.errorTypes.VALIDATION, context, { validationData } ); }
/** * Create security error * @param {string} message - Error message * @param {Object} context - Pipeline context * @param {Object} securityData - Security specific data * @returns {Object} Error info */ security(message, context = null, securityData = {}) { return this.handle( new Error(message), this.errorTypes.SECURITY, context, { securityData } ); }
/** * Create execution error * @param {string} message - Error message * @param {Object} context - Pipeline context * @param {Object} executionData - Execution specific data * @returns {Object} Error info */ execution(message, context = null, executionData = {}) { return this.handle( new Error(message), this.errorTypes.EXECUTION, context, { executionData } ); }
/** * Create bridge communication error * @param {string} message - Error message * @param {Object} context - Pipeline context * @param {Object} bridgeData - Bridge specific data * @returns {Object} Error info */ bridge(message, context = null, bridgeData = {}) { return this.handle( new Error(message), this.errorTypes.BRIDGE, context, { bridgeData } ); }
/** * Create context error * @param {string} message - Error message * @param {Object} context - Pipeline context * @param {Object} contextData - Context specific data * @returns {Object} Error info */ context(message, context = null, contextData = {}) { return this.handle( new Error(message), this.errorTypes.CONTEXT, context, { contextData } ); }
/** * Wrap function with error handling * @param {Function} fn - Function to wrap * @param {string} errorType - Error type for this function * @param {Object} context - Pipeline context * @returns {Function} Wrapped function */ wrap(fn, errorType = this.errorTypes.SYSTEM, context = null) { return async (...args) => { try { return await fn(...args); } catch (error) { this.handle(error, errorType, context, { functionName: fn.name, arguments: args.length }); throw error; // Re-throw for upstream handling } }; }
/** * Get recent errors * @param {number} limit - Number of recent errors to get * @param {string} type - Filter by error type * @returns {Array} Array of error objects */ getRecentErrors(limit = 10, type = null) { try { if (!fs.existsSync(this.logFile)) { return []; }
const logContent = fs.readFileSync(this.logFile, 'utf8'); const lines = logContent.trim().split('\n').filter(line => line); let errors = lines.map(line => { try { return JSON.parse(line); } catch (e) { return null; } }).filter(error => error !== null);
// Filter by type if specified if (type) { errors = errors.filter(error => error.type === type); }
// Sort by timestamp (newest first) and limit return errors .sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp)) .slice(0, limit); } catch (error) { console.error('Failed to read error log:', error.message); return []; } }
/** * Clear error logs * @returns {boolean} Success status */ clearLogs() { try { if (fs.existsSync(this.logFile)) { fs.writeFileSync(this.logFile, '', 'utf8'); console.log(' Error logs cleared'); return true; } return true; } catch (error) { console.error('Failed to clear error logs:', error.message); return false; } }
/** * Generate unique error ID * @private * @returns {string} Error ID */ generateErrorId() { const timestamp = Date.now(); const random = Math.random().toString(36).substring(2, 8); return `err_${timestamp}_${random}`; }
/** * Ensure log directory exists * @private */ ensureLogDirectory() { const logDir = path.dirname(this.logFile); if (!fs.existsSync(logDir)) { try { fs.mkdirSync(logDir, { recursive: true }); } catch (error) { console.warn('Could not create log directory:', error.message); } } }
/** * Get error handler status * @returns {Object} Status information */ getStatus() { return { errorTypes: Object.values(this.errorTypes), logFile: this.logFile, debugMode: this.debugMode, logExists: fs.existsSync(this.logFile), ready: true }; }
/** * Set debug mode * @param {boolean} enabled - Enable debug mode */ setDebugMode(enabled) { this.debugMode = enabled; console.log(` Debug mode: ${enabled ? 'enabled' : 'disabled'}`); }
/** * Log error with type and metadata (for BaseStrategy compatibility) * @param {string} type - Error type * @param {Error|string} error - Error object or message * @param {Object} metadata - Additional metadata */ logError(type, error, metadata = {}) { this.handle(error, type, null, metadata); }}
// Export class (not singleton)module.exports = ErrorHandler; 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242/** * executor.js - Execution Strategy Manager (Level 5) * สำหรับ Chahuadev Framework * * ใช้: system-detector.js (Level 4), validation_gateway.js (Level 4) * จัดการ: Strategy selection, execution flow, error handling */
const SystemDetector = require('./system-detector');const ErrorHandler = require('./error-handler');const ContextManager = require('./context-manager');
class Executor { constructor() { this.systemDetector = new SystemDetector(); this.errorHandler = new ErrorHandler(); this.contextManager = new ContextManager(); this.executionHistory = []; this.maxHistorySize = 100; console.log(' Executor initialized - ready for strategy execution'); }
/** * Main execution method */ async execute(request) { const executionId = this.generateExecutionId(); const startTime = Date.now(); try { console.log(` Starting execution [${executionId}]`); // Phase 1: Use request as-is (validation done by ValidationGateway) const validationResult = { success: true, sessionId: 'exec_' + Date.now(), userId: request.userId || 'system', permissions: request.permissions || 'admin', level: 'admin' }; // Phase 2: Context Preparation const executionContext = this.prepareExecutionContext(request, executionId, validationResult); // Phase 3: System Detection const detectionResult = await this.systemDetector.detect( executionContext.projectPath, executionContext ); // Phase 4: Strategy Execution const executionResult = await this.executeWithStrategy( detectionResult.strategy, executionContext ); // Phase 5: Result Processing const finalResult = this.processExecutionResult( executionResult, detectionResult, executionContext, startTime ); this.recordExecution(finalResult); console.log(` Execution completed [${executionId}] in ${finalResult.totalDuration}ms`); return finalResult;
} catch (error) { console.log(` Execution failed [${executionId}]: ${error.message}`); const errorResult = this.handleExecutionError(error, request, executionId, startTime); this.recordExecution(errorResult); return errorResult; } }
/** * เตรียม execution context */ prepareExecutionContext(request, executionId, validationResult) { // จัดการ command และ args let fullCommand; if (request.args && Array.isArray(request.args) && request.args.length > 0) { // ถ้ามี args แยกมา ให้รวมกับ command fullCommand = `${request.command} ${request.args.join(' ')}`; } else { // ถ้าไม่มี args ใช้ command ตรงๆ fullCommand = request.command; }
const context = this.contextManager.createContext({ executionId: executionId, command: fullCommand, originalCommand: request.command, // เก็บ command เดิมไว้ args: request.args || [], // เก็บ args แยกไว้ projectPath: request.projectPath || process.cwd(), options: request.options || {}, sessionId: validationResult.sessionId, userId: validationResult.userId, permissions: validationResult.permissions, timestamp: Date.now(), platform: process.platform, nodeVersion: process.version, isSecure: validationResult.success, validationLevel: validationResult.level });
console.log(` Execution context prepared: ${context.executionId}`); return context; }
/** * รัน command ด้วย strategy */ async executeWithStrategy(strategy, executionContext) { console.log(` Executing with strategy: ${strategy.name}`); const strategyStatus = await strategy.getStatus(); if (strategyStatus.status !== 'READY') { throw new Error(`Strategy not ready: ${strategy.name}`); } const result = await strategy.execute(executionContext); console.log(` Strategy execution completed: ${strategy.name}`); return result; }
/** * ประมวลผลผลลัพธ์ */ processExecutionResult(executionResult, detectionResult, executionContext, startTime) { return { success: executionResult.success, executionId: executionContext.executionId, command: executionContext.command, projectPath: executionContext.projectPath, strategy: detectionResult.type, confidence: detectionResult.confidence, output: executionResult.output, exitCode: executionResult.exitCode, error: executionResult.error, totalDuration: Date.now() - startTime, strategyDuration: executionResult.duration, sessionId: executionContext.sessionId, userId: executionContext.userId, timestamp: startTime, platform: executionContext.platform }; }
/** * จัดการ error */ handleExecutionError(error, request, executionId, startTime) { this.errorHandler.logError('EXECUTION_FAILED', error, { executionId: executionId, request: request });
return { success: false, executionId: executionId, error: error.message, command: request.command, projectPath: request.projectPath, totalDuration: Date.now() - startTime, timestamp: startTime, errorType: error.constructor.name }; }
/** * บันทึก execution history */ recordExecution(result) { this.executionHistory.unshift(result); if (this.executionHistory.length > this.maxHistorySize) { this.executionHistory = this.executionHistory.slice(0, this.maxHistorySize); } console.log(` Execution recorded: ${result.executionId}`); }
/** * รัน command แบบง่าย */ async run(command, projectPath = process.cwd(), options = {}) { return this.execute({ command: command, projectPath: projectPath, options: options }); }
/** * รายงานสถานะ */ async getStatus() { const systemStatus = await this.systemDetector.getStatus(); return { executor: 'ExecutionManager', status: 'READY', components: { systemDetector: systemStatus }, executionHistory: { total: this.executionHistory.length, successful: this.executionHistory.filter(r => r.success).length, failed: this.executionHistory.filter(r => !r.success).length }, timestamp: Date.now() }; }
/** * สร้าง execution ID */ generateExecutionId() { return `exec_${Date.now()}_${Math.random().toString(36).substring(2, 8)}`; }
/** * ดู execution history */ getHistory(limit = 10) { return this.executionHistory.slice(0, limit); }
/** * ล้าง history */ clearHistory() { this.executionHistory = []; console.log(' Execution history cleared'); }}
module.exports = Executor; 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207/** * Health Monitor - ระบบตรวจสอบสุขภาพ * Chahua Development Thailand * CEO: Saharath C. * * Purpose: ตรวจสอบสุขภาพของระบบและ components */
const os = require('os');const fs = require('fs').promises;
class HealthMonitor { constructor(options = {}) { this.config = { checkInterval: options.checkInterval || 30000, // 30 seconds thresholds: { cpu: options.cpuThreshold || 80, memory: options.memoryThreshold || 80, disk: options.diskThreshold || 90 } }; this.healthStatus = { system: 'healthy', components: {}, lastCheck: null, uptime: process.uptime() }; this.isMonitoring = false; console.log(' Health Monitor initialized'); }
async startMonitoring() { if (this.isMonitoring) { console.log(' Health monitoring already running'); return; }
this.isMonitoring = true; console.log(' Starting health monitoring...'); // Initial health check await this.performHealthCheck(); // Start periodic monitoring this.monitoringInterval = setInterval(async () => { await this.performHealthCheck(); }, this.config.checkInterval); }
stopMonitoring() { if (this.monitoringInterval) { clearInterval(this.monitoringInterval); this.monitoringInterval = null; } this.isMonitoring = false; console.log(' Health monitoring stopped'); }
async performHealthCheck() { const checkStart = Date.now(); try { const systemHealth = await this.checkSystemHealth(); const componentsHealth = await this.checkComponentsHealth(); this.healthStatus = { system: this.determineOverallHealth(systemHealth, componentsHealth), systemMetrics: systemHealth, components: componentsHealth, lastCheck: new Date().toISOString(), uptime: process.uptime(), checkDuration: Date.now() - checkStart }; if (this.healthStatus.system !== 'healthy') { console.warn(` System health: ${this.healthStatus.system}`); } } catch (error) { console.error(' Health check failed:', error.message); this.healthStatus.system = 'critical'; this.healthStatus.error = error.message; } }
async checkSystemHealth() { const cpuUsage = await this.getCPUUsage(); const memoryUsage = this.getMemoryUsage(); const diskUsage = await this.getDiskUsage(); return { cpu: { usage: cpuUsage, status: cpuUsage > this.config.thresholds.cpu ? 'warning' : 'healthy' }, memory: { usage: memoryUsage, status: memoryUsage > this.config.thresholds.memory ? 'warning' : 'healthy' }, disk: { usage: diskUsage, status: diskUsage > this.config.thresholds.disk ? 'warning' : 'healthy' } }; }
async checkComponentsHealth() { const components = {}; // Check if key modules are responding try { components.fileSystem = await this.checkFileSystemAccess(); components.network = await this.checkNetworkConnectivity(); components.nodeVersion = this.checkNodeVersion(); } catch (error) { console.error('Component health check error:', error.message); } return components; }
async getCPUUsage() { return new Promise((resolve) => { const startUsage = process.cpuUsage(); setTimeout(() => { const endUsage = process.cpuUsage(startUsage); const totalUsage = (endUsage.user + endUsage.system) / 1000; // Convert to ms const usage = Math.round((totalUsage / 100) * 100) / 100; // Percentage estimation resolve(Math.min(usage, 100)); }, 100); }); }
getMemoryUsage() { const used = process.memoryUsage(); const total = os.totalmem(); return Math.round((used.rss / total) * 100); }
async getDiskUsage() { try { const stats = await fs.stat(process.cwd()); // Simple disk usage estimation (this is platform-dependent) return 50; // Return a safe default } catch (error) { return 0; } }
async checkFileSystemAccess() { try { await fs.access(process.cwd(), fs.constants.R_OK | fs.constants.W_OK); return { status: 'healthy', message: 'File system accessible' }; } catch (error) { return { status: 'critical', message: 'File system access failed' }; } }
async checkNetworkConnectivity() { // Simple network check return { status: 'healthy', message: 'Network connectivity assumed OK' }; }
checkNodeVersion() { const version = process.version; const majorVersion = parseInt(version.split('.')[0].substring(1)); return { version: version, status: majorVersion >= 16 ? 'healthy' : 'warning', message: majorVersion >= 16 ? 'Node.js version OK' : 'Node.js version may be outdated' }; }
determineOverallHealth(systemHealth, componentsHealth) { // Check for critical issues if (Object.values(componentsHealth).some(c => c.status === 'critical')) { return 'critical'; } if (Object.values(systemHealth).some(s => s.status === 'warning')) { return 'warning'; } if (Object.values(componentsHealth).some(c => c.status === 'warning')) { return 'warning'; } return 'healthy'; }
getHealthStatus() { return this.healthStatus; }
getSimpleStatus() { return { status: this.healthStatus.system, uptime: this.healthStatus.uptime, lastCheck: this.healthStatus.lastCheck }; }}
module.exports = HealthMonitor; 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167/** * Chahuadev Framework - Key System Module (Testing Only) * JWT Key Management + Security System * * DEPRECATED: This module is used for testing purposes only. * For license validation, use: ./chahua-license-system * * Chahua Development Thailand * CEO: Saharath C. * www.chahuadev.com * * @deprecated Use Chahua License System for production license validation * @usecase Testing and JWT token generation for test scenarios */
const crypto = require('crypto');const jwt = require('jsonwebtoken');
class KeySystem { constructor() { // JWT Secret from environment variable (required for security) this.jwtSecret = process.env.JWT_SECRET || 'chahuadev-framework-super-secret-key-for-development-2025-v1.0.0-thailand'; this.algorithm = 'HS256'; this.defaultExpiry = '1h'; console.log(' Key System initialized'); if (!process.env.JWT_SECRET) { console.warn(' Warning: Using fallback JWT secret. Set JWT_SECRET environment variable for production!'); } }
/** * Generate JWT token for authentication * @param {Object} payload - Data to encode in token * @param {string} expiresIn - Token expiry time * @returns {string} JWT token */ generateToken(payload = {}, expiresIn = this.defaultExpiry) { try { const tokenPayload = { ...payload, iat: Math.floor(Date.now() / 1000), iss: 'chahuadev-framework' };
const token = jwt.sign(tokenPayload, this.jwtSecret, { algorithm: this.algorithm, expiresIn: expiresIn });
console.log(' JWT token generated successfully'); return token; } catch (error) { console.error(' JWT generation failed:', error.message); throw new Error('Failed to generate JWT token'); } }
/** * Verify and decode JWT token * @param {string} token - JWT token to verify * @returns {Object} Decoded payload */ verifyToken(token) { try { if (!token) { throw new Error('Token is required'); }
const decoded = jwt.verify(token, this.jwtSecret, { algorithms: [this.algorithm] });
console.log(' JWT token verified successfully'); return decoded; } catch (error) { console.error(' JWT verification failed:', error.message); throw new Error(`Invalid token: ${error.message}`); } }
/** * Generate API key for bridge communication * @returns {string} API key */ generateApiKey() { const apiKey = crypto.randomBytes(32).toString('hex'); console.log(' API key generated'); return apiKey; }
/** * Hash sensitive data * @param {string} data - Data to hash * @returns {string} Hashed data */ hashData(data) { if (!data) { throw new Error('Data is required for hashing'); }
const hash = crypto.createHash('sha256') .update(data) .digest('hex'); return hash; }
/** * Generate secure random string * @param {number} length - Length of random string * @returns {string} Random string */ generateSecureRandom(length = 16) { return crypto.randomBytes(Math.ceil(length / 2)) .toString('hex') .slice(0, length); }
/** * Check if token is expired (without throwing error) * @param {string} token - JWT token to check * @returns {boolean} True if expired */ isTokenExpired(token) { try { this.verifyToken(token); return false; } catch (error) { return error.message.includes('expired'); } }
/** * Extract payload without verification (for debugging) * @param {string} token - JWT token * @returns {Object} Decoded payload (without verification) */ decodeTokenUnsafe(token) { try { return jwt.decode(token); } catch (error) { return null; } }
/** * Get key system status * @returns {Object} Status information */ getStatus() { return { algorithm: this.algorithm, hasJwtSecret: !!process.env.JWT_SECRET, defaultExpiry: this.defaultExpiry, ready: true }; }}
// Export class (not singleton)module.exports = KeySystem; 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596/** * Plugin Manager (V4 - Correct Pathing) * Chahua Development Thailand * Purpose: โหลดและจัดการ plugins ผ่าน chahua.json manifest เท่านั้น * แก้ไข: กำหนด Path ของ plugins ให้ถูกต้องทั้งในโหมด Dev และ Production */const fs = require('fs');const path = require('path');const os = require('os');
class PluginManager { constructor() { this.projectFeatures = new Map();
// --- ส่วน Path Detection ที่แก้ไขใหม่ให้ถูกต้อง 100% ---const { app } = require('electron');
if (app.isPackaged) { // Production Mode: ใช้โฟลเดอร์ 'plugins' ที่อยู่ข้างไฟล์ .exe this.pluginsDir = path.join(path.dirname(app.getPath('exe')), 'plugins');} else { // Development Mode: ใช้โฟลเดอร์ 'plugins' ใน AppData this.pluginsDir = path.join(app.getPath('userData'), 'plugins');}
// สร้างโฟลเดอร์ plugins ให้ผู้ใช้เลย ถ้ายังไม่มีif (!fs.existsSync(this.pluginsDir)) { try { fs.mkdirSync(this.pluginsDir, { recursive: true }); console.log(` Created user plugins directory at: ${this.pluginsDir}`); } catch (error) { console.error(` Failed to create user plugins directory:`, error); }} console.log(' Plugin Manager initialized. User plugins path is now:', this.pluginsDir); }
/** * ฟังก์ชันหลัก: สแกนหาและอ่าน chahua.json จาก Path ที่ถูกต้อง */ async loadPlugins() { console.log(`[PluginManager] Scanning for manifests in '${this.pluginsDir}'...`); this.projectFeatures.clear();
if (!fs.existsSync(this.pluginsDir)) { console.warn(`[PluginManager] Plugins directory not found, skipping scan.`); return; }
try { const items = fs.readdirSync(this.pluginsDir, { withFileTypes: true });
for (const item of items) { if (!item.isDirectory()) continue;
const projectPath = path.join(this.pluginsDir, item.name); const manifestPath = path.join(projectPath, 'chahua.json');
if (fs.existsSync(manifestPath)) { try { const manifestContent = fs.readFileSync(manifestPath, 'utf8'); const manifestData = JSON.parse(manifestContent);
this.projectFeatures.set(item.name, { name: item.name, displayName: manifestData.name || item.name, path: projectPath, description: manifestData.description || 'No description.', type: manifestData.type || 'unknown', icon: manifestData.icon || '', buttons: manifestData.buttons || [] }); console.log(` -> Registered plugin: ${manifestData.name || item.name}`); } catch (e) { console.error(` -> Error parsing manifest for ${item.name}: ${e.message}`); } } } } catch (error) { console.error(`[PluginManager] Error during manifest scan: ${error.message}`); } }
getProjectFeatures() { return Array.from(this.projectFeatures.values()); }
getPluginStats() { return { projects: this.getProjectFeatures() }; }}
module.exports = PluginManager; 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131/** * Retry Controller - ระบบควบคุมการทำซ้ำ * Chahua Development Thailand * CEO: Saharath C. * * Purpose: จัดการการ retry operations ที่ล้มเหลว */
class RetryController { constructor(options = {}) { this.config = { maxRetries: options.maxRetries || 3, baseDelay: options.baseDelay || 1000, // 1 second maxDelay: options.maxDelay || 30000, // 30 seconds backoffMultiplier: options.backoffMultiplier || 2, jitter: options.jitter || true }; this.retryHistory = new Map(); console.log(' Retry Controller initialized'); }
async executeWithRetry(operation, context = {}, customConfig = {}) { const config = { ...this.config, ...customConfig }; const operationId = context.id || this.generateOperationId(); console.log(` Starting operation with retry: ${operationId}`); let lastError; let attempt = 0; while (attempt <= config.maxRetries) { try { console.log(` Attempt ${attempt + 1}/${config.maxRetries + 1}`); const result = await operation(context, attempt); if (attempt > 0) { console.log(` Operation succeeded on attempt ${attempt + 1}`); } this.logSuccess(operationId, attempt); return result; } catch (error) { lastError = error; attempt++; console.log(` Attempt ${attempt} failed: ${error.message}`); if (attempt <= config.maxRetries) { const delay = this.calculateDelay(attempt, config); console.log(` Retrying in ${delay}ms...`); await this.sleep(delay); } else { console.log(` All retry attempts exhausted for ${operationId}`); } } } this.logFailure(operationId, config.maxRetries + 1, lastError); throw new Error(`Operation failed after ${config.maxRetries + 1} attempts: ${lastError.message}`); }
calculateDelay(attempt, config) { let delay = config.baseDelay * Math.pow(config.backoffMultiplier, attempt - 1); // Cap at max delay delay = Math.min(delay, config.maxDelay); // Add jitter to prevent thundering herd if (config.jitter) { delay = delay * (0.5 + Math.random() * 0.5); } return Math.round(delay); }
async sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }
generateOperationId() { return `op_${Date.now()}_${Math.random().toString(36).substring(2, 8)}`; }
logSuccess(operationId, attempts) { this.retryHistory.set(operationId, { operationId, success: true, attempts: attempts + 1, timestamp: new Date().toISOString() }); }
logFailure(operationId, attempts, error) { this.retryHistory.set(operationId, { operationId, success: false, attempts, error: error.message, timestamp: new Date().toISOString() }); }
getRetryStats() { const history = Array.from(this.retryHistory.values()); const successful = history.filter(h => h.success).length; const failed = history.length - successful; const avgAttempts = history.length > 0 ? Math.round(history.reduce((sum, h) => sum + h.attempts, 0) / history.length) : 0; return { totalOperations: history.length, successful, failed, successRate: history.length > 0 ? Math.round((successful / history.length) * 100) : 0, averageAttempts: avgAttempts }; }
clearHistory() { this.retryHistory.clear(); console.log(' Retry history cleared'); }}
module.exports = RetryController; 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274/** * Rollback Manager - ระบบจัดการ Rollback * Chahua Development Thailand * CEO: Saharath C. * * Purpose: จัดการการ rollback เมื่อเกิดข้อผิดพลาด */
const fs = require('fs');const path = require('path');
class RollbackManager { constructor(options = {}) { this.config = { snapshotPath: options.snapshotPath || './logs/snapshots', maxSnapshots: options.maxSnapshots || 10, enableCompression: options.enableCompression || false, retentionDays: options.retentionDays || 7 }; this.activeTransactions = new Map(); this.rollbackHistory = []; this.ensureSnapshotDirectory(); console.log('Rollback Manager initialized'); }
ensureSnapshotDirectory() { try { if (!fs.existsSync(this.config.snapshotPath)) { fs.mkdirSync(this.config.snapshotPath, { recursive: true }); } } catch (error) { console.warn('Warning: Could not create snapshot directory:', error.message); } }
async createSnapshot(transactionId, data, metadata = {}) { try { const snapshot = { id: transactionId, timestamp: new Date().toISOString(), data: JSON.parse(JSON.stringify(data)), // Deep clone metadata: { source: metadata.source || 'unknown', description: metadata.description || 'Auto snapshot', version: metadata.version || '1.0.0', ...metadata }, size: this.calculateDataSize(data) }; // Store in memory this.activeTransactions.set(transactionId, snapshot); // Save to disk await this.saveSnapshotToDisk(snapshot); console.log(`Snapshot created: ${transactionId}`); return transactionId; } catch (error) { console.error('Error creating snapshot:', error.message); return null; } }
async rollback(transactionId) { try { console.log(`Starting rollback for transaction: ${transactionId}`); let snapshot = this.activeTransactions.get(transactionId); // If not in memory, try loading from disk if (!snapshot) { snapshot = await this.loadSnapshotFromDisk(transactionId); } if (!snapshot) { throw new Error(`Snapshot not found for transaction: ${transactionId}`); } // Perform rollback const rollbackResult = await this.performRollback(snapshot); // Log rollback this.logRollback(transactionId, rollbackResult); // Cleanup await this.cleanupSnapshot(transactionId); console.log(`Rollback completed: ${transactionId}`); return { success: true, transactionId, timestamp: new Date().toISOString(), dataRestored: rollbackResult.itemsRestored || 0 }; } catch (error) { console.error(`Rollback failed for ${transactionId}:`, error.message); return { success: false, transactionId, error: error.message, timestamp: new Date().toISOString() }; } }
async performRollback(snapshot) { // This is a generic rollback implementation // In a real system, this would restore actual system state console.log(`Restoring data from snapshot: ${snapshot.id}`); console.log(`Snapshot created: ${snapshot.timestamp}`); console.log(`Data size: ${snapshot.size} bytes`); // Simulate data restoration let itemsRestored = 0; if (snapshot.data && typeof snapshot.data === 'object') { itemsRestored = Object.keys(snapshot.data).length; } return { itemsRestored, snapshotId: snapshot.id, originalTimestamp: snapshot.timestamp }; }
async saveSnapshotToDisk(snapshot) { try { const filename = `snapshot_${snapshot.id}_${Date.now()}.json`; const filepath = path.join(this.config.snapshotPath, filename); const snapshotData = { ...snapshot, filename, savedAt: new Date().toISOString() }; fs.writeFileSync(filepath, JSON.stringify(snapshotData, null, 2)); // Update snapshot with file path snapshot.filepath = filepath; snapshot.filename = filename; } catch (error) { console.error('Error saving snapshot to disk:', error.message); } }
async loadSnapshotFromDisk(transactionId) { try { const files = fs.readdirSync(this.config.snapshotPath); const snapshotFile = files.find(file => file.includes(`snapshot_${transactionId}_`)); if (!snapshotFile) { return null; } const filepath = path.join(this.config.snapshotPath, snapshotFile); const snapshotData = JSON.parse(fs.readFileSync(filepath, 'utf8')); console.log(`Snapshot loaded from disk: ${transactionId}`); return snapshotData; } catch (error) { console.error('Error loading snapshot from disk:', error.message); return null; } }
async cleanupSnapshot(transactionId) { try { // Remove from memory this.activeTransactions.delete(transactionId); // Remove from disk (optional - you might want to keep for audit) const files = fs.readdirSync(this.config.snapshotPath); const snapshotFile = files.find(file => file.includes(`snapshot_${transactionId}_`)); if (snapshotFile) { const filepath = path.join(this.config.snapshotPath, snapshotFile); fs.unlinkSync(filepath); console.log(`Snapshot file cleaned up: ${snapshotFile}`); } } catch (error) { console.error('Error cleaning up snapshot:', error.message); } }
logRollback(transactionId, result) { const rollbackEntry = { transactionId, timestamp: new Date().toISOString(), success: result.itemsRestored !== undefined, itemsRestored: result.itemsRestored || 0, details: result }; this.rollbackHistory.push(rollbackEntry); // Keep only recent entries if (this.rollbackHistory.length > 100) { this.rollbackHistory.shift(); } }
calculateDataSize(data) { try { return JSON.stringify(data).length; } catch (error) { return 0; } }
getActiveTransactions() { return Array.from(this.activeTransactions.keys()); }
getRollbackHistory() { return this.rollbackHistory.slice(-20); // Last 20 entries }
getStats() { const totalRollbacks = this.rollbackHistory.length; const successfulRollbacks = this.rollbackHistory.filter(r => r.success).length; return { activeTransactions: this.activeTransactions.size, totalRollbacks, successfulRollbacks, failedRollbacks: totalRollbacks - successfulRollbacks, successRate: totalRollbacks > 0 ? Math.round((successfulRollbacks / totalRollbacks) * 100) : 0 }; }
async cleanupOldSnapshots() { try { const files = fs.readdirSync(this.config.snapshotPath); const cutoffDate = new Date(Date.now() - (this.config.retentionDays * 24 * 60 * 60 * 1000)); let cleanedCount = 0; for (const file of files) { if (file.startsWith('snapshot_')) { const filepath = path.join(this.config.snapshotPath, file); const stats = fs.statSync(filepath); if (stats.mtime < cutoffDate) { fs.unlinkSync(filepath); cleanedCount++; } } } if (cleanedCount > 0) { console.log(`Cleaned up ${cleanedCount} old snapshot files`); } return cleanedCount; } catch (error) { console.error('Error cleaning up old snapshots:', error.message); return 0; } }}
module.exports = RollbackManager; 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346/** * Security Logger - ระบบบันทึกเหตุการณ์ความปลอดภัย * Chahua Development Thailand * CEO: Saharath C. * * Purpose: บันทึกและตรวจสอบเหตุการณ์ด้านความปลอดภัย */
const fs = require('fs');const path = require('path');
class SecurityLogger { constructor(options = {}) { this.config = { logPath: options.logPath || './logs/security', maxLogSize: options.maxLogSize || 10 * 1024 * 1024, // 10MB maxLogFiles: options.maxLogFiles || 5, alertThreshold: options.alertThreshold || 10, // Alert after 10 events enableRealTimeAlerts: options.enableRealTimeAlerts || true, sensitiveFields: options.sensitiveFields || ['password', 'token', 'secret', 'key'] }; this.securityEvents = []; this.alertCount = 0; this.blockedIPs = new Set(); this.suspiciousActivities = new Map(); this.ensureLogDirectory(); console.log('Security Logger initialized'); }
ensureLogDirectory() { try { if (!fs.existsSync(this.config.logPath)) { fs.mkdirSync(this.config.logPath, { recursive: true }); } } catch (error) { console.warn('Warning: Could not create security log directory:', error.message); } }
async logSecurityEvent(eventData) { const timestamp = new Date().toISOString(); const eventId = this.generateEventId(); const securityEvent = { id: eventId, timestamp, type: eventData.type || 'UNKNOWN', severity: eventData.severity || 'medium', details: this.sanitizeDetails(eventData), ip: eventData.ip || 'unknown', userAgent: eventData.userAgent || 'unknown', source: eventData.source || 'system' }; // Add to memory this.securityEvents.push(securityEvent); // Maintain max events in memory if (this.securityEvents.length > 1000) { this.securityEvents.shift(); } // Write to file this.writeToLogFile(securityEvent); // Check for alerts this.checkForAlerts(securityEvent); // Update suspicious activity tracking this.updateSuspiciousActivity(securityEvent); console.log(`Security Event [${securityEvent.severity.toUpperCase()}]: ${securityEvent.type} - ${eventId}`); return eventId; }
logAuthFailure(ip, username, details = {}) { return this.logSecurityEvent({ type: 'AUTH_FAILURE', ip, username, severity: 'high', ...details }); }
logAuthSuccess(ip, username, details = {}) { return this.logSecurityEvent({ type: 'AUTH_SUCCESS', ip, username, severity: 'low', ...details }); }
logSuspiciousAccess(ip, endpoint, details = {}) { return this.logSecurityEvent({ type: 'SUSPICIOUS_ACCESS', ip, endpoint, severity: 'high', ...details }); }
logRateLimitExceeded(ip, endpoint, details = {}) { return this.logSecurityEvent({ type: 'RATE_LIMIT_EXCEEDED', ip, endpoint, severity: 'medium', ...details }); }
logDataBreach(source, details = {}) { return this.logSecurityEvent({ type: 'DATA_BREACH', source, severity: 'critical', ...details }); }
logUnauthorizedAccess(ip, resource, details = {}) { return this.logSecurityEvent({ type: 'UNAUTHORIZED_ACCESS', ip, resource, severity: 'high', ...details }); }
logSystemAnomaly(anomalyType, details = {}) { return this.logSecurityEvent({ type: 'SYSTEM_ANOMALY', anomalyType, severity: 'medium', ...details }); }
sanitizeDetails(details) { const sanitized = { ...details }; // Remove sensitive fields for (const field of this.config.sensitiveFields) { if (sanitized[field]) { sanitized[field] = '***REDACTED***'; } } return sanitized; }
writeToLogFile(event) { try { const logFileName = `security-${new Date().toISOString().split('T')[0]}.log`; const logFilePath = path.join(this.config.logPath, logFileName); const logEntry = JSON.stringify(event) + '\n'; // Check file size and rotate if needed if (fs.existsSync(logFilePath)) { const stats = fs.statSync(logFilePath); if (stats.size > this.config.maxLogSize) { this.rotateLogFile(logFilePath); } } fs.appendFileSync(logFilePath, logEntry); } catch (error) { console.error('Error writing security log:', error.message); } }
rotateLogFile(logFilePath) { try { const logDir = path.dirname(logFilePath); const baseName = path.basename(logFilePath, '.log'); // Rotate existing files for (let i = this.config.maxLogFiles - 1; i > 0; i--) { const oldFile = path.join(logDir, `${baseName}.${i}.log`); const newFile = path.join(logDir, `${baseName}.${i + 1}.log`); if (fs.existsSync(oldFile)) { if (i === this.config.maxLogFiles - 1) { fs.unlinkSync(oldFile); // Delete oldest } else { fs.renameSync(oldFile, newFile); } } } // Move current file to .1 const rotatedFile = path.join(logDir, `${baseName}.1.log`); fs.renameSync(logFilePath, rotatedFile); console.log(`Security log rotated: ${logFilePath}`); } catch (error) { console.error('Error rotating security log:', error.message); } }
checkForAlerts(event) { if (!this.config.enableRealTimeAlerts) return; // Count events from same IP in last hour const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000); const recentEvents = this.securityEvents.filter(e => e.ip === event.ip && new Date(e.timestamp) > oneHourAgo ); if (recentEvents.length >= this.config.alertThreshold) { this.triggerAlert(event.ip, recentEvents); } // Immediate alert for critical events if (event.severity === 'critical') { this.triggerCriticalAlert(event); } }
triggerAlert(ip, events) { this.alertCount++; console.warn(`SECURITY ALERT: Multiple events from IP ${ip} (${events.length} events)`); // Block IP after multiple alerts if (events.length >= this.config.alertThreshold * 2) { this.blockedIPs.add(ip); console.warn(`IP ${ip} has been blocked due to suspicious activity`); } // In a real system, you might send email/SMS alerts here }
triggerCriticalAlert(event) { console.error(`CRITICAL SECURITY ALERT: ${event.type} - ${event.id}`); // In a real system, you might trigger immediate notifications }
updateSuspiciousActivity(event) { const key = `${event.ip}_${event.type}`; const count = this.suspiciousActivities.get(key) || 0; this.suspiciousActivities.set(key, count + 1); }
isIPBlocked(ip) { return this.blockedIPs.has(ip); }
unblockIP(ip) { if (this.blockedIPs.delete(ip)) { console.log(`IP ${ip} has been unblocked`); return true; } return false; }
getSecurityReport(timeRange = '24h') { const hours = timeRange === '24h' ? 24 : parseInt(timeRange); const startTime = new Date(Date.now() - hours * 60 * 60 * 1000); const relevantEvents = this.securityEvents.filter(e => new Date(e.timestamp) > startTime ); const report = { timeRange: `${hours} hours`, totalEvents: relevantEvents.length, eventTypes: {}, severityBreakdown: {}, topIPs: {}, blockedIPs: Array.from(this.blockedIPs), alertsTriggered: this.alertCount }; // Analyze events relevantEvents.forEach(event => { // Event types report.eventTypes[event.type] = (report.eventTypes[event.type] || 0) + 1; // Severity breakdown report.severityBreakdown[event.severity] = (report.severityBreakdown[event.severity] || 0) + 1; // Top IPs report.topIPs[event.ip] = (report.topIPs[event.ip] || 0) + 1; }); // Sort top IPs report.topIPs = Object.entries(report.topIPs) .sort(([,a], [,b]) => b - a) .slice(0, 10) .reduce((obj, [ip, count]) => { obj[ip] = count; return obj; }, {}); return report; }
exportSecurityLogs(startDate, endDate) { try { const events = this.securityEvents.filter(e => { const eventDate = new Date(e.timestamp); return eventDate >= startDate && eventDate <= endDate; }); const exportData = { exportDate: new Date().toISOString(), dateRange: { start: startDate, end: endDate }, totalEvents: events.length, events: events }; return exportData; } catch (error) { console.error('Error exporting security logs:', error.message); return null; } }
generateEventId() { return `sec_${Date.now()}_${Math.random().toString(36).substring(2, 8)}`; }
getStats() { return { totalEvents: this.securityEvents.length, alertsTriggered: this.alertCount, blockedIPs: this.blockedIPs.size, suspiciousActivities: this.suspiciousActivities.size }; }}
module.exports = SecurityLogger; 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253/** * ╔════════════════════════════════════════════════════════════════════════════════════╗ * ║ SVG ICON SYSTEM ║ * ║ ระบบไอคอน SVG ปลอดภัย ║ * ║ [ใช้งาน] ใช้แทนอิโมจิทั้งหมดในระบบ Chahuadev Framework ║ * ╚════════════════════════════════════════════════════════════════════════════════════╝ */
class SVGIcons { /** * สร้างไอคอน SVG สำหรับใช้ในระบบ */ static icons = { // Security & Auth Icons lock: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect> <path d="M7 11V7a5 5 0 0 1 10 0v4"></path> <circle cx="12" cy="20" r="1"></circle> </svg>`, unlock: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect> <path d="M7 11V7a5 5 0 0 1 9.2 1"></path> <circle cx="12" cy="20" r="1"></circle> </svg>`, shield: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path> </svg>`, checkCircle: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path> <polyline points="22 4 12 14.01 9 11.01"></polyline> </svg>`, alertCircle: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <circle cx="12" cy="12" r="10"></circle> <line x1="12" y1="8" x2="12" y2="12"></line> <line x1="12" y1="16" x2="12.01" y2="16"></line> </svg>`, xCircle: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <circle cx="12" cy="12" r="10"></circle> <line x1="15" y1="9" x2="9" y2="15"></line> <line x1="9" y1="9" x2="15" y2="15"></line> </svg>`, // User & Auth Icons user: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path> <circle cx="12" cy="7" r="4"></circle> </svg>`, users: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path> <circle cx="9" cy="7" r="4"></circle> <path d="M23 21v-2a4 4 0 0 0-3-3.87"></path> <path d="M16 3.13a4 4 0 0 1 0 7.75"></path> </svg>`, userCheck: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path> <circle cx="8.5" cy="7" r="4"></circle> <polyline points="21 15 16 20 13 17"></polyline> </svg>`, userX: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path> <circle cx="8.5" cy="7" r="4"></circle> <line x1="18" y1="8" x2="23" y2="13"></line> <line x1="23" y1="8" x2="18" y2="13"></line> </svg>`, // System Icons zap: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"></polygon> </svg>`, settings: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <circle cx="12" cy="12" r="3"></circle> <path d="M12 1v6m0 6v6M4.22 4.22l4.24 4.24m3.08 3.08l4.24 4.24M1 12h6m6 0h6m-16.78 7.78l4.24-4.24m3.08-3.08l4.24-4.24"></path> </svg>`, loader: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <line x1="12" y1="2" x2="12" y2="6"></line> <line x1="12" y1="18" x2="12" y2="22"></line> <line x1="4.22" y1="4.22" x2="7.34" y2="7.34"></line> <line x1="16.66" y1="16.66" x2="19.78" y2="19.78"></line> <line x1="2" y1="12" x2="6" y2="12"></line> <line x1="18" y1="12" x2="22" y2="12"></line> <line x1="4.22" y1="19.78" x2="7.34" y2="16.66"></line> <line x1="16.66" y1="7.34" x2="19.78" y2="4.22"></line> </svg>`, // Status Icons check: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <polyline points="20 6 9 17 4 12"></polyline> </svg>`, x: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <line x1="18" y1="6" x2="6" y2="18"></line> <line x1="6" y1="6" x2="18" y2="18"></line> </svg>`, alertTriangle: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3.05h16.94a2 2 0 0 0 1.71-3.05l-8.47-14.14a2 2 0 0 0-3.42 0z"></path> <line x1="12" y1="9" x2="12" y2="13"></line> <line x1="12" y1="17" x2="12.01" y2="17"></line> </svg>`, info: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <circle cx="12" cy="12" r="10"></circle> <line x1="12" y1="16" x2="12" y2="12"></line> <line x1="12" y1="8" x2="12.01" y2="8"></line> </svg>`, // App Icons plugin: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <circle cx="12" cy="12" r="1"></circle> <path d="M12 1v6m0 6v6"></path> <path d="M4.22 4.22l4.24 4.24m3.08 3.08l4.24 4.24"></path> <path d="M1 12h6m6 0h6"></path> <path d="M4.22 19.78l4.24-4.24m3.08-3.08l4.24-4.24"></path> </svg>`, package: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <line x1="16.5" y1="9.4" x2="7.5" y2="4.21"></line> <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"></path> <polyline points="3.27 6.96 12 12.01 20.73 6.96"></polyline> <line x1="12" y1="22.08" x2="12" y2="12"></line> </svg>`, database: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <ellipse cx="12" cy="5" rx="9" ry="3"></ellipse> <path d="M3 5v14a9 3 0 0 0 18 0V5"></path> <ellipse cx="12" cy="19" rx="9" ry="3"></ellipse> </svg>`, // Action Icons download: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path> <polyline points="7 10 12 15 17 10"></polyline> <line x1="12" y1="15" x2="12" y2="3"></line> </svg>`, upload: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path> <polyline points="17 8 12 3 7 8"></polyline> <line x1="12" y1="3" x2="12" y2="15"></line> </svg>`, refresh: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <polyline points="23 4 23 10 17 10"></polyline> <polyline points="1 20 1 14 7 14"></polyline> <path d="M3.51 9a9 9 0 0 1 14.85-3.36M20.49 15a9 9 0 0 1-14.85 3.36"></path> </svg>`, trash: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <polyline points="3 6 5 6 21 6"></polyline> <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path> <line x1="10" y1="11" x2="10" y2="17"></line> <line x1="14" y1="11" x2="14" y2="17"></line> </svg>`, edit: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path> <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path> </svg>`, // System Status server: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <rect x="2" y="2" width="20" height="8" rx="2" ry="2"></rect> <rect x="2" y="14" width="20" height="8" rx="2" ry="2"></rect> <line x1="6" y1="6" x2="6.01" y2="6"></line> <line x1="6" y1="18" x2="6.01" y2="18"></line> </svg>`, gitBranch: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <line x1="6" y1="3" x2="6" y2="15"></line> <circle cx="18" cy="6" r="3"></circle> <circle cx="6" cy="18" r="3"></circle> <path d="M18 9a9 9 0 0 1-9 9"></path> </svg>`, terminal: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <polyline points="4 17 10 11 4 5"></polyline> <line x1="12" y1="19" x2="20" y2="19"></line> </svg>`, // Misc Icons eye: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path> <circle cx="12" cy="12" r="3"></circle> </svg>`, eyeOff: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"></path> <line x1="1" y1="1" x2="23" y2="23"></line> </svg>`, search: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <circle cx="11" cy="11" r="8"></circle> <path d="m21 21-4.35-4.35"></path> </svg>`, bell: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"></path> <path d="M13.73 21a2 2 0 0 1-3.46 0"></path> </svg>`, clock: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <circle cx="12" cy="12" r="10"></circle> <polyline points="12 6 12 12 16 14"></polyline> </svg>`, };
/** * ดึง SVG icon แบบสตริง * @param {string} name - ชื่อ icon * @param {string} className - CSS class ที่ต้องเพิ่ม (optional) * @returns {string} HTML SVG element */ static getSVG(name, className = '') { if (!this.icons[name]) { console.warn(`Icon not found: ${name}`); return ''; }
const svgString = this.icons[name]; if (className) { return svgString.replace('<svg', `<svg class="${className}"`); } return svgString; }
/** * สร้าง HTML element จาก SVG * @param {string} name - ชื่อ icon * @param {string} className - CSS class * @returns {HTMLElement} SVG element */ static createSVGElement(name, className = '') { const svg = this.getSVG(name, className); const div = document.createElement('div'); div.innerHTML = svg; return div.firstChild; }}
// ส่งออกif (typeof module !== 'undefined' && module.exports) { module.exports = SVGIcons;}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157/** * system-detector.js - Auto System Detection (Level 4) * สำหรับ Chahuadev Framework * * ใช้: BaseStrategy และ concrete strategies จาก Level 3 * ตรวจสอบ: Project type, runtime environment, available tools */
const fs = require('fs');const path = require('path');const { exec } = require('child_process');
// Import strategies จาก Level 3const NodeStrategy = require('../strategies/NodeStrategy');const PythonStrategy = require('../strategies/PythonStrategy');const JavaStrategy = require('../strategies/JavaStrategy');const ApiStrategy = require('../strategies/ApiStrategy');const ButtonGenerator = require('./button-generator');
class SystemDetector { constructor() { // สร้าง strategy instances this.strategies = { node: new NodeStrategy(), python: new PythonStrategy(), java: new JavaStrategy(), api: new ApiStrategy(), // เพิ่ม strategies สำหรับ executable และ batch projects // ใช้ NodeStrategy เพราะสามารถรันคำสั่งทั่วไปได้ executable_project: new NodeStrategy(), batch_project: new NodeStrategy() }; this.detectionRules = this.initializeDetectionRules(); // เพิ่มระบบสร้างปุ่มอัจฉริยะ this.buttonGenerator = new ButtonGenerator(); this.projectsWithButtons = new Map(); console.log(' SystemDetector initialized with Smart Button System'); }
/** * กำหนด detection rules สำหรับแต่ละ project type */ initializeDetectionRules() { return { node: { files: ['package.json', 'node_modules/', 'yarn.lock', 'package-lock.json'], extensions: ['.js', '.ts', '.json'], commands: ['node', 'npm', 'yarn'], priority: 10 }, python: { files: ['requirements.txt', 'setup.py', 'pyproject.toml', 'Pipfile', 'main.py', 'app.py'], extensions: ['.py', '.pyx', '.ipynb'], commands: ['python', 'python3', 'pip', 'pip3'], priority: 9 }, java: { files: ['pom.xml', 'build.gradle', 'gradlew', 'build.xml'], extensions: ['.java', '.class', '.jar'], commands: ['java', 'javac', 'mvn', 'gradle'], priority: 8 }, // เพิ่มประเภทใหม่สำหรับโปรเจกต์ .exe executable_project: { files: [], // ไม่ต้องหาไฟล์ชื่อเฉพาะ extensions: ['.exe'], // แค่มองหานามสกุล .exe ก็พอ commands: [], priority: 12 // ให้ความสำคัญสูงสุด เพราะชัดเจนที่สุด }, // เพิ่มประเภทใหม่สำหรับโปรเจกต์ .bat batch_project: { files: [], // ไม่ต้องหาไฟล์ชื่อเฉพาะ extensions: ['.bat', '.cmd'], // หานามสกุล .bat และ .cmd commands: [], priority: 11 // ให้ความสำคัญรองจาก .exe }, api: { // API strategy ไม่ต้องมี files เพราะใช้ URL files: [], extensions: [], commands: [], priority: 5, special: 'url-based' // ตรวจสอบจาก URL pattern } }; }
/** * SystemDetector V2: Checklist-based Detection * ตรวจสอบ project type ตามลำดับความสำคัญอย่างชัดเจน */ async detect(projectPath = process.cwd(), context = {}) { console.log(`[SystemDetector V2] Using Checklist-based detection for: ${path.basename(projectPath)}`); try { // ถ้า context มี URL ให้ใช้ API strategy if (context.command && this.isUrl(context.command)) { console.log(' URL detected, using API strategy'); return { type: 'api', strategy: this.strategies.api, confidence: 100, reason: 'URL detected in command' }; } // ถ้า context ระบุ type มาแล้ว if (context.forceType && this.strategies[context.forceType]) { console.log(` Forced type detected: ${context.forceType}`); return { type: context.forceType, strategy: this.strategies[context.forceType], confidence: 100, reason: 'Force type specified in context' }; }
if (!fs.existsSync(projectPath)) { throw new Error(`Project path not found: ${projectPath}`); }
const files = fs.readdirSync(projectPath).map(f => f.toLowerCase()); let detectedType = 'unknown';
// --- ระบบ Checklist ตามลำดับความสำคัญ ---
// Priority 1: Batch Project (ชัดเจนที่สุด) if (files.some(f => f.endsWith('.bat') || f.endsWith('.cmd'))) { detectedType = 'batch_project'; console.log(` -> Priority 1: Found .bat/.cmd file. Type set to [${detectedType}]`); // Priority 2: Executable Project } else if (files.some(f => f.endsWith('.exe'))) { detectedType = 'executable_project'; console.log(` -> Priority 2: Found .exe file. Type set to [${detectedType}]`); // Priority 3: Node.js Project } else if (files.includes('package.json')) { detectedType = 'node'; console.log(` -> Priority 3: Found package.json. Type set to [${detectedType}]`); // Priority 4: Python Project } else if (files.includes('requirements.txt') || files.includes('main.py') || files.includes('app.py')) { detectedType = 'python'; console.log(` -> Priority 4: Found Python indicators. Type set to [${detectedType}]`); // Priority 5: Java Project } else if (files.includes('pom.xml') || files.includes('build.gradle')) { detectedType = 'java'; console.log(` -> Priority 5: Found Java indicators. Type set to [${detectedType}]`); // Priority 6: Basic HTML Project } else if (files.some(f => f.endsWith('.html'))) { detectedType = 'html'; console.log(` -> Priority 6: Found .html file. Type set to [${detectedType}]`); } // --- จบระบบ Checklist ---
if (detectedType === 'unknown') { console.log(` -> No specific project type detected. Marked as 'unknown'.`); // เพิ่ม fallback สำหรับ production mode const { app } = require('electron'); if (app.isPackaged) { detectedType = 'executable_project'; console.log(` -> [Fallback] Set to executable_project for production mode`); } }
// สร้างปุ่มสำหรับโปรเจคที่ตรวจพบ if (detectedType !== 'unknown') { const detectionResult = { type: detectedType, confidence: 100 }; await this.generateProjectButtons(projectPath, detectionResult); }
return { type: detectedType, confidence: detectedType !== 'unknown' ? 100 : 0, // ถ้าเจอคือมั่นใจ 100% reason: `Checklist-based detection: Priority rule for [${detectedType}] triggered.`, strategy: this.strategies[detectedType] || this.strategies.node // Fallback to node strategy };
} catch (error) { console.error(` Detection failed for ${projectPath}: ${error.message}`); return { type: 'unknown', confidence: 0, error: error.message, strategy: this.strategies.node }; } }
/** * รัน detection tests สำหรับทุก strategy */ async runDetectionTests(projectPath) { const results = {}; for (const [strategyName, rules] of Object.entries(this.detectionRules)) { if (rules.special === 'url-based') { // Skip API strategy สำหรับ file-based detection continue; } console.log(` Testing ${strategyName} detection...`); const score = await this.calculateDetectionScore(projectPath, rules, strategyName); results[strategyName] = { type: strategyName, strategy: this.strategies[strategyName], score: score, confidence: Math.min(score * 10, 100), // แปลง score เป็น percentage rules: rules }; console.log(` ${strategyName} detection score: ${score}/10 (${results[strategyName].confidence}%)`); } return results; }
/** * คำนวณ detection score สำหรับ strategy */ async calculateDetectionScore(projectPath, rules, strategyName) { let score = 0; const maxScore = 10; // ตรวจสอบ files (40% ของคะแนน) const fileScore = this.checkFiles(projectPath, rules.files); score += fileScore * 0.4; // ตรวจสอบ extensions (30% ของคะแนน) const extensionScore = this.checkExtensions(projectPath, rules.extensions); score += extensionScore * 0.3; // ตรวจสอบ commands (30% ของคะแนน) const commandScore = await this.checkCommands(rules.commands); score += commandScore * 0.3; return Math.round(score * 10) / 10; // ปัดเศษ 1 ตำแหน่ง }
/** * ตรวจสอบ files ที่บ่งบอกประเภท project */ checkFiles(projectPath, requiredFiles) { if (!requiredFiles.length) return 0; let foundCount = 0; for (const file of requiredFiles) { const filePath = path.join(projectPath, file); if (fs.existsSync(filePath)) { foundCount++; console.log(` Found indicator file: ${file}`); } } return foundCount / requiredFiles.length * 10; }
/** * ตรวจสอบ file extensions */ checkExtensions(projectPath, extensions) { if (!extensions.length) return 0; const files = this.getFilesRecursive(projectPath, 2); // ค้นหา 2 levels let foundCount = 0; for (const ext of extensions) { const hasExtension = files.some(file => file.endsWith(ext)); if (hasExtension) { foundCount++; console.log(` Found files with extension: ${ext}`); } } return foundCount / extensions.length * 10; }
/** * ตรวจสอบ commands ว่ามีอยู่ในระบบหรือไม่ */ async checkCommands(commands) { if (!commands.length) return 0; let availableCount = 0; for (const command of commands) { const isAvailable = await this.isCommandAvailable(command); if (isAvailable) { availableCount++; console.log(` Command available: ${command}`); } } return availableCount / commands.length * 10; }
/** * ตรวจสอบว่า command มีอยู่ในระบบหรือไม่ */ async isCommandAvailable(command) { return new Promise((resolve) => { const testCommand = process.platform === 'win32' ? `where ${command}` : `which ${command}`; exec(testCommand, (error, stdout, stderr) => { resolve(!error && stdout.trim().length > 0); }); }); }
/** * เลือก strategy ที่ดีที่สุด */ selectBestStrategy(detectionResults) { const strategies = Object.values(detectionResults); // เรียงลำดับตาม confidence และ priority strategies.sort((a, b) => { if (a.confidence !== b.confidence) { return b.confidence - a.confidence; // เรียงจากมากไปน้อย } return b.rules.priority - a.rules.priority; // เรียงตาม priority }); const bestStrategy = strategies[0]; return { type: bestStrategy.type, strategy: bestStrategy.strategy, confidence: bestStrategy.confidence, reason: `Best match based on detection tests`, allResults: detectionResults }; }
/** * ตรวจสอบว่าเป็น URL หรือไม่ */ isUrl(str) { try { new URL(str); return str.startsWith('http://') || str.startsWith('https://'); } catch { return false; } }
/** * ค้นหาไฟล์แบบ recursive */ getFilesRecursive(dirPath, maxDepth = 2) { const files = []; const scanDir = (currentPath, depth) => { if (depth > maxDepth) return; try { const items = fs.readdirSync(currentPath); for (const item of items) { const fullPath = path.join(currentPath, item); const stat = fs.lstatSync(fullPath); if (stat.isFile()) { files.push(fullPath); } else if (stat.isDirectory() && !item.startsWith('.') && item !== 'node_modules') { scanDir(fullPath, depth + 1); } } } catch (error) { // Ignore permission errors } }; scanDir(dirPath, 0); return files; }
// สร้างปุ่มตามข้อมูลโปรเจค (เวอร์ชันสแกนรูปอัตโนมัติ) async generateProjectButtons(projectPath, detectionResult) { try { console.log(` Generating buttons for project at: ${projectPath}`); // วิเคราะห์ฟีเจอร์ของโปรเจค const features = await this.analyzeProjectFeatures(projectPath, detectionResult); // สร้างภาพตัวอย่างปลั๊กอิน const previewImage = await this.generatePluginPreview(projectPath, detectionResult); // --- จุดแก้ไข: ตรวจสอบและดึง strategy ให้ถูกต้อง --- const strategy = this.strategies[detectionResult.type]; if (!strategy) { console.warn(` No strategy found for project type "${detectionResult.type}". Skipping button generation.`); // ลองใช้ fallback strategy ถ้ามี const fallbackStrategy = this.strategies.node; if (!fallbackStrategy) return []; } // --- จบส่วนแก้ไข --- // สร้างข้อมูลโปรเจค const projectInfo = { name: path.basename(projectPath), path: projectPath, type: detectionResult.type, confidence: detectionResult.confidence, strategy: strategy ? strategy.constructor.name : 'Unknown', // ป้องกัน error previewImage: previewImage // เพิ่มภาพตัวอย่าง }; // สร้างปุ่ม const buttons = this.buttonGenerator.generateProjectButtons(projectInfo, features); // เก็บข้อมูลโปรเจคและปุ่ม this.projectsWithButtons.set(projectPath, { projectInfo, buttons, generated: new Date().toISOString() }); console.log(` Generated ${buttons.length} buttons for ${projectInfo.name}`); return buttons; } catch (error) { console.warn(` Failed to generate buttons for ${projectPath}:`, error.message); return []; } }
// สร้างภาพตัวอย่างปลั๊กอิน async generatePluginPreview(projectPath, detectionResult) { try { console.log(` Generating preview for plugin: ${path.basename(projectPath)}`); const previewsDir = this.getPreviewsDirectory(); const pluginName = path.basename(projectPath); const previewFileName = `${pluginName}_preview.png`; const previewPath = path.join(previewsDir, previewFileName); // ตรวจสอบว่ามีภาพตัวอย่างอยู่แล้วหรือไม่ if (fs.existsSync(previewPath)) { console.log(` Preview already exists: ${previewFileName}`); return `file://${previewPath.replace(/\\/g, '/')}`; } // สร้างภาพตัวอย่างตามประเภทปลั๊กอิน const success = await this.createPreviewImage(projectPath, detectionResult, previewPath); if (success) { console.log(` Preview created: ${previewFileName}`); return `file://${previewPath.replace(/\\/g, '/')}`; } else { console.warn(` Failed to create preview for ${pluginName}`); return this.getDefaultPreviewImage(detectionResult.type); } } catch (error) { console.error(` Error generating preview: ${error.message}`); return this.getDefaultPreviewImage(detectionResult.type); } }
// ดึง directory สำหรับเก็บภาพตัวอย่าง getPreviewsDirectory() { const { app } = require('electron'); let previewsDir; if (app.isPackaged) { previewsDir = path.join(path.dirname(app.getPath('exe')), 'previews'); } else { previewsDir = path.join(process.cwd(), 'previews'); } // สร้างโฟลเดอร์ถ้ายังไม่มี if (!fs.existsSync(previewsDir)) { fs.mkdirSync(previewsDir, { recursive: true }); console.log(` Created previews directory: ${previewsDir}`); } return previewsDir; }
// สร้างภาพตัวอย่างตามประเภทปลั๊กอิน async createPreviewImage(projectPath, detectionResult, outputPath) { try { const { type } = detectionResult; switch (type) { case 'executable_project': return await this.createExecutablePreview(projectPath, outputPath); case 'batch_project': return await this.createBatchPreview(projectPath, outputPath); case 'node': return await this.createNodePreview(projectPath, outputPath); case 'python': return await this.createPythonPreview(projectPath, outputPath); case 'html': return await this.createWebPreview(projectPath, outputPath); default: return await this.createGenericPreview(projectPath, outputPath, type); } } catch (error) { console.error(` Error creating preview image: ${error.message}`); return false; } }
// สร้างภาพตัวอย่างสำหรับ Executable async createExecutablePreview(projectPath, outputPath) { try { const canvas = this.createCanvas(400, 300); const ctx = canvas.getContext('2d'); // Background gradient const gradient = ctx.createLinearGradient(0, 0, 400, 300); gradient.addColorStop(0, '#4A5568'); gradient.addColorStop(1, '#2D3748'); ctx.fillStyle = gradient; ctx.fillRect(0, 0, 400, 300); // Icon ctx.font = 'bold 60px Arial'; ctx.fillStyle = '#E2E8F0'; ctx.textAlign = 'center'; ctx.fillText('', 200, 120); // Title ctx.font = 'bold 24px Arial'; ctx.fillStyle = '#F7FAFC'; const pluginName = path.basename(projectPath); ctx.fillText(pluginName, 200, 180); // Subtitle ctx.font = '16px Arial'; ctx.fillStyle = '#CBD5E0'; ctx.fillText('Executable Application', 200, 210); // Type badge ctx.fillStyle = '#4FD1C7'; ctx.fillRect(150, 230, 100, 25); ctx.fillStyle = '#1A202C'; ctx.font = '12px Arial'; ctx.fillText('EXE', 200, 247); return await this.saveCanvas(canvas, outputPath); } catch (error) { console.error(` Error creating executable preview: ${error.message}`); return false; } }
// สร้างภาพตัวอย่างสำหรับ Batch async createBatchPreview(projectPath, outputPath) { try { const canvas = this.createCanvas(400, 300); const ctx = canvas.getContext('2d'); // Background const gradient = ctx.createLinearGradient(0, 0, 400, 300); gradient.addColorStop(0, '#38A169'); gradient.addColorStop(1, '#2F855A'); ctx.fillStyle = gradient; ctx.fillRect(0, 0, 400, 300); // Icon ctx.font = 'bold 60px Arial'; ctx.fillStyle = '#F0FFF4'; ctx.textAlign = 'center'; ctx.fillText('', 200, 120); // Title ctx.font = 'bold 24px Arial'; ctx.fillStyle = '#F7FAFC'; const pluginName = path.basename(projectPath); ctx.fillText(pluginName, 200, 180); // Subtitle ctx.font = '16px Arial'; ctx.fillStyle = '#C6F6D5'; ctx.fillText('Batch Script', 200, 210); // Type badge ctx.fillStyle = '#68D391'; ctx.fillRect(150, 230, 100, 25); ctx.fillStyle = '#1A202C'; ctx.font = '12px Arial'; ctx.fillText('BAT', 200, 247); return await this.saveCanvas(canvas, outputPath); } catch (error) { console.error(` Error creating batch preview: ${error.message}`); return false; } }
// สร้างภาพตัวอย่างสำหรับ Node.js async createNodePreview(projectPath, outputPath) { try { const canvas = this.createCanvas(400, 300); const ctx = canvas.getContext('2d'); // Background const gradient = ctx.createLinearGradient(0, 0, 400, 300); gradient.addColorStop(0, '#68D391'); gradient.addColorStop(1, '#48BB78'); ctx.fillStyle = gradient; ctx.fillRect(0, 0, 400, 300); // Icon ctx.font = 'bold 60px Arial'; ctx.fillStyle = '#F0FFF4'; ctx.textAlign = 'center'; ctx.fillText('', 200, 120); // Title ctx.font = 'bold 24px Arial'; ctx.fillStyle = '#F7FAFC'; const pluginName = path.basename(projectPath); ctx.fillText(pluginName, 200, 180); // Subtitle ctx.font = '16px Arial'; ctx.fillStyle = '#C6F6D5'; ctx.fillText('Node.js Project', 200, 210); // Type badge ctx.fillStyle = '#9AE6B4'; ctx.fillRect(150, 230, 100, 25); ctx.fillStyle = '#1A202C'; ctx.font = '12px Arial'; ctx.fillText('NODE', 200, 247); return await this.saveCanvas(canvas, outputPath); } catch (error) { console.error(` Error creating node preview: ${error.message}`); return false; } }
// สร้างภาพตัวอย่างสำหรับ Python async createPythonPreview(projectPath, outputPath) { try { const canvas = this.createCanvas(400, 300); const ctx = canvas.getContext('2d'); // Background const gradient = ctx.createLinearGradient(0, 0, 400, 300); gradient.addColorStop(0, '#4FD1C7'); gradient.addColorStop(1, '#38B2AC'); ctx.fillStyle = gradient; ctx.fillRect(0, 0, 400, 300); // Icon ctx.font = 'bold 60px Arial'; ctx.fillStyle = '#E6FFFA'; ctx.textAlign = 'center'; ctx.fillText('', 200, 120); // Title ctx.font = 'bold 24px Arial'; ctx.fillStyle = '#F7FAFC'; const pluginName = path.basename(projectPath); ctx.fillText(pluginName, 200, 180); // Subtitle ctx.font = '16px Arial'; ctx.fillStyle = '#B2F5EA'; ctx.fillText('Python Project', 200, 210); // Type badge ctx.fillStyle = '#81E6D9'; ctx.fillRect(150, 230, 100, 25); ctx.fillStyle = '#1A202C'; ctx.font = '12px Arial'; ctx.fillText('PY', 200, 247); return await this.saveCanvas(canvas, outputPath); } catch (error) { console.error(` Error creating python preview: ${error.message}`); return false; } }
// สร้างภาพตัวอย่างสำหรับ Web/HTML async createWebPreview(projectPath, outputPath) { try { const canvas = this.createCanvas(400, 300); const ctx = canvas.getContext('2d'); // Background const gradient = ctx.createLinearGradient(0, 0, 400, 300); gradient.addColorStop(0, '#90CDF4'); gradient.addColorStop(1, '#63B3ED'); ctx.fillStyle = gradient; ctx.fillRect(0, 0, 400, 300); // Icon ctx.font = 'bold 60px Arial'; ctx.fillStyle = '#EBF8FF'; ctx.textAlign = 'center'; ctx.fillText('', 200, 120); // Title ctx.font = 'bold 24px Arial'; ctx.fillStyle = '#F7FAFC'; const pluginName = path.basename(projectPath); ctx.fillText(pluginName, 200, 180); // Subtitle ctx.font = '16px Arial'; ctx.fillStyle = '#BEE3F8'; ctx.fillText('Web Application', 200, 210); // Type badge ctx.fillStyle = '#A3BFFA'; ctx.fillRect(150, 230, 100, 25); ctx.fillStyle = '#1A202C'; ctx.font = '12px Arial'; ctx.fillText('WEB', 200, 247); return await this.saveCanvas(canvas, outputPath); } catch (error) { console.error(` Error creating web preview: ${error.message}`); return false; } }
// สร้างภาพตัวอย่างทั่วไป async createGenericPreview(projectPath, outputPath, type) { try { const canvas = this.createCanvas(400, 300); const ctx = canvas.getContext('2d'); // Background const gradient = ctx.createLinearGradient(0, 0, 400, 300); gradient.addColorStop(0, '#A0AEC0'); gradient.addColorStop(1, '#718096'); ctx.fillStyle = gradient; ctx.fillRect(0, 0, 400, 300); // Icon ctx.font = 'bold 60px Arial'; ctx.fillStyle = '#F7FAFC'; ctx.textAlign = 'center'; ctx.fillText('', 200, 120); // Title ctx.font = 'bold 24px Arial'; ctx.fillStyle = '#F7FAFC'; const pluginName = path.basename(projectPath); ctx.fillText(pluginName, 200, 180); // Subtitle ctx.font = '16px Arial'; ctx.fillStyle = '#E2E8F0'; ctx.fillText(`${type.toUpperCase()} Plugin`, 200, 210); // Type badge ctx.fillStyle = '#CBD5E0'; ctx.fillRect(150, 230, 100, 25); ctx.fillStyle = '#1A202C'; ctx.font = '12px Arial'; ctx.fillText(type.substring(0, 8).toUpperCase(), 200, 247); return await this.saveCanvas(canvas, outputPath); } catch (error) { console.error(` Error creating generic preview: ${error.message}`); return false; } }
// สร้าง Canvas (ใช้ node-canvas หรือ fallback) createCanvas(width, height) { try { // ลองใช้ node-canvas ก่อน const { createCanvas } = require('canvas'); return createCanvas(width, height); } catch (error) { // Fallback: สร้าง mock canvas สำหรับ testing console.warn(' node-canvas not available, using fallback'); return this.createMockCanvas(width, height); } }
// Mock Canvas สำหรับ fallback createMockCanvas(width, height) { return { width, height, getContext: () => ({ fillStyle: '', font: '', textAlign: '', fillRect: () => {}, fillText: () => {}, createLinearGradient: () => ({ addColorStop: () => {} }) }), toBuffer: () => Buffer.from('') }; }
// บันทึก Canvas เป็นไฟล์ async saveCanvas(canvas, outputPath) { try { const buffer = canvas.toBuffer('image/png'); fs.writeFileSync(outputPath, buffer); return true; } catch (error) { console.error(` Error saving canvas: ${error.message}`); // สร้างไฟล์ placeholder return this.createPlaceholderImage(outputPath); } }
// สร้างไฟล์ placeholder createPlaceholderImage(outputPath) { try { // สร้างไฟล์ SVG placeholder const svgContent = ` <svg width="400" height="300" xmlns="http://www.w3.org/2000/svg"> <rect width="400" height="300" fill="#718096"/> <text x="200" y="150" font-family="Arial" font-size="20" fill="white" text-anchor="middle"> Plugin Preview</text> <text x="200" y="180" font-family="Arial" font-size="14" fill="#E2E8F0" text-anchor="middle">Preview Generation Failed</text> </svg> `; // เปลี่ยนนามสกุลเป็น .svg const svgPath = outputPath.replace('.png', '.svg'); fs.writeFileSync(svgPath, svgContent); console.log(` Created SVG placeholder: ${path.basename(svgPath)}`); return true; } catch (error) { console.error(` Error creating placeholder: ${error.message}`); return false; } }
// ดึงภาพตัวอย่างเริ่มต้นตามประเภท getDefaultPreviewImage(type) { const defaultImages = { 'executable_project': 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAwIiBoZWlnaHQ9IjMwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjQwMCIgaGVpZ2h0PSIzMDAiIGZpbGw9IiM0QTU1NjgiLz4KPHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHg9IjE4MCIgeT0iODAiPgo8dGV4dCB4PSIyMCIgeT0iMzAiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIzMCIgZmlsbD0iI0UyRThGMCI+8J+agDwvdGV4dD4KPC9zdmc+Cjx0ZXh0IHg9IjIwMCIgeT0iMTgwIiBmb250LWZhbWlseT0iQXJpYWwiIGZvbnQtc2l6ZT0iMjAiIGZpbGw9IndoaXRlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIj5FeGVjdXRhYmxlPC90ZXh0Pgo8L3N2Zz4=', 'batch_project': 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAwIiBoZWlnaHQ9IjMwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjQwMCIgaGVpZ2h0PSIzMDAiIGZpbGw9IiMzOEExNjkiLz4KPHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHg9IjE4MCIgeT0iODAiPgo8dGV4dCB4PSIyMCIgeT0iMzAiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIzMCIgZmlsbD0iI0YwRkZGNCI+8J+mhzwvdGV4dD4KPC9zdmc+Cjx0ZXh0IHg9IjIwMCIgeT0iMTgwIiBmb250LWZhbWlseT0iQXJpYWwiIGZvbnQtc2l6ZT0iMjAiIGZpbGw9IndoaXRlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIj5CYXRjaCBTY3JpcHQ8L3RleHQ+Cjwvc3ZnPg==', 'node': 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAwIiBoZWlnaHQ9IjMwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjQwMCIgaGVpZ2h0PSIzMDAiIGZpbGw9IiM2OEQzOTEiLz4KPHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHg9IjE4MCIgeT0iODAiPgo8dGV4dCB4PSIyMCIgeT0iMzAiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIzMCIgZmlsbD0iI0YwRkZGNCI+8J+UpzwvdGV4dD4KPC9zdmc+Cjx0ZXh0IHg9IjIwMCIgeT0iMTgwIiBmb250LWZhbWlseT0iQXJpYWwiIGZvbnQtc2l6ZT0iMjAiIGZpbGw9IndoaXRlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIj5Ob2RlLmpzPC90ZXh0Pgo8L3N2Zz4=', 'python': 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAwIiBoZWlnaHQ9IjMwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjQwMCIgaGVpZ2h0PSIzMDAiIGZpbGw9IiM0RkQxQzciLz4KPHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHg9IjE4MCIgeT0iODAiPgo8dGV4dCB4PSIyMCIgeT0iMzAiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIzMCIgZmlsbD0iI0U2RkZGQSI+8J+QjTwvdGV4dD4KPC9zdmc+Cjx0ZXh0IHg9IjIwMCIgeT0iMTgwIiBmb250LWZhbWlseT0iQXJpYWwiIGZvbnQtc2l6ZT0iMjAiIGZpbGw9IndoaXRlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIj5QeXRob248L3RleHQ+Cjwvc3ZnPg==', 'html': 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAwIiBoZWlnaHQ9IjMwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjQwMCIgaGVpZ2h0PSIzMDAiIGZpbGw9IiM5MENERjQiLz4KPHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHg9IjE4MCIgeT0iODAiPgo8dGV4dCB4PSIyMCIgeT0iMzAiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIzMCIgZmlsbD0iI0VCRjhGRiI+8J+MkDwvdGV4dD4KPC9zdmc+Cjx0ZXh0IHg9IjIwMCIgeT0iMTgwIiBmb250LWZhbWlseT0iQXJpYWwiIGZvbnQtc2l6ZT0iMjAiIGZpbGw9IndoaXRlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIj5XZWIgQXBwPC90ZXh0Pgo8L3N2Zz4=', 'default': 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAwIiBoZWlnaHQ9IjMwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjQwMCIgaGVpZ2h0PSIzMDAiIGZpbGw9IiM3MTgwOTYiLz4KPHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHg9IjE4MCIgeT0iODAiPgo8dGV4dCB4PSIyMCIgeT0iMzAiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIzMCIgZmlsbD0iI0Y3RkFGQyI+8J+UjDwvdGV4dD4KPC9zdmc+Cjx0ZXh0IHg9IjIwMCIgeT0iMTgwIiBmb250LWZhbWlseT0iQXJpYWwiIGZvbnQtc2l6ZT0iMjAiIGZpbGw9IndoaXRlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIj5QbHVnaW48L3RleHQ+Cjwvc3ZnPg==' }; return defaultImages[type] || defaultImages['default']; }
// วิเคราะห์ฟีเจอร์เพิ่มเติมของโปรเจค async analyzeProjectFeatures(projectPath, detectionResult) { const features = { hasPackageJson: false, hasNodeModules: false, hasRequirementsTxt: false, hasMainPy: false, hasAppPy: false, hasIndexHtml: false, hasElectron: false, hasTypeScript: false, hasLinter: false, hasTests: false, hasFlask: false, hasDjango: false, hasJupyter: false, hasCSS: false, hasJS: false, hasDocker: false, projectType: detectionResult.type };
try { const files = fs.readdirSync(projectPath); // ตรวจสอบไฟล์พื้นฐาน features.hasPackageJson = files.includes('package.json'); features.hasNodeModules = files.includes('node_modules'); features.hasRequirementsTxt = files.includes('requirements.txt'); features.hasMainPy = files.includes('main.py'); features.hasAppPy = files.includes('app.py'); features.hasIndexHtml = files.includes('index.html'); features.hasDocker = files.includes('Dockerfile') || files.includes('docker-compose.yml');
// วิเคราะห์ package.json สำหรับ Node.js if (features.hasPackageJson) { const packagePath = path.join(projectPath, 'package.json'); try { const packageData = JSON.parse(fs.readFileSync(packagePath, 'utf8')); const allDeps = { ...packageData.dependencies, ...packageData.devDependencies }; features.hasElectron = 'electron' in allDeps; features.hasTypeScript = 'typescript' in allDeps || files.some(f => f.endsWith('.ts')); features.hasLinter = 'eslint' in allDeps || 'tslint' in allDeps; features.hasTests = 'jest' in allDeps || 'mocha' in allDeps || 'jasmine' in allDeps; } catch (error) { console.warn('Could not parse package.json:', error.message); } }
// วิเคราะห์ requirements.txt สำหรับ Python if (features.hasRequirementsTxt) { const requirementsPath = path.join(projectPath, 'requirements.txt'); try { const requirements = fs.readFileSync(requirementsPath, 'utf8'); features.hasFlask = requirements.includes('Flask'); features.hasDjango = requirements.includes('Django'); features.hasJupyter = requirements.includes('jupyter') || requirements.includes('notebook'); } catch (error) { console.warn('Could not parse requirements.txt:', error.message); } }
// ตรวจสอบไฟล์เว็บ const webFiles = files.filter(f => f.endsWith('.css') || f.endsWith('.js') || f.endsWith('.html')); features.hasCSS = webFiles.some(f => f.endsWith('.css')); features.hasJS = webFiles.some(f => f.endsWith('.js'));
} catch (error) { console.warn(` Error analyzing features for ${projectPath}:`, error.message); }
return features; }
// ดึงข้อมูลโปรเจคที่มีปุ่ม getProjectsWithButtons() { return Array.from(this.projectsWithButtons.values()); }
// ดึงปุ่มสำหรับโปรเจคเฉพาะ getProjectButtons(projectPath) { const projectData = this.projectsWithButtons.get(projectPath); return projectData ? projectData.buttons : []; }
// สร้าง UI Interface สำหรับการแสดงผล generateProjectsUI() { const projects = this.getProjectsWithButtons(); const uiInterface = { sections: [], totalProjects: projects.length, totalButtons: 0, lastUpdated: new Date().toISOString() };
for (const projectData of projects) { const { projectInfo, buttons, features } = projectData; const section = { projectName: projectInfo.name, projectType: projectInfo.type, projectPath: projectInfo.path, confidence: projectInfo.confidence, buttons: buttons, features: features, buttonCount: buttons.length }; uiInterface.sections.push(section); uiInterface.totalButtons += buttons.length; }
return uiInterface; }
// --- ฟังก์ชันใหม่: สแกนหาโปรเจกต์ทั้งหมดอย่างครอบคลุม --- /** * สแกนหาโปรเจกต์ทั้งหมดจากตำแหน่งที่กำหนดไว้ */ async scanProjects() { console.log('[SystemDetector] ==========================================='); console.log('[SystemDetector] Starting a full project scan...'); this.projectsWithButtons.clear(); // ล้างข้อมูลเก่าก่อนเริ่มสแกน
const { app } = require('electron'); const isPackaged = app.isPackaged;
// --- ส่วนที่แก้ไข --- let pluginsPath; if (isPackaged) { // Production: มองหาโฟลเดอร์ plugins ข้างๆ ไฟล์ .exe pluginsPath = path.join(path.dirname(app.getPath('exe')), 'plugins'); } else { // Development: มองหาใน UserData (หรือตามที่คุณตั้งค่าไว้) // เราจะใช้ basePath สำหรับโฟลเดอร์อื่น แต่จะระบุ pluginsPath แยกต่างหาก const basePath = app.getAppPath(); pluginsPath = path.join(basePath, 'plugins'); // หรือ path.join(app.getPath('userData'), 'plugins') หากต้องการ }
const scanLocations = [ pluginsPath // สแกนที่ตำแหน่งของ plugins ที่ถูกต้องเพียงที่เดียว ];
for (const location of scanLocations) { console.log(`[SystemDetector] Scanning location: ${location}`); if (fs.existsSync(location)) { await this.scanDirectoryRecursive(location, 0, 3); // สแกนลึกสูงสุด 3 ระดับ } else { console.warn(`[SystemDetector] -> Location not found, skipping.`); } } console.log(`[SystemDetector] Scan complete. Found ${this.projectsWithButtons.size} actionable projects.`); console.log('[SystemDetector] ==========================================='); const uiData = this.generateProjectsUI(); return { success: true, projects: uiData.sections, count: uiData.totalProjects }; }
/** * สแกนโฟลเดอร์ย่อยๆ ข้���งใน (Recursive) */ async scanDirectoryRecursive(dirPath, currentDepth = 0, maxDepth = 3) { // หยุดสแกนถ้าลึกเกินที่กำหนด if (currentDepth > maxDepth) { return; }
try { const items = fs.readdirSync(dirPath, { withFileTypes: true });
for (const item of items) { const fullPath = path.join(dirPath, item.name); // ข้ามโฟลเดอร์ที่ไม่ควรสแกน if (item.name === 'node_modules' || item.name.startsWith('.') || item.name === 'vendor' || item.name === 'logs' || item.name === 'cache') { continue; }
if (item.isDirectory()) { // ตรวจสอบว่าโฟลเดอร์นี้เป็นโปรเจกต์หรือไม่ const detectionResult = await this.detect(fullPath); if (detectionResult.confidence > 30) { // ถ้ามั่นใจเกิน 30% ว่าเป็นโปรเจกต์ console.log(`[SystemDetector] -> Project detected: ${item.name} (Type: ${detectionResult.type}, Confidence: ${detectionResult.confidence}%)`); await this.generateProjectButtons(fullPath, detectionResult); } else { // ถ้าไม่ใช่โปรเจกต์ ให้ลองสแกนหาข้างในต่อ await this.scanDirectoryRecursive(fullPath, currentDepth + 1, maxDepth); } } } } catch (error) { console.warn(`[SystemDetector] Error scanning directory ${dirPath}:`, error.message); } }
// รีเฟรชการสแกนและสร้างปุ่ม (เก็บไว้เพื่อ backward compatibility) async refreshProjectScans() { console.log(' Refreshing project scans and button generation...'); this.projectsWithButtons.clear(); this.buttonGenerator.reset(); const { app } = require('electron'); const isPackaged = app.isPackaged;
// --- ส่วนที่แก้ไข --- let pluginsPath; if (isPackaged) { // Production: มองหาโฟลเดอร์ plugins ข้างๆ ไฟล์ .exe pluginsPath = path.join(path.dirname(app.getPath('exe')), 'plugins'); } else { // Development: มองหาใน Root ของโปรเจกต์ const basePath = app.getAppPath(); pluginsPath = path.join(basePath, 'plugins'); } // สแกนโปรเจคใหม่ใน directories ต่างๆ const projectDirs = [ pluginsPath, path.join(pluginsPath, 'Chahuadev_Studio_V.10.0.0'), path.join(pluginsPath, 'Chahuadev_Engine_ระบบต้นแบบ') ];
for (const dir of projectDirs) { if (fs.existsSync(dir)) { await this.scanProjectDirectory(dir); } }
console.log(` Refresh complete! Found ${this.projectsWithButtons.size} projects with buttons`); return this.generateProjectsUI(); }
// สแกนโฟลเดอร์โปรเจค async scanProjectDirectory(dirPath) { try { if (fs.statSync(dirPath).isFile()) { return; }
const items = fs.readdirSync(dirPath, { withFileTypes: true }); for (const item of items) { if (item.isDirectory()) { const fullPath = path.join(dirPath, item.name); // ตรวจสอบว่าเป็นโปรเจคหรือไม่ const detectionResult = await this.detect(fullPath); if (detectionResult.confidence > 30) { await this.generateProjectButtons(fullPath, detectionResult); } } } } catch (error) { console.warn(` Error scanning directory ${dirPath}:`, error.message); } }
/** * รายงานสถานะ detector */ async getStatus() { const strategiesStatus = {}; for (const [name, strategy] of Object.entries(this.strategies)) { strategiesStatus[name] = await strategy.getStatus(); } return { detector: 'SystemDetector', status: 'READY', supportedStrategies: Object.keys(this.strategies), detectionRules: this.detectionRules, projectsWithButtons: this.projectsWithButtons.size, totalButtons: this.buttonGenerator.getAllButtons().length, strategies: strategiesStatus, timestamp: Date.now() }; }}
module.exports = SystemDetector; 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387/** * Tamper Detection System - Anti-Modification Protection * ระบบตรวจจับการแก้ไขไฟล์และป้องกันการดัดแปลง * * Features: * - Real-time file integrity monitoring * - Script injection detection * - Checksum validation * - Warning notifications (Thai/English) */
const fs = require('fs');const path = require('path');const crypto = require('crypto');const { dialog, app } = require('electron');
// ตรวจสอบว่า chokidar มีหรือไม่ (สำหรับ dev mode)let chokidar = null;try { chokidar = require('chokidar');} catch (error) { console.log(' chokidar not available - file watching disabled');}
class TamperDetector { constructor() { this.isMonitoring = false; this.originalChecksums = {}; // ตรวจสอบว่าเป็น development หรือ production this.isPackaged = app ? app.isPackaged : false; this.appPath = this.getAppBasePath(); console.log(` TamperDetector mode: ${this.isPackaged ? 'PRODUCTION' : 'DEVELOPMENT'}`); console.log(` App path: ${this.appPath}`); // กำหนดไฟล์ที่ต้องตรวจสอบตาม environment if (this.isPackaged) { // Production: ตรวจไฟล์ asar และไฟล์สำคัญ this.criticalFiles = [ 'resources/app.asar', // ไฟล์หลักที่บีบแล้ว 'checksums.json', 'checksums.sig', 'public_key.pem' ]; } else { // Development: ตรวจ source files this.criticalFiles = [ 'main.js', 'preload.js', 'validation_gateway.js', 'modules/executor.js', 'modules/system-detector.js', 'modules/plugin-manager.js' ]; } this.warningMessages = { thai: { title: ' ตรวจพบการแก้ไขไฟล์', fileModified: 'พบการแก้ไขไฟล์ระบบ:', scriptInjection: 'ตรวจพบการแทรกสคิปต์ต้องสงสัย:', checksumMismatch: 'Checksum ไม่ตรงกัน - ไฟล์อาจถูกดัดแปลง:', securityThreat: 'การกระทำนี้อาจเป็นภัยต่อความปลอดภัย\nโปรแกรมจะหยุดทำงานเพื่อป้องกันความเสียหาย', actions: 'การดำเนินการ:\n กรุณาตรวจสอบไฟล์\n คืนค่าไฟล์จาก backup\n ติดต่อฝ่ายสนับสนุน', buttons: ['ออกจากโปรแกรม', 'ข้ามการตรวจสอบ (ไม่แนะนำ)'] }, english: { title: ' File Modification Detected', fileModified: 'System file modification detected:', scriptInjection: 'Suspicious script injection detected:', checksumMismatch: 'Checksum mismatch - file may be tampered:', securityThreat: 'This action may pose a security risk.\nApplication will terminate to prevent damage.', actions: 'Recommended actions:\n Verify file integrity\n Restore from backup\n Contact support team', buttons: ['Exit Application', 'Skip Check (Not Recommended)'] } }; console.log(' Tamper Detection System initialized'); }
/** * ได้ path ฐานของแอปพลิเคชัน */ getAppBasePath() { if (!app) { // หากไม่มี app object ให้ใช้ __dirname (สำหรับ testing) return path.join(__dirname, '..'); }
if (this.isPackaged) { // Production: ไฟล์อยู่ใน .exe directory // path ควรจะเป็น: C:\Program Files\AppName\ หรือ .\dist\win-unpacked\ const execPath = process.execPath; // path ของ .exe const appDir = path.dirname(execPath); // directory ที่มี .exe console.log(` Production app directory: ${appDir}`); return appDir; } else { // Development: ใช้ __dirname return path.join(__dirname, '..'); } }
/** * เริ่มต้นระบบตรวจจับการแก้ไข */ async startMonitoring() { if (this.isMonitoring) { console.log(' Tamper detection already running'); return; }
try { // โหลด checksums ที่ถูกต้อง await this.loadOriginalChecksums(); // ตรวจสอบไฟล์ครั้งแรก await this.performInitialCheck(); // เริ่มต้น file watcher this.startFileWatcher(); this.isMonitoring = true; console.log(' Tamper detection monitoring started'); } catch (error) { console.error(' Failed to start tamper detection:', error); } }
/** * โหลด checksums ที่ถูกต้อง */ async loadOriginalChecksums() { try { const checksumsPath = path.join(this.appPath, 'checksums.json'); if (fs.existsSync(checksumsPath)) { const data = fs.readFileSync(checksumsPath, 'utf8'); this.originalChecksums = JSON.parse(data); console.log(' Loaded checksums for', Object.keys(this.originalChecksums).length, 'files'); } else { console.warn(' checksums.json not found - generating new checksums'); await this.generateCurrentChecksums(); } } catch (error) { console.error(' Error loading checksums:', error); throw error; } }
/** * สร้าง checksums ปัจจุบัน */ async generateCurrentChecksums() { for (const file of this.criticalFiles) { const filePath = path.join(this.appPath, file); if (fs.existsSync(filePath)) { const checksum = await this.calculateFileChecksum(filePath); this.originalChecksums[file] = checksum; } } }
/** * คำนวณ checksum ของไฟล์ */ async calculateFileChecksum(filePath) { return new Promise((resolve, reject) => { const hash = crypto.createHash('sha256'); const stream = fs.createReadStream(filePath); stream.on('data', (data) => hash.update(data)); stream.on('end', () => resolve(hash.digest('hex'))); stream.on('error', reject); }); }
/** * ตรวจสอบไฟล์ครั้งแรก */ async performInitialCheck() { console.log(' Performing initial integrity check...'); for (const file of this.criticalFiles) { await this.checkFileIntegrity(file); } console.log(' Initial integrity check completed'); }
/** * ตรวจสอบความถูกต้องของไฟล์ */ async checkFileIntegrity(fileName) { try { const filePath = path.join(this.appPath, fileName); if (!fs.existsSync(filePath)) { this.showTamperWarning('thai', 'fileModified', fileName + ' (ไฟล์หายไป/File missing)'); return false; }
const currentChecksum = await this.calculateFileChecksum(filePath); const originalChecksum = this.originalChecksums[fileName];
if (originalChecksum && currentChecksum !== originalChecksum) { console.log(` Checksum mismatch for ${fileName}`); console.log(` Original: ${originalChecksum}`); console.log(` Current: ${currentChecksum}`); this.showTamperWarning('thai', 'checksumMismatch', fileName); return false; }
// ตรวจสอบการแทรกสคิปต์ if (await this.detectScriptInjection(filePath)) { this.showTamperWarning('thai', 'scriptInjection', fileName); return false; }
return true; } catch (error) { console.error(` Error checking ${fileName}:`, error); return false; } }
/** * ตรวจจับการแทรกสคิปต์ต้องสงสัย */ async detectScriptInjection(filePath) { try { const content = fs.readFileSync(filePath, 'utf8'); // รายการ patterns ต้องสงสัย const suspiciousPatterns = [ /eval\s*\(/gi, // eval() calls /Function\s*\(/gi, // Function constructor /document\.write/gi, // document.write /innerHTML\s*=/gi, // innerHTML assignments /outerHTML\s*=/gi, // outerHTML assignments /script\s*>/gi, // script tags /javascript\s*:/gi, // javascript: protocol /on\w+\s*=/gi, // event handlers (onclick, etc.) /setTimeout\s*\(/gi, // setTimeout with strings /setInterval\s*\(/gi, // setInterval with strings /\.appendChild/gi, // DOM manipulation /\.createElement\s*\(\s*['"]script/gi, // Creating script elements /base64/gi, // base64 encoded content /atob\s*\(/gi, // base64 decode /btoa\s*\(/gi, // base64 encode /unescape\s*\(/gi, // unescape /decodeURI/gi, // URI decoding /\\x[0-9a-f]{2}/gi, // hex encoded strings /\\u[0-9a-f]{4}/gi, // unicode encoded strings ];
for (const pattern of suspiciousPatterns) { if (pattern.test(content)) { console.log(` Suspicious pattern detected in ${path.basename(filePath)}: ${pattern}`); return true; } }
return false; } catch (error) { console.error(' Error detecting script injection:', error); return false; } }
/** * เริ่มต้น file watcher */ startFileWatcher() { if (this.isPackaged) { console.log(' File watcher disabled in production - monitoring asar integrity instead'); return; }
if (!chokidar) { console.log(' File watcher disabled - chokidar not available'); return; }
const watchPaths = this.criticalFiles.map(file => path.join(this.appPath, file) );
this.watcher = chokidar.watch(watchPaths, { ignored: /(^|[\/\\])\../, // ignore dotfiles persistent: true, ignoreInitial: true });
this.watcher .on('change', (filePath) => { const fileName = path.relative(this.appPath, filePath); console.log(` File changed: ${fileName}`); setTimeout(() => this.checkFileIntegrity(fileName), 1000); // รอ 1 วินาที }) .on('unlink', (filePath) => { const fileName = path.relative(this.appPath, filePath); console.log(` File deleted: ${fileName}`); this.showTamperWarning('thai', 'fileModified', fileName + ' (ถูกลบ/Deleted)'); });
console.log(' File watcher started for', this.criticalFiles.length, 'critical files'); }
/** * แสดงข้อความเตือนการดัดแปลง */ showTamperWarning(language, type, fileName) { const msg = this.warningMessages[language]; const message = `${msg[type]} ${fileName}\n\n${msg.securityThreat}\n\n${msg.actions}`; // แสดงทั้งภาษาไทยและอังกฤษ const englishMsg = this.warningMessages.english; const fullMessage = `${message}\n\n--- English ---\n${englishMsg[type]} ${fileName}\n\n${englishMsg.securityThreat}\n\n${englishMsg.actions}`;
dialog.showMessageBox({ type: 'warning', title: `${msg.title} / ${englishMsg.title}`, message: fullMessage, buttons: [...msg.buttons, ...englishMsg.buttons], defaultId: 0, cancelId: 1 }).then((result) => { if (result.response === 0 || result.response === 2) { // ออกจากโปรแกรม console.log(' Application terminated due to security threat'); process.exit(1); } else { console.log(' User chose to skip security check - WARNING!'); } }); }
/** * หยุดการตรวจสอบ */ stopMonitoring() { if (this.watcher && chokidar) { this.watcher.close(); } this.isMonitoring = false; console.log(' Tamper detection monitoring stopped'); }
/** * ตรวจสอบแบบ manual */ async manualCheck() { console.log(' Manual integrity check requested...'); let allFilesOk = true; for (const file of this.criticalFiles) { const isOk = await this.checkFileIntegrity(file); if (!isOk) { allFilesOk = false; } } if (allFilesOk) { console.log(' All files passed integrity check'); dialog.showMessageBox({ type: 'info', title: ' ตรวจสอบเสร็จสิ้��� / Check Complete', message: 'ไฟล์ทั้งหมดผ่านการตรวจสอบความถูกต้อง\n\nAll files passed integrity verification.', buttons: ['ตกลง / OK'] }); } else { console.log(' Some files failed integrity check'); } return allFilesOk; }}
module.exports = TamperDetector;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144@echo offchcp 65001 > nulcolor 0Atitle Chahuadev Framework Desktop Builder
echo.
:MENUclsecho ╔════════════════════════════════════════════════════════════════════════════════╗echo ║ 🚀 Chahuadev Framework Desktop Builder ║echo ║ Version 1.0.0 ║echo ╚════════════════════════════════════════════════════════════════════════════════╝echo.echo.echo --- Common Tasks ---echo [1] npm install (ติดตั้ง Dependencies)echo [2] npm start (รันโปรเจกต์)echo [3] npm run dev (รันในโหมดพัฒนา)echo [4] npm test (รันเทส)echo.echo --- Build & Package ---echo [7] npm run build (Build โปรเจกต์)echo [8] npm run pack (Pack เป็น Unpacked Folder)echo [9] npm run dist (สร้างไฟล์ติดตั้ง)echo.echo --- Utilities ---echo [5] Open Folder (เปิดโฟลเดอร์นี้ใน Explorer)echo [6] Open VS Code (เปิดโฟลเดอร์นี้ใน VS Code)echo.echo [0] Exit (ออกจากสคริปต์)echo.echo ===================================================echo.
:: รับ Input จากผู้ใช้set /p "CHOICE=Please select an option and press Enter: "
:: ตรวจสอบตัวเลือกif "%CHOICE%"=="1" goto INSTALLif "%CHOICE%"=="2" goto STARTif "%CHOICE%"=="3" goto DEVif "%CHOICE%"=="4" goto TESTif "%CHOICE%"=="5" goto OPEN_FOLDERif "%CHOICE%"=="6" goto OPEN_CODEif "%CHOICE%"=="7" goto BUILDif "%CHOICE%"=="8" goto PACKif "%CHOICE%"=="9" goto DISTif "%CHOICE%"=="0" goto EXIT
:: ถ้าพิมพ์ผิดecho Invalid choice. Please try again.pausegoto MENU
:: =================================:: ## Action Sections ##:: =================================
:INSTALLclsecho ########## Running npm install ##########echo.call npm installecho.echo ########## 'npm install' finished. ##########pausegoto MENU
:STARTclsecho ########## Running npm start ##########echo.call npm startecho.echo ########## 'npm start' finished or was terminated. ##########pausegoto MENU
:DEVclsecho ########## Running npm run dev ##########echo.call npm run devecho.echo ########## 'npm run dev' finished or was terminated. ##########pausegoto MENU
:TESTclsecho ########## Running npm test ##########echo.call npm testecho.echo ########## 'npm test' finished. ##########pausegoto MENU
:BUILDclsecho ########## Running npm run build ##########echo.call npm run buildecho.echo ########## 'npm run build' finished. ##########pausegoto MENU
:PACKclsecho ########## Running npm run pack ##########echo.call npm run packecho.echo ########## 'npm run pack' finished. ##########pausegoto MENU
:DISTclsecho ########## Running npm run dist ##########echo.call npm run distecho.echo ########## 'npm run dist' finished. ##########pausegoto MENU
:OPEN_FOLDERclsecho ########## Opening current folder... ##########explorer .goto MENU
:OPEN_CODEclsecho ########## Opening in VS Code... ##########code .goto MENU
:EXITexit /b123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261{ "name": "chahuadev-framework", "version": "6.0.0", "description": "Chahuadev Framework - NPM Project Manager Desktop App", "main": "main.js", "scripts": { "prestart": "node -e \"const fs=require('fs'); if(!fs.existsSync('private_key.pem')||!fs.existsSync('public_key.pem')){console.warn('⚠️ Warning: Security keys not found. Build integrity protection may be disabled.');} else {console.log('🔐 Security keys found - integrity protection active');}\"", "start": "electron .", "dev": "electron . --dev", "dev-mode": "electron . --dev-mode", "generate-checksums": "node generate-checksums.js", "build": "cross-env NODE_ENV=production npm run docs:copy && npm run generate-checksums && electron-builder", "pack": "cross-env NODE_ENV=production npm run docs:copy && npm run generate-checksums && electron-builder --dir", "dist": "cross-env NODE_ENV=production electron-builder --publish=always", "build-win": "cross-env NODE_ENV=production npm run docs:copy && npm run generate-checksums && electron-builder --win", "build-msi": "cross-env NODE_ENV=production npm run docs:copy && npm run generate-checksums && electron-builder --win msi --x64", "build-exe": "cross-env NODE_ENV=production npm run generate-checksums && electron-builder --win portable --x64", "build-nsis": "cross-env NODE_ENV=production npm run docs:copy && npm run generate-checksums && electron-builder --win nsis --x64", "build:secure": "cross-env NODE_ENV=production electron-builder --win --publish=never", "build:secure-msi": "cross-env NODE_ENV=production node scripts/secure-build.js && electron-builder --win msi --x64", "build:fort-knox": "echo ' Starting Fort-Knox Level Build...' && cross-env NODE_ENV=production node scripts/secure-build.js", "docs:copy": "node scripts/copy-user-guides.js", "docs:status": "node scripts/copy-user-guides.js --status", "docs:help": "node scripts/copy-user-guides.js --help", "build:win": "cross-env NODE_ENV=production electron-builder --win", "build:msi": "cross-env NODE_ENV=production electron-builder --win --publish=never", "pack:msi": "cross-env NODE_ENV=production electron-builder --win --dir", "dist:msi": "cross-env NODE_ENV=production electron-builder --win msi --publish=always", "build:dev": "cross-env CSC_IDENTITY_AUTO_DISCOVERY=false npm run build", "build:prod": "cross-env NODE_ENV=production npm run security:check && npm run generate-checksums && electron-builder", "build:unsigned": "cross-env CSC_IDENTITY_AUTO_DISCOVERY=false electron-builder --win", "build:signed": "cross-env NODE_ENV=production electron-builder --win", "prepare:signing": "echo 'Preparing Code Signing...' && echo 'Set CSC_LINK and CSC_KEY_PASSWORD environment variables' && echo 'Example: export CSC_LINK=path/to/certificate.p12' && echo 'Example: export CSC_KEY_PASSWORD=your_certificate_password'", "ui": "electron .", "projects": "cmd /c \"cd chahuadev-framework && npm run project:list && pause\"", "install-sample": "cmd /c \"cd chahuadev-framework && npm run install:sample\"", "start-sample": "cmd /c \"cd chahuadev-framework && npm run start:sample\"", "start-studio": "cmd /c \"cd chahuadev-framework && npm run project:start Chahuadev_Studio_V.10.0.0\"", "install-studio": "cmd /c \"cd chahuadev-framework && npm run project:install Chahuadev_Studio_V.10.0.0\"", "validation": "node validation_gateway.js", "test": "node test/test-runner.js", "postinstall": "electron-builder install-app-deps", "test:packed": "echo \"ทดสอบแอปที่ Pack แล้วในโหมดพัฒนา:\" && echo \"./dist/win-unpacked/\\\"Chahuadev Framework.exe\\\" --dev-mode\"", "studio:dev": "cd plugins/Chahuadev_Studio_V.10.0.0 && npm run dev", "studio:build": "cd plugins/Chahuadev_Studio_V.10.0.0 && npm run build", "studio:install": "cd plugins/Chahuadev_Studio_V.10.0.0 && npm install", "plugins:generate": "node generate-manifests.js", "framework:status": "node -e \"console.log('Chahuadev Framework Status: Ready')\"", "quick": "electron . && echo 'Quick Launch Complete'", "test:splash": "echo \" Testing Splash Screen System...\" && electron . --dev-mode", "test:logo": "echo \" Logo System Test:\" && echo \" 1. Checking icon.png...\" && (ls icon.png > nul 2>&1 && echo \" [SUCCESS] icon.png found\" || echo \" [ERROR] icon.png missing\") && echo \" 2. Checking splash.html...\" && (ls splash.html > nul 2>&1 && echo \" [SUCCESS] splash.html found\" || echo \" [ERROR] splash.html missing\") && echo \" 3. Testing app...\" && electron . --dev-mode", "security:audit": "npm audit --audit-level=moderate", "security:audit-fix": "npm audit fix --force", "security:check": "npm run security:audit && npm run security:outdated && npm run security:licenses", "security:outdated": "npm outdated --depth=0", "security:licenses": "echo \" Checking package licenses...\" && npx license-checker --summary", "security:update": "npx npm-check-updates -u && npm install && npm run security:audit", "security:report": "echo \" Generating Security Report...\" && npm audit --json > security-audit.json && npm outdated --json > outdated-packages.json && echo \"[SUCCESS] Security reports generated\"", "security:daily": "echo \" Daily Security Check...\" && npm run security:check && echo \"[SUCCESS] Daily security check completed\"", "dist:exe": "electron-builder --win portable --publish=always", "dist:dev": "electron-builder --publish=never", "build:simple": "electron-builder", "npm:prepare": "node scripts/prepare-npm-package.js", "npm:build": "npm run build:win && npm run npm:prepare", "npm:publish": "cd npm-package && npm publish", "npm:publish-test": "cd npm-package && npm publish --dry-run", "build:windows": "cross-env NODE_ENV=production npm run docs:copy && npm run generate-checksums && electron-builder --win --x64 --ia32", "build:linux": "cross-env NODE_ENV=production npm run docs:copy && npm run generate-checksums && electron-builder --linux --x64", "build:linux:native": "cross-env NODE_ENV=production electron-builder --linux --x64", "build:linux:wsl": "wsl bash build-linux-wsl.sh", "build:all": "cross-env NODE_ENV=production npm run docs:copy && npm run generate-checksums && electron-builder --win --x64 --ia32 --linux --x64", "build:all:smart": "node scripts/build-all-platforms.js" }, "keywords": [ "chahuadev", "framework", "npm", "electron", "desktop" ], "author": "Chahua Development Thailand", "license": "SEE LICENSE IN LICENSE.md", "dependencies": { "acorn": "^8.15.0", "adm-zip": "^0.5.16", "archiver": "^4.0.2", "axios": "^1.11.0", "canvas": "^3.1.2", "cheerio": "^1.1.0", "child_process": "*", "commander": "^11.0.0", "cors": "^2.8.5", "crypto": "^1.0.1", "cytoscape-svg": "^0.4.0", "exceljs": "^4.1.1", "express": "^4.21.2", "fs-extra": "^11.0.0", "glob": "^11.0.3", "html2canvas": "^1.4.1", "jsonwebtoken": "^9.0.2", "mammoth": "^1.9.1", "mime-types": "^2.1.35", "monaco-editor": "^0.45.0", "os": "*", "path": "*", "pdf-parse": "^1.1.1", "rimraf": "^6.1.3", "util": "*", "uuid": "^11.1.0", "ws": "^8.18.3", "yauzl": "^3.2.0" }, "devDependencies": { "audit-ci": "^7.1.0", "concurrently": "^8.2.0", "cross-env": "^7.0.3", "electron": "^38.0.0", "electron-builder": "^26.8.1", "electron-updater": "^6.6.2", "javascript-obfuscator": "^0.14.3", "license-checker": "^25.0.1", "nodemon": "^3.0.1", "npm-check-updates": "^17.0.6", "retire": "^5.0.0", "webpack-obfuscator": "^0.6.0" }, "build": { "asar": true, "appId": "com.chahuadev.framework", "productName": "Chahuadev Framework", "artifactName": "${productName}-${version}.${ext}", "directories": { "output": "dist/${productName}-${version}", "buildResources": "build" }, "extraFiles": [ { "from": "icon.png", "to": "." }, { "from": "logo.png", "to": "." }, { "from": "logo.ico", "to": "." }, { "from": "splash.html", "to": "." }, { "from": "build_assets/plugins", "to": "plugins" } ], "extraResources": [ { "from": "vendor/node-v20.15.1-win-x64/", "to": "node" } ], "files": [ "main.js", "app.html", "splash.html", "preload.js", "package.json", "icon.png", "web/**/*", "modules/**/*", "strategies/**/*", "backend/**/*", "tools/**/*", "video/**/*", "!plugins/**/*", "projects/**/*", "vendor/**/*", "config/**/*", "validation_gateway.js", "cli.js", "generate-manifests.js", "checksums.json", "checksums.sig", "public_key.pem", "!private_key.pem", "!node_modules/.cache/**/*", "!dist/**/*", "!projects/*/node_modules/**/*", "!projects/*/dist/**/*", "!builder.html", "!generated_*/**/*", "!**/logs/**/*", "!test/**/*", "!docs/**/*", "!*.log" ], "win": { "target": [ { "target": "nsis", "arch": [ "x64", "ia32"
] }, { "target": "msi", "arch": [ "x64", "ia32" ] }, { "target": "portable", "arch": [ "x64", "ia32" ] }, { "target": "dir", "arch": [ "x64", "ia32" ] } ], "icon": "icon.png", "requestedExecutionLevel": "asInvoker", "signAndEditExecutable": false, "verifyUpdateCodeSignature": false, "artifactName": "${productName}-${version}-${os}-${arch}.${ext}" }, "mac": { "target": "dmg", "icon": "icon.png" }, "linux": { "target": "AppImage", "icon": "icon.png" }, "nsis": { "oneClick": false, "allowToChangeInstallationDirectory": true, "createDesktopShortcut": true, "createStartMenuShortcut": true, "shortcutName": "Chahuadev Framework" }, "msi": { "oneClick": false, "warningsAsErrors": false, "additionalWixArgs": [ "-cultures:th-TH" ] }, "generateUpdatesFilesForAllChannels": true }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354# CHAHUADEV NON-COMMERCIAL & ACCEPTABLE USE LICENSE
Copyright (c) 2026 Chahuadev. All rights reserved.
This software and its source code are provided for educational, personal, and open-source community use. By downloading, accessing, or using this software, you agree to the following conditions:
---
## 1. FREE DISTRIBUTION ONLY (การแจกจ่ายต้องฟรีเท่านั้น)
You are permitted to download, copy, modify, and distribute the software and its source code, provided that such distribution is **strictly free of charge**.
---
## 2. NO COMMERCIAL USE (ห้ามใช้หรือดัดแปลงเพื่อการค้า)
You may **NOT** use, modify, distribute, or incorporate this software (or any of its parts) for any commercial purposes. This includes, but is not limited to:
- Selling the software or derived versions.- Locking the software behind a paywall or subscription.- Using the software to provide commercial services.- Placing advertisements within the software.
---
## 3. ACCEPTABLE USE / NO MALICIOUS USE (ห้ามใช้ในทางที่ผิด)
This software must not be used for any illegal, malicious, or harmful activities. You are strictly prohibited from using this codebase to:
- Create malware, ransomware, or any destructive software.- Bypass security systems, steal data, or perform unauthorized access.- Violate any local, national, or international laws.
If the software is found to be used in violation of these terms, your license to use it is immediately and permanently terminated without notice.
---
## 4. ATTRIBUTION (ต้องแสดงแหล่งที่มา)
Any permitted distribution or modification must clearly credit the original author:
> Original work by **Chahuadev** — https://chahuadev.com
You may not remove, obscure, or alter any copyright notices or attribution present in the source code or documentation.
---
## 5. DISCLAIMER OF LIABILITY (ข้อสงวนสิทธิ์ความรับผิดชอบ)
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---
For questions regarding licensing, contact: **Chahuadev** via https://chahuadev.com123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143# @chahuadev/framework
The official core executable framework for Chahuadev.
<div align="center">
<p align="center"> <img src="https://huggingface.co/datasets/chahuadev/chahuadev-emoji-cleaner-tool/blob/main/chahuadev-framework.png" width="600" alt="Chahuadev Framework"></p>
<p align="center"> <a href="https://www.npmjs.com/package/@chahuadev/framework"><img src="https://img.shields.io/npm/v/@chahuadev/framework?style=for-the-badge&color=blue" alt="NPM Version"></a> <a href="https://www.npmjs.com/package/@chahuadev/framework"><img src="https://img.shields.io/npm/dt/@chahuadev/framework?style=for-the-badge&color=success" alt="NPM Downloads"></a> <a href="https://huggingface.co/datasets/chahuadev/chahuadev-framework-binaries"><img src="https://img.shields.io/badge/Hugging%20Face-Dataset-FFD21E?style=for-the-badge" alt="Hugging Face Dataset"></a></p>
> ⏳ **Development Journey:** This framework is the proud result of **1 full year of dedicated development**. What began as a simple concept evolved into a highly advanced, secure, and robust architecture. Every line of code was meticulously crafted to ensure maximum stability and a premium experience for developers.
</div>
---
## � Running on Linux / WSL2 (Ubuntu)
First install the required system libraries (one-time setup):
```bashsudo apt-get update && sudo apt-get install -y \ libnss3 libatk1.0-0 libatk-bridge2.0-0 libcups2 \ libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 \ libxrandr2 libgbm1 libasound2```
Then run the AppImage:
```bashchmod +x "Chahuadev-Framework.AppImage"DISPLAY=:0 WAYLAND_DISPLAY=wayland-0 \ ./"Chahuadev-Framework.AppImage" \ --appimage-extract-and-run --no-sandbox --disable-gpu```
> **WSL2 tip:** Copy to WSL native filesystem first:> ```bash> # Path after: npm install -g @chahuadev/framework> # (no sudo)> cp ~/.npm-global/lib/node_modules/@chahuadev/framework/bin/Chahuadev-Framework.AppImage /tmp/ChahuadevFramework.AppImage> # (with sudo)> # cp /usr/lib/node_modules/@chahuadev/framework/bin/Chahuadev-Framework.AppImage /tmp/ChahuadevFramework.AppImage> chmod +x /tmp/ChahuadevFramework.AppImage> DISPLAY=:0 WAYLAND_DISPLAY=wayland-0 /tmp/ChahuadevFramework.AppImage \> --appimage-extract-and-run --no-sandbox --disable-gpu> ```
---
## �🛡️ CRITICAL SECURITY WARNING - FORTRESS PROTECTION
### Maximum Security Architecture- **Intelligent OS Routing**: Automatically detects and securely isolates platform-specific binaries.- **Strict Execution Boundaries**: Prevents unauthorized cross-platform executions and corrupted loads.- **Anti-Hack Protection System**: Built-in safeguards against malicious executable swapping.- **Dependency Isolation**: Operates securely via standalone binaries without bloating your system.
---
## ⚙️ Installation & Usage
> **Multi-Platform Support:** This framework runs seamlessly on **Windows (x64, ia32)** and **Linux (x64)**.> Our system automatically detects your operating system and securely downloads the required binary behind the scenes.
### Global Install (Recommended for CLI)If you want to use the framework from your terminal anywhere on your system:
```bashnpm install -g @chahuadev/framework --foreground-scripts --force
```---
### When you install:**1. npm detects your OS and architecture2. Installs only the required platform-specific package3. index.js routes to the correct executable
This ensures:- Minimal disk space usage (only your OS binary)- No cross-platform conflicts- Automatic binary selection
---
## Platform Support
| Platform | Architecture | Status | Format ||----------|-------------|--------|--------|| Windows | 64-bit (x64) | Supported | EXE || Windows | 32-bit (ia32) | Supported | EXE || Linux | 64-bit (x64) | Supported | AppImage || macOS | Intel (x64) | Coming Soon | DMG/App || macOS | Apple Silicon (arm64) | Coming Soon | DMG/App |
---
## Package Structure
@chahuadev/├── framework/ │ └── index.js │ └── install.js │ └── package.json │ └── README.md ---
## Troubleshooting
### "Command not found: chahuadev-framework"Make sure you installed globally:```bashnpm install -g @chahuadev/framework --foreground-scripts --force```
### "Module not found"If using locally, ensure it's installed:```bashnpm install -g @chahuadev/framework --foreground-scripts --force```
### "Unsupported platform"Your OS/architecture combination is not yet supported. Check the Platform Support table above.
---
## LicenseNon-Commercial & Acceptable Use — See [LICENSE.md](LICENSE.md)
---
1234567891011121314151617181920212223242526#!/usr/bin/env node'use strict';const path = require('path');const { spawnSync } = require('child_process');const fs = require('fs');const os = require('os');
const platform = os.platform();let exeName = '';
if (platform === 'win32') { exeName = 'Chahuadev-Framework.exe';} else { console.error(`Chahuadev Framework does not support ${platform} yet.`); process.exit(1);}
const exePath = path.join(__dirname, 'bin', exeName);if (!fs.existsSync(exePath)) { console.error(`Executable not found: ${exePath}`); console.error('Try running "npm install" again to download the binary.'); process.exit(1);}
const result = spawnSync(exePath, process.argv.slice(2), { stdio: 'inherit' });process.exit(result.status ?? 0);12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273'use strict';const fs = require('fs');const path = require('path');const https = require('https');const os = require('os');
const platform = os.platform();const arch = os.arch();
const R2_BASE = 'https://pub-419d22521da042dfb27d1f404b3eb8a6.r2.dev';
let downloadUrl = '';let fileName = '';
if (platform === 'win32') { downloadUrl = `${R2_BASE}/Chahuadev-Framework.exe`; fileName = 'Chahuadev Framework.exe';} else if (platform === 'linux') { downloadUrl = `${R2_BASE}/Chahuadev-Framework.AppImage`; fileName = 'Chahuadev Framework.AppImage';} else { console.warn(`Chahuadev Framework does not support ${platform} ${arch} yet.`); process.exit(0);}
const binDir = path.join(__dirname, 'bin');if (!fs.existsSync(binDir)) fs.mkdirSync(binDir, { recursive: true });
const filePath = path.join(binDir, fileName);console.log(`Downloading Chahuadev Framework for ${platform} (${arch})...`);console.log('Please wait, this may take a few minutes.\n');
function downloadFile(url, dest) { https.get(url, (response) => { if (response.statusCode === 301 || response.statusCode === 302) { return downloadFile(response.headers.location, dest); } if (response.statusCode !== 200) { console.error(`Download failed: HTTP ${response.statusCode}`); process.exit(1); } const totalBytes = parseInt(response.headers['content-length'], 10); let downloadedBytes = 0; const file = fs.createWriteStream(dest); response.on('data', (chunk) => { downloadedBytes += chunk.length; if (!isNaN(totalBytes)) { const percent = ((downloadedBytes / totalBytes) * 100).toFixed(1); const dlMB = (downloadedBytes / (1024 * 1024)).toFixed(1); const totalMB = (totalBytes / (1024 * 1024)).toFixed(1); const filled = Math.round(30 * downloadedBytes / totalBytes); const bar = '#'.repeat(filled) + '-'.repeat(30 - filled); process.stdout.write(`\r[${bar}] ${percent}% (${dlMB} MB / ${totalMB} MB)`); } else { process.stdout.write(`\rDownloading... ${(downloadedBytes / (1024 * 1024)).toFixed(1)} MB`); } }); response.pipe(file); file.on('finish', () => { file.close(); console.log('\n\nDownload completed.'); console.log(`Saved to: ${dest}\n`); if (platform !== 'win32') fs.chmodSync(dest, 0o755); }); }).on('error', (err) => { fs.unlink(dest, () => {}); console.error('\nDownload failed:', err.message); process.exit(1); });}
downloadFile(downloadUrl, filePath);12345678910111213141516{ "name": "@chahuadev/framework", "version": "6.0.1", "description": "Chahuadev Framework", "main": "index.js", "bin": { "chahuadev-framework": "index.js" }, "scripts": { "postinstall": "node install.js" }, "license": "SEE LICENSE IN LICENSE.md", "publishConfig": { "access": "public" }}.gitattributes+7-60
.gitignoreAdded+84
.wslconfigAdded+11
ApiTraceDebugger.jsAdded+284
LICENSE.mdAdded+54
README.md+263-3
app.htmlAdded
auth-dialog.jsAdded+171
backend/utils/inspector-worker.jsAdded+169
backend/utils/project-inspector-ipc.jsAdded+247
backend/utils/project-inspector.jsAdded+1813
build-desktop.batAdded+220
build-linux-wsl.shAdded+90
build_assets/plugins/.gitkeepAdded+2
checksums.jsonAdded+13
checksums.sigAdded+1
config/default.jsonAdded+102
config/obfuscator.config.jsAdded+143
config/production.jsonAdded+102
debug-manager.jsAdded+501
debugger.htmlAdded+884
debugger.jsAdded+659
generate-checksums.jsAdded+73
generate-manifests.jsAdded+124
junk-map-layout.jsonAdded+242
main.jsAdded+2464
modules/button-generator.jsAdded+621
modules/cache-manager.jsAdded+350
modules/callback-hub.jsAdded+202
modules/callback-logger.jsAdded+147
modules/cli.jsAdded+301
modules/context-manager.jsAdded+368
modules/error-handler.jsAdded+380
modules/executor.jsAdded+242
modules/health-monitor.jsAdded+207
modules/key-system.jsAdded+167
modules/plugin-manager.jsAdded+96
modules/retry-controller.jsAdded+131
modules/rollback-manager.jsAdded+274
modules/security-logger.jsAdded+346
modules/svg-icons.jsAdded+253
modules/system-detector.jsAdded+1157
modules/tamper-detector.jsAdded+387
npm-runner.batAdded+144
package.jsonAdded+261
packages/@chahuadev/framework/LICENSE.mdAdded+54
packages/@chahuadev/framework/README.mdAdded+143
packages/@chahuadev/framework/index.jsAdded+26
packages/@chahuadev/framework/install.jsAdded+73
packages/@chahuadev/framework/package.jsonAdded+16