File size: 94,272 Bytes
857cdcf | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 |
const { app, BrowserWindow, ipcMain, dialog, Menu, shell } = require('electron'); // เพิ่ม Menu และ shell
const path = require('path');
const fs = require('fs');
const os = require('os'); // เพิ่ม os
const crypto = require('crypto'); // เพิ่ม crypto
const https = require('https'); // เพิ่มสำหรับ OAuth Device Flow
const { 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 เพื่อป้องกัน error
const 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 Detector
const 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 builds
const { generateManifests } = require('./generate-manifests.js');
// ฟังก์ชันตรวจสอบ Digital Signature และ Integrity
function 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 compatibility
const 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 functions
let splashWindow; // เพิ่มตัวแปรสำหรับ splash window
let 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 architecture
const validationGateway = new ValidationGateway();
// ASAR-Safe Path Helper Functions
function 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 first
function 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 ValidationGateway
async 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 - ตรวจสอบ Dependencies
async 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 handlers
app.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 functionality
ipcMain.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 tokens
ipcMain.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.js
ipcMain.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 - ผ่าน ValidationGateway
ipcMain.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 diagnostics
function 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.isPackaged
ipcMain.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 Security
ipcMain.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.js
ipcMain.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 Mode
ipcMain.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 }; |