admin / Synapse-NetscanXi
publicNetwork Scanning, Vulnerability and Compliance Application
Synapse-NetscanXi / NetscanXiVersion13 / app / static / app.js
137683 B · main
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 | let pollTimer = null; let tickTimer = null; // 1s ticker for the elapsed clock let scanStartedAt = null; // epoch ms when current scan started let currentHosts = []; let currentScanId = null; let currentCompliance = null; let currentGroups = []; // v12: tenant asset groups let progDisplay = 0, progTarget = 0, progAnimTimer = null; // v12: smooth progress let remItems = [], agAsset = null; // v12: remediation items / group-edit target let sortKey = "ip", sortAsc = true; let expanded = {}; function esc(s){ return (s||"").toString().replace(/[&<>"']/g,c=> ({"&":"&","<":"<",">":">",'"':""","'":"'"}[c])); } // ---- Light / Dark theme toggle (persisted in localStorage) ---- function applyTheme(theme){ document.documentElement.setAttribute("data-theme", theme); const icon=document.getElementById("themeIcon"); const label=document.getElementById("themeLabel"); if(icon) icon.textContent = theme==="light" ? "\u2600" : "\u263E"; // sun / moon if(label) label.textContent = theme==="light" ? "Light" : "Dark"; } function toggleTheme(){ const cur=document.documentElement.getAttribute("data-theme")||"dark"; const next=cur==="light" ? "dark" : "light"; try { localStorage.setItem("netscan-theme", next); } catch(e){} applyTheme(next); } // Sync the button to whatever theme the early head-script already applied. applyTheme(document.documentElement.getAttribute("data-theme")||"dark"); function collectOptions(){ return { ports: document.getElementById("opt-ports").checked, services: document.getElementById("opt-services").checked, os: document.getElementById("opt-os").checked, docker: document.getElementById("opt-docker").checked, docker_deep:(document.getElementById("opt-docker-deep")||{}).checked||false, vulns: document.getElementById("opt-vulns").checked, patch_audit:(document.getElementById("opt-patch")||{}).checked||false, creds: (document.getElementById("opt-creds")||{}).checked||false, ad_audit: (document.getElementById("opt-ad")||{}).checked||false, ssl_certs:(document.getElementById("opt-ssl")||{}).checked||false, }; } // v9.1: multi-select state for the asset table. let selected = {}; // ip -> true let lastChart = {os:null, sev:null, compliance:null, snaps:[], posture:{}}; // cached chart data for redraw function startScan(){ const target=document.getElementById("target").value.trim(); const profile=document.getElementById("profile").value; const options=collectOptions(); document.getElementById("scanBtn").disabled=true; document.getElementById("cancelBtn").style.display=""; setStatus("run","Queuing scan…"); showProgress(true); setProgress(0,"Starting…"); setCurrentIp(null); startTimer(); fetch("/api/scan",{method:"POST",headers:{"Content-Type":"application/json"}, body:JSON.stringify({target,profile,options,scan_type:"active"})}) .then(r=>r.json()).then(d=>{ if(!d.ok){ setStatus("err",d.error||"failed"); resetButtons(); return; } poll(); }) .catch(e=>{ setStatus("err",e.message); resetButtons(); }); } // v9: passive scan - listen only, no probes. // v10r1: the user can set how long (0-10 min) to listen for self-announcements. function startPassiveScan(){ const target=document.getElementById("target").value.trim(); // Clamp the listen duration to the supported 0-10 minute range. const pmEl=document.getElementById("passive-minutes"); let passive_minutes=pmEl?parseFloat(pmEl.value):NaN; if(!isFinite(passive_minutes)) passive_minutes=1; passive_minutes=Math.max(0,Math.min(10,passive_minutes)); if(pmEl) pmEl.value=passive_minutes; document.getElementById("scanBtn").disabled=true; const pb=document.getElementById("passiveBtn"); if(pb) pb.disabled=true; document.getElementById("cancelBtn").style.display=""; setStatus("run","Queuing passive scan…"); showProgress(true); setProgress(0,passive_minutes>0?`Listening ${passive_minutes} min…`:"Reading ARP cache…"); setCurrentIp(null); startTimer(); fetch("/api/scan",{method:"POST",headers:{"Content-Type":"application/json"}, body:JSON.stringify({target,profile:"standard",scan_type:"passive",passive_minutes})}) .then(r=>r.json()).then(d=>{ if(!d.ok){ setStatus("err",d.error||"failed"); resetButtons(); return; } poll(); }) .catch(e=>{ setStatus("err",e.message); resetButtons(); }); } // ---- Scan timing: start time + live elapsed (updates every 1s) ---- function startTimer(){ scanStartedAt = Date.now(); const el=document.getElementById("scanStarted"); if(el) el.textContent = "Started: " + new Date(scanStartedAt).toLocaleTimeString(); if(tickTimer) clearInterval(tickTimer); updateElapsed(); tickTimer = setInterval(updateElapsed, 1000); } function stopTimer(){ if(tickTimer){ clearInterval(tickTimer); tickTimer=null; } } function fmtElapsed(sec){ sec=Math.max(0,Math.floor(sec)); const h=Math.floor(sec/3600), m=Math.floor((sec%3600)/60), s=sec%60; const pad=n=>String(n).padStart(2,"0"); return (h>0?h+":":"")+pad(m)+":"+pad(s); } function updateElapsed(serverElapsed){ const el=document.getElementById("scanElapsed"); if(!el) return; let sec; if(typeof serverElapsed==="number" && serverElapsed>0) sec=serverElapsed; else if(scanStartedAt) sec=(Date.now()-scanStartedAt)/1000; else sec=0; el.textContent = "Elapsed: " + fmtElapsed(sec); } function cancelScan(){ fetch("/api/cancel",{method:"POST"}).then(r=>r.json()).then(()=>setStatus("run","Cancelling…")); } function resetButtons(){ document.getElementById("scanBtn").disabled=false; const pb=document.getElementById("passiveBtn"); if(pb) pb.disabled=false; document.getElementById("cancelBtn").style.display="none"; stopTimer(); showProgress(false); } function poll(){ if(pollTimer) clearTimeout(pollTimer); fetch("/api/status").then(r=>r.json()).then(d=>{ // Sync the start clock to the server's authoritative value when present. if(d.started_at){ const srvStart=d.started_at*1000; if(!scanStartedAt || Math.abs(srvStart-scanStartedAt)>1500){ scanStartedAt=srvStart; const el=document.getElementById("scanStarted"); if(el) el.textContent="Started: "+new Date(srvStart).toLocaleTimeString(); } } if(d.active || d.status==="running"){ const q=d.queued?` · ${d.queued} queued`:""; setStatus("run",`Scanning ${d.target||""} [${d.profile||""}]${q}`,true); setProgress(d.progress||0,d.phase||""); setCurrentIp(d.current_ip); if(typeof d.elapsed==="number") updateElapsed(d.elapsed); document.getElementById("cancelBtn").style.display=""; document.getElementById("scanBtn").disabled=true; // Poll every 1s so the progress bar updates ~every second. pollTimer=setTimeout(poll,1000); } else if(d.status==="done"){ setProgress(100,"Complete"); setCurrentIp(null); if(typeof d.elapsed==="number") updateElapsed(d.elapsed); resetButtons(); setStatus("",`Scan complete in ${fmtElapsed(d.elapsed||0)}.`); loadDashboard(); setTimeout(()=>showProgress(false),1500); } else if(d.status==="cancelled"){ if(typeof d.elapsed==="number") updateElapsed(d.elapsed); resetButtons(); setStatus("","Scan cancelled."); loadDashboard(); } else if(d.status==="error"){ resetButtons(); setStatus("err","Scan failed."); } else { resetButtons(); loadDashboard(); } }).catch(()=>{ pollTimer=setTimeout(poll,2000); }); } function showProgress(on){ document.getElementById("progressWrap").classList.toggle("show",on); if(on) startProgAnim(); else stopProgAnim(); } // v8: show the host nmap is currently scanning. function setCurrentIp(ip){ const el=document.getElementById("scanCurrentIp"); if(!el) return; el.textContent = ip ? ("Scanning: "+ip) : ""; } // v12: smooth, always-advancing progress. The server reports the real % each // poll; between polls (and during long, quiet phases like NSE/vuln scanning) // we gently creep the bar forward so the user always sees movement — without // ever overtaking the real value by more than a few % or falsely hitting 100. function _renderProg(){ const f=document.getElementById("progressFill"), l=document.getElementById("progressLabel"); if(f) f.style.width=progDisplay.toFixed(1)+"%"; if(l) l.textContent=Math.round(progDisplay)+"%"; } function _progTick(){ const ceil = progTarget>=100 ? 100 : Math.min(99, progTarget+6); if(progDisplay < progTarget){ progDisplay += Math.max(0.4,(progTarget-progDisplay)*0.2); if(progDisplay>progTarget) progDisplay=progTarget; _renderProg(); } else if(progDisplay < ceil){ progDisplay = Math.min(ceil, progDisplay+0.15); // gentle idle creep _renderProg(); } } function startProgAnim(){ if(!progAnimTimer) progAnimTimer=setInterval(_progTick,140); } function stopProgAnim(){ if(progAnimTimer){ clearInterval(progAnimTimer); progAnimTimer=null; } } function setProgress(p,phase){ p=Math.max(0,Math.min(100,p)); if(p===0){ progTarget=0; progDisplay=0; } else { progTarget=Math.max(progTarget,p); } if(p>=100) progTarget=100; const ph=document.getElementById("progressPhase"); if(ph) ph.textContent=phase||""; _renderProg(); startProgAnim(); } function setStatus(cls,msg,spin){ const el=document.getElementById("status"); el.className="status "+(cls||""); el.innerHTML=(spin?'<span class="spinner"></span>':'')+esc(msg); } function loadDashboard(){ fetch("/api/dashboard").then(r=>r.json()).then(d=>{ currentHosts=d.hosts||[]; currentScanId=d.scan?d.scan.id:null; currentCompliance=d.compliance||null; currentGroups=d.asset_groups||[]; renderCards(d.summary,d.scan); renderTopVulns(d.top_vulnerabilities||[]); renderChanges(d.changes||[]); renderComplianceSummary(currentCompliance); // v9.2: customisable interactive charts lastChart.os=d.os_distribution||{}; lastChart.sev=d.severity_distribution||{}; renderChart("os"); renderChart("sev"); renderSorted(); loadTrends(); }); } // =========================================================================== // v9.2: Customisable chart tiles // Per-tile type (pie / horizontal bars / vertical bars / line), // user resize (CSS resize + persisted size) and drag-to-reorder. // State persists in localStorage("netscan-charts"). // =========================================================================== const CHART_COLORS=["#2f81f7","#58a6ff","#d29922","#f85149","#a371f7","#39c5cf","#db61a2","#8b949e"]; const SEV_COLORS={Critical:"#f85149",High:"#db6d28",Medium:"#d29922",Low:"#3fb950",Unknown:"#8b949e"}; const SEV_ORDER=["Critical","High","Medium","Low","Unknown"]; const CHART_KEYS=["os","sev","risk","comp"]; const CHART_DEFAULT_TYPE={os:"pie", sev:"hbar", risk:"line", comp:"hbar"}; const CHART_TYPE_OPTS={pie:"Pie chart", hbar:"Horizontal bars", vbar:"Vertical bars", line:"Trend (line)"}; // Only the risk/compliance tile keeps the historical line as an option. function chartTypeChoices(key){ return key==="risk" ? ["line","pie","hbar","vbar"] : ["pie","hbar","vbar"]; } let chartState=loadChartState(); function loadChartState(){ let s={order:CHART_KEYS.slice(), types:Object.assign({},CHART_DEFAULT_TYPE), sizes:{}}; try{ const raw=localStorage.getItem("netscan-charts"); if(raw){ const o=JSON.parse(raw); if(Array.isArray(o.order)){ s.order=o.order.filter(k=>CHART_KEYS.includes(k)); CHART_KEYS.forEach(k=>{ if(!s.order.includes(k)) s.order.push(k); }); } if(o.types) Object.assign(s.types,o.types); if(o.sizes) s.sizes=o.sizes; } }catch(e){} return s; } function saveChartState(){ try{ localStorage.setItem("netscan-charts",JSON.stringify(chartState)); }catch(e){} } // --- data accessors: each returns {entries:[[label,value],...], color, tips, empty} --- function chartData(key){ if(key==="os"){ return {entries:Object.entries(lastChart.os||{}).filter(([,v])=>v>0), color:(n,i)=>CHART_COLORS[i%CHART_COLORS.length], clickable:true, empty:"No host data yet."}; } if(key==="sev"){ const d=lastChart.sev||{}; return {entries:SEV_ORDER.map(k=>[k,d[k]||0]).filter(([,v])=>v>0), color:n=>SEV_COLORS[n]||"#8b949e", clickable:true, empty:"No vulnerabilities. Run a Deep / patch-aware scan."}; } if(key==="risk"){ const p=lastChart.posture||{}; return {entries:[["Risk score",Math.round(p.risk_score||0)],["Compliance %",Math.round(p.compliance_pct||0)]], color:n=>n==="Risk score"?"#f85149":"#39c5cf", max:100, suffix:n=>n==="Compliance %"?"%":"", empty:"No posture data yet — run scans over time."}; } // comp — regulatory compliance: failing checks per framework const c=lastChart.compliance; if(!c || !c.frameworks) return {entries:[], empty:"No compliance data yet."}; const tips={}; const entries=FRAMEWORKS.map(fw=>{ const f=c.frameworks[fw]||{pass:0,fail:0}; tips[fw]=`${f.pass} pass / ${f.fail} fail`; return [fw, f.fail]; }); return {entries, tips, color:(n,i)=>CHART_COLORS[i%CHART_COLORS.length], empty:"\u2713 All frameworks passing."}; } function chartClick(key,name){ if(key==="os") filterByOs(name); else if(key==="sev") filterBySeverity(name); } function clickAttr(spec,name){ return spec.clickable?` onclick="chartClick('${spec._key}','${esc(name)}')"`:""; } function labelTip(spec,name,val){ return (spec.tips&&spec.tips[name])||`${val}`; } function renderChart(key){ const body=document.getElementById("ctBody-"+key); if(!body) return; const type=chartState.types[key]||CHART_DEFAULT_TYPE[key]; if(type==="line" && key==="risk") return renderLineChart(body, lastChart.snaps||[]); const spec=chartData(key); spec._key=key; const entries=spec.entries||[]; const total=entries.reduce((a,[,v])=>a+(v||0),0); if(!entries.length || (type==="pie" && total<=0)){ body.innerHTML=`<div class="ct-empty">${esc(spec.empty||"No data yet.")}</div>`; return; } if(type==="pie") renderPieChart(body,entries,spec); else if(type==="vbar") renderVBars(body,entries,spec); else renderHBars(body,entries,spec); } function renderAllCharts(){ CHART_KEYS.forEach(renderChart); } function setChartType(key,type){ chartState.types[key]=type; saveChartState(); renderChart(key); } function renderPieChart(body,entries,spec){ const live=entries.filter(([,v])=>v>0); const total=live.reduce((a,[,v])=>a+v,0)||1; let acc=0; const cx=100,cy=100,r=78; let paths=""; live.forEach(([name,val],i)=>{ const col=spec.color?spec.color(name,i):CHART_COLORS[i%CHART_COLORS.length]; const tip=labelTip(spec,name,val); if(live.length===1){ paths+=`<circle cx="${cx}" cy="${cy}" r="${r}" fill="${col}"${clickAttr(spec,name)}><title>${esc(name)}: ${esc(tip)}</title></circle>`; return; } const frac=val/total; const a0=acc*2*Math.PI-Math.PI/2; acc+=frac; const a1=acc*2*Math.PI-Math.PI/2; const x0=cx+r*Math.cos(a0),y0=cy+r*Math.sin(a0),x1=cx+r*Math.cos(a1),y1=cy+r*Math.sin(a1); const large=frac>0.5?1:0; paths+=`<path d="M${cx},${cy} L${x0.toFixed(2)},${y0.toFixed(2)} A${r},${r} 0 ${large} 1 ${x1.toFixed(2)},${y1.toFixed(2)} Z" `+ `fill="${col}" class="pie-slice"${clickAttr(spec,name)}><title>${esc(name)}: ${esc(tip)} (${Math.round(frac*100)}%)</title></path>`; }); const legend=live.map(([name,val],i)=>{ const col=spec.color?spec.color(name,i):CHART_COLORS[i%CHART_COLORS.length]; return `<div class="leg-item"${clickAttr(spec,name)}><span class="swatch" style="background:${col}"></span>${esc(name)} <span class="muted">(${val})</span></div>`; }).join(""); body.innerHTML=`<div class="ct-piewrap"><svg viewBox="0 0 200 200" class="pie" preserveAspectRatio="xMidYMid meet">${paths}</svg><div class="legend">${legend}</div></div>`; } function renderHBars(body,entries,spec){ const max=Math.max(1,spec.max||0,...entries.map(([,v])=>v||0)); body.innerHTML='<div class="hbars">'+entries.map(([name,val],i)=>{ const col=spec.color?spec.color(name,i):CHART_COLORS[i%CHART_COLORS.length]; const pct=Math.round(100*(val||0)/max); const sfx=spec.suffix?spec.suffix(name):""; return `<div class="hbar-row" title="${esc(name)}: ${esc(labelTip(spec,name,val))}"${clickAttr(spec,name)}>`+ `<span class="hbar-label">${esc(name)}</span>`+ `<span class="hbar-track"><span class="hbar-fill" style="width:${pct}%;background:${col}"></span></span>`+ `<span class="hbar-val">${val}${sfx}</span></div>`; }).join("")+'</div>'; } function renderVBars(body,entries,spec){ const max=Math.max(1,spec.max||0,...entries.map(([,v])=>v||0)); body.innerHTML='<div class="vbars">'+entries.map(([name,val],i)=>{ const col=spec.color?spec.color(name,i):CHART_COLORS[i%CHART_COLORS.length]; const h=Math.round(100*(val||0)/max); const sfx=spec.suffix?spec.suffix(name):""; return `<div class="vbar-col" title="${esc(name)}: ${esc(labelTip(spec,name,val))}"${clickAttr(spec,name)}>`+ `<span class="vbar-val">${val}${sfx}</span>`+ `<span class="vbar-bar" style="height:${h}%;background:${col}"></span>`+ `<span class="vbar-label">${esc(name)}</span></div>`; }).join("")+'</div>'; } function filterByOs(name){ const f=document.getElementById("filter"); if(!f) return; // Map the pie family back to a substring filter the table understands. const map={Apple:"mac","Network/IoT":"",Unknown:"",Other:""}; f.value=(name in map)?map[name]:name; switchTab("assets"); renderSorted(); f.scrollIntoView({behavior:"smooth",block:"center"}); } function filterBySeverity(band){ switchTab("assets"); setStatus("",`Showing assets — ${band}-severity findings highlighted in detail views.`); } // Historical risk + compliance trend (line) — risk tile only. function loadTrends(){ fetch("/api/trends?days=365").then(r=>r.json()).then(d=>{ if(d.ok){ const snaps=d.snapshots||[]; lastChart.snaps=snaps; const last=snaps[snaps.length-1]||{}; lastChart.posture={risk_score:last.risk_score||0, compliance_pct:last.compliance_pct||0}; renderChart("risk"); } }).catch(()=>{}); } function renderLineChart(body,snaps){ const W=720,H=300,pad=38; if(!snaps||!snaps.length){ body.innerHTML='<div class="ct-empty">No trend data yet — run scans over time to build history.</div>'; return; } const t0=snaps[0].ts, t1=snaps[snaps.length-1].ts||t0+1; const span=(t1-t0)||1; const xx=ts=>pad+(W-2*pad)*((ts-t0)/span); const yy=val=>H-pad-(H-2*pad)*(Math.max(0,Math.min(100,val))/100); function line(key,color){ if(snaps.length===1){ const s=snaps[0]; return `<circle cx="${xx(s.ts)}" cy="${yy(s[key])}" r="4" fill="${color}"/>`; } const pts=snaps.map(s=>`${xx(s.ts).toFixed(1)},${yy(s[key]).toFixed(1)}`).join(" "); const dots=snaps.map(s=>`<circle cx="${xx(s.ts).toFixed(1)}" cy="${yy(s[key]).toFixed(1)}" r="3" fill="${color}"><title>${new Date(s.ts*1000).toLocaleDateString()}: ${s[key]}</title></circle>`).join(""); return `<polyline points="${pts}" fill="none" stroke="${color}" stroke-width="2"/>${dots}`; } let grid=""; for(let g=0;g<=100;g+=25){ const y=yy(g); grid+=`<line x1="${pad}" y1="${y}" x2="${W-pad}" y2="${y}" stroke="#30363d" stroke-width="1"/>`+ `<text x="${pad-6}" y="${y+3}" text-anchor="end" font-size="11" fill="#8b949e">${g}</text>`; } const xl=new Date(t0*1000).toLocaleDateString(), xr=new Date(t1*1000).toLocaleDateString(); body.innerHTML=`<div class="ct-linewrap"><svg viewBox="0 0 ${W} ${H}" class="ct-svg" preserveAspectRatio="xMidYMid meet">`+ grid+`<text x="${pad}" y="${H-8}" font-size="11" fill="#8b949e">${xl}</text>`+ `<text x="${W-pad}" y="${H-8}" text-anchor="end" font-size="11" fill="#8b949e">${xr}</text>`+ line("risk_score","#f85149")+line("compliance_pct","#39c5cf")+`</svg>`+ `<div class="trend-legend"><span class="tl risk">● Risk score</span><span class="tl comp">● Compliance %</span></div></div>`; } // --- chart tile setup: selects, persisted size, drag-to-reorder --- function initCharts(){ const grid=document.getElementById("chartGrid"); if(!grid) return; chartState.order.forEach(k=>{ const el=grid.querySelector(`.chart-tile[data-chart="${k}"]`); if(el) grid.appendChild(el); }); CHART_KEYS.forEach(k=>{ const tile=grid.querySelector(`.chart-tile[data-chart="${k}"]`); if(!tile) return; const sel=tile.querySelector(".ct-type"); if(sel){ sel.innerHTML=chartTypeChoices(k).map(t=>`<option value="${t}">${CHART_TYPE_OPTS[t]}</option>`).join(""); sel.value=chartState.types[k]||CHART_DEFAULT_TYPE[k]; } const sz=chartState.sizes[k]; if(sz){ if(sz.w) tile.style.width=sz.w+"px"; if(sz.h) tile.style.height=sz.h+"px"; } observeChartResize(tile,k); }); enableChartDrag(); renderAllCharts(); } function observeChartResize(tile,key){ if(!window.ResizeObserver) return; let t=null; const ro=new ResizeObserver(()=>{ clearTimeout(t); t=setTimeout(()=>{ chartState.sizes[key]={w:Math.round(tile.offsetWidth), h:Math.round(tile.offsetHeight)}; saveChartState(); },350); }); ro.observe(tile); } function enableChartDrag(){ const grid=document.getElementById("chartGrid"); if(!grid) return; grid.querySelectorAll(".chart-tile").forEach(tile=>{ tile.setAttribute("draggable","false"); const handle=tile.querySelector(".ct-drag"); if(handle){ handle.onmousedown=()=>tile.setAttribute("draggable","true"); handle.onmouseup=()=>tile.setAttribute("draggable","false"); } tile.ondragstart=e=>{ e.dataTransfer.setData("text/plain",tile.dataset.chart); tile.classList.add("dragging"); }; tile.ondragend=()=>{ tile.classList.remove("dragging"); tile.setAttribute("draggable","false"); grid.querySelectorAll(".chart-tile").forEach(t=>t.classList.remove("drop-target")); }; tile.ondragover=e=>{ e.preventDefault(); tile.classList.add("drop-target"); }; tile.ondragleave=()=>tile.classList.remove("drop-target"); tile.ondrop=e=>{ e.preventDefault(); tile.classList.remove("drop-target"); const from=e.dataTransfer.getData("text/plain"), to=tile.dataset.chart; if(!from || from===to) return; let order=[...grid.querySelectorAll(".chart-tile")].map(t=>t.dataset.chart).filter(x=>x!==from); const idx=order.indexOf(to); order.splice(idx,0,from); chartState.order=order; saveChartState(); order.forEach(k=>{ const el=grid.querySelector(`.chart-tile[data-chart="${k}"]`); if(el) grid.appendChild(el); }); enableChartDrag(); }; }); } function resetCharts(){ try{ localStorage.removeItem("netscan-charts"); }catch(e){} chartState=loadChartState(); const grid=document.getElementById("chartGrid"); if(!grid) return; CHART_KEYS.forEach(k=>{ const el=grid.querySelector(`.chart-tile[data-chart="${k}"]`); if(el){ el.style.width=""; el.style.height=""; grid.appendChild(el); const sel=el.querySelector(".ct-type"); if(sel) sel.value=chartState.types[k]; } }); renderAllCharts(); } function renderCards(s,scan){ s=s||{}; const when=scan&&scan.finished?new Date(scan.finished*1000).toLocaleString():"—"; const cards=[ {n:s.hosts||0,l:"Hosts"}, {n:s.vulns||0,l:"Vulnerabilities",cls:s.vulns?"warn":""}, {n:s.kev||0,l:"Known-Exploited (KEV)",cls:s.kev?"kev":""}, {n:s.high_risk||0,l:"High-risk assets",cls:s.high_risk?"alert":""}, {n:s.docker||0,l:"Docker hosts",cls:s.docker?"docker":""}, {n:s.critical_changes||0,l:"Critical changes",cls:s.critical_changes?"alert":""}, ]; document.getElementById("cards").innerHTML=cards.map(c=> `<div class="card ${c.cls||''}"><div class="n">${c.n}</div><div class="l">${esc(c.l)}</div></div>`).join("")+ `<div class="card"><div class="n" style="font-size:14px">${esc(scan?scan.profile:"—")}</div>`+ `<div class="l">Last scan · ${esc(when)}</div></div>`; renderDockerCards(s.docker_stats||{}); } // v10r1: dedicated Docker / container stat row (only shown when relevant). function renderDockerCards(ds){ const wrap=document.getElementById("dockerCards"); const sec=document.getElementById("dockerSection"); const comp=document.getElementById("comp-docker"); if(!wrap) return; if(!ds || !ds.docker_hosts){ if(sec) sec.style.display="none"; if(comp) comp.dataset.empty="1"; // applyDashLayout keeps empty comps hidden if(comp) comp.style.display="none"; return; } if(comp){ comp.dataset.empty="0"; } if(sec) sec.style.display=""; const cards=[ {n:ds.docker_hosts||0,l:"Docker hosts",cls:"docker"}, {n:ds.containers_running+"/"+ds.containers,l:"Containers running"}, {n:ds.containers_unhealthy||0,l:"Unhealthy containers",cls:ds.containers_unhealthy?"alert":""}, {n:ds.images||0,l:"Images"}, {n:ds.image_vulns||0,l:"Image CVEs",cls:ds.image_vulns?"warn":""}, {n:ds.image_critical||0,l:"Critical image CVEs",cls:ds.image_critical?"alert":""}, {n:ds.privileged_containers||0,l:"Privileged containers",cls:ds.privileged_containers?"alert":""}, {n:ds.sock_mounts||0,l:"docker.sock mounts",cls:ds.sock_mounts?"alert":""}, {n:ds.cis_failures||0,l:"CIS failures",cls:ds.cis_failures?"alert":""}, ]; wrap.innerHTML=cards.map(c=> `<div class="card ${c.cls||''}"><div class="n">${c.n}</div><div class="l">${esc(c.l)}</div></div>`).join(""); } // v10r1: render the deep Docker block (engine, containers, image CVEs, CIS). function renderDockerDeep(d){ if(!d) return ""; let html=""; const sum=d.summary||{}; const cap=d.capabilities||{}; const api=d.api||{}; // Capability / API status line. const apiTxt = api.reachable ? `API reachable at ${esc(api.endpoint||"")}${api.secure===false?" (insecure / no TLS)":""}` : `API not reached${api.reason?" — "+esc(api.reason):""}`; html+=`<div class="item docker-item"><div class="docker-substat">`+ `<span class="badge ${api.reachable?'docker':'muted-badge'}">${api.reachable?'\u{1F50C} API connected':'API offline'}</span> `+ `<span class="muted">${apiTxt}</span></div></div>`; // Engine details (when API reachable). if(d.engine && d.engine.version){ const e=d.engine; html+='<div class="item"><b>Engine:</b> '+ `Docker ${esc(e.version)} · API ${esc(e.api_version||"?")} · ${esc(e.storage_driver||"")} · `+ `${e.rootless?'<span class="st pass">rootless</span>':'<span class="st warn">root</span>'}`+ `${e.live_restore?' · live-restore':''}</div>`; } // Containers table. if((d.containers||[]).length){ html+=`<h4>\u{1F4E6} Containers (${sum.containers_running||0}/${sum.containers||d.containers.length} running)</h4>`; for(const c of d.containers){ const flags=[]; if(c.privileged) flags.push('<span class="st fail">privileged</span>'); if(c.docker_sock_mounted) flags.push('<span class="st fail">docker.sock</span>'); if((c.network_mode||"").toLowerCase()==='host') flags.push('<span class="st warn">host-net</span>'); if((c.pid_mode||"").toLowerCase().indexOf('host')>=0) flags.push('<span class="st warn">host-pid</span>'); if((c.cap_add||[]).length) flags.push(`<span class="st warn">+caps</span>`); // v12: container health badge (only when a HEALTHCHECK is defined). const hb={healthy:'st ok',unhealthy:'st fail',starting:'st warn'}[c.health]; if(hb){ let ht='health: '+esc(c.health); if(c.health==='unhealthy'&&c.health_failing_streak) ht+=' \u00d7'+c.health_failing_streak; flags.push(`<span class="${hb}" title="${esc(c.health_last_output||'')}">${ht}</span>`); } const st=c.state==='running'?'gdot on':'gdot'; // v12: per-container IPs (from Engine API NetworkSettings.Networks). let ipLine=''; if((c.networks||[]).length){ const parts=c.networks.filter(n=>n.ip||n.ipv6).map(n=> `${esc(n.network)}: ${esc(n.ip||n.ipv6)}`); if(parts.length) ipLine=`<div class="sub">ip: ${parts.join(" \u00b7 ")}</div>`; } else if((c.ips||[]).length){ ipLine=`<div class="sub">ip: ${esc(c.ips.join(", "))}</div>`; } const pub=(c.ports_published||[]); const intl=(c.ports_internal||[]); let portLine=''; if(pub.length||intl.length){ const bits=[]; if(pub.length) bits.push(`published ${esc(pub.join(", "))}`); if(intl.length) bits.push(`internal ${esc(intl.join(", "))}`); portLine=`<div class="sub">ports: ${bits.join(" \u00b7 ")}</div>`; } else if((c.ports||[]).length){ portLine=`<div class="sub">ports: ${esc(c.ports.join(", "))}</div>`; } html+=`<div class="item docker-cont"><span class="${st}"></span>`+ `<b>${esc(c.name||c.id)}</b> <span class="muted">${esc(c.image||"")}</span>`+ `${flags.length?' '+flags.join(' '):''}`+ `${ipLine}${portLine}</div>`; } } // Image vulnerability scan results. const is=d.image_scan||{}; if(is.ran){ const sev=is.severity||{}; html+=`<h4>\u{1F50E} Image Vulnerabilities <span class="muted" style="font-weight:400">(${esc(is.scanner||"")} · ${is.scanned||0}/${is.image_count||0} images · ${is.total_vulns||0} CVEs${is.kev_count?` · ${is.kev_count} KEV`:''})</span></h4>`; html+=`<div class="sev-strip">`+ sevPill('Critical',sev.Critical)+sevPill('High',sev.High)+sevPill('Medium',sev.Medium)+sevPill('Low',sev.Low)+`</div>`; for(const rep of (is.reports||[])){ const rs=rep.severity||{}; html+=`<div class="item docker-img"><b>${esc(rep.image)}</b> `+ `<span class="muted">${rep.vuln_count||0} CVEs${rep.kev_count?` · ${rep.kev_count} KEV`:''}</span>`; if(rep.error) html+=` <span class="st warn" title="${esc(rep.error)}">scan error</span>`; // top few CVEs const top=(rep.vulns||[]).slice(0,6); if(top.length){ html+='<div class="img-cves">'; for(const v of top){ const sc=scoreClass(v.cvss); html+=`<span class="cve-chip ${sc}" title="${esc(v.pkg||"")} ${esc(v.installed||"")} → ${esc(v.fixed||"no fix")}">`+ `${v.kev?'\u{1F525} ':''}${esc(v.id)}${v.cvss?` (${esc(v.cvss)})`:''}</span>`; } if((rep.vulns||[]).length>top.length) html+=`<span class="muted"> +${rep.vulns.length-top.length} more</span>`; html+='</div>'; } html+='</div>'; } } else if(cap.api_inventory && (d.images||[]).length && !cap.image_scanner){ html+=`<div class="item docker-warn">\u2139 ${d.images.length} image(s) found. Install <b>Trivy</b> or <b>Grype</b> on the NetscanXi host to scan images for CVEs.</div>`; } // CIS Docker Benchmark audit. if((d.cis_audit||[]).length){ const cs=d.cis_summary||{}; html+=`<h4>\u{1F6E1}\uFE0F CIS Docker Audit <span class="muted" style="font-weight:400">(${cs.fail||0} fail · ${cs.warn||0} warn · ${cs.pass||0} pass)</span></h4>`; const order={fail:0,warn:1,pass:2}; const sorted=[...d.cis_audit].sort((a,b)=>order[a.status]-order[b.status]); for(const a of sorted){ html+=`<div class="item cis-row"><span class="st ${a.status}">${a.status}</span> `+ `<b>${esc(a.check)}</b> <span class="muted">${esc(a.detail)}</span> `+ `<span class="cis-ref">${esc(a.ref)}</span></div>`; } } // Orchestration. const orch=d.orchestration||{}; if(orch.detected){ html+=`<h4>\u{1F578}\uFE0F Orchestration <span class="muted" style="font-weight:400">(${esc(orch.kind||"detected")})</span></h4>`; html+='<div class="item">'; for(const i of (orch.indicators||[])){ html+=`<span class="badge ${i.sensitive?'kev':'docker'}" title="port ${esc(i.port)}">${esc(i.role)}</span> `; } html+='</div>'; } return html; } function sevPill(label,n){ n=n||0; const cls=label.toLowerCase(); return `<span class="sev-pill ${cls}${n?'':' zero'}">${label}: ${n}</span>`; } function scoreClass(c){ const s=parseFloat(c); if(isNaN(s))return"na"; if(s>=7)return"high"; if(s>=4)return"med"; return"low"; } function renderTopVulns(vulns){ document.getElementById("vulnCount").textContent=vulns.length?`${vulns.length} shown`:""; const el=document.getElementById("topVulns"); if(!vulns.length){ el.innerHTML='<div class="muted">No vulnerabilities found. Run a <b>Deep</b> scan to enable vuln detection.</div>'; return; } el.innerHTML=vulns.map(v=>{ const sc=v.cvss?(+v.cvss).toFixed(1):"N/A"; const tags=(v.kev?'<span class="tag kev">KEV</span>':'')+(v.exploit?'<span class="tag exp">EXPLOIT</span>':''); const hosts=(v.hosts||[]).length; const cve=v.cve||(/^CVE-/i.test(v.id||"")?v.id:""); const idCell=cve ? `<a class="vid" href="https://nvd.nist.gov/vuln/detail/${esc(cve)}" target="_blank" rel="noopener">${esc(v.id)}</a>` : `<span class="vid">${esc(v.id)}</span>`; const desc=v.description?`<div class="vdesc">${esc(v.description)}</div>`:""; const mit=v.mitigation?`<div class="vmit"><span class="mit-label">\u{1F6E0} Mitigation:</span> ${esc(v.mitigation)}</div>`:""; const lc=v.lifecycle&&v.lifecycle!=="open"?` <span class="lc-badge lc-${esc(v.lifecycle)}">${lcLabel(v.lifecycle)}</span>`:""; return `<div class="vrow lc-${esc(v.lifecycle||'open')}"><div class="score ${scoreClass(v.cvss)}">${sc}</div>`+ `<div style="flex:1">${idCell}${tags}${lc}`+ `<div class="meta">${hosts} host(s)</div>${desc}${mit}</div></div>`; }).join(""); } function renderChanges(changes){ document.getElementById("changeCount").textContent=changes.length?`${changes.length} change(s)`:""; const el=document.getElementById("changes"); if(!changes.length){ el.innerHTML='<div class="muted">No changes since the previous scan.</div>'; return; } const dot={critical:"🔴",warn:"🟠",info:"🔵"}; el.innerHTML=changes.slice(0,40).map(c=> `<div class="chg ${esc(c.severity)}"><span class="dot">${dot[c.severity]||"•"}</span>`+ `<span class="ip">${esc(c.ip)}</span><span>${esc(c.detail)}</span></div>`).join(""); } function ipNum(ip){ const p=(ip||"").split("."); if(p.length!==4)return 0; return p.reduce((a,x)=>a*256+(parseInt(x)||0),0); } function matchesFilter(h,q){ if(!q) return true; q=q.toLowerCase(); const hay=[h.asset_id,h.ip,h.hostname,h.os,h.device_type,h.vendor, (h.ports||[]).join(" "),(h.software||[]).map(s=>s.name).join(" "), (h.advertised_services||[]).join(" "), (h.vulns||[]).map(v=>v.id).join(" ")].join(" ").toLowerCase(); return hay.includes(q); } function renderSorted(){ const q=(document.getElementById("filter")||{}).value||""; let hosts=currentHosts.filter(h=>matchesFilter(h,q)); hosts=[...hosts].sort((a,b)=>{ let av,bv; if(sortKey==="ip"){ av=ipNum(a.ip); bv=ipNum(b.ip); } else if(sortKey==="ports"){ av=(a.ports||[]).length; bv=(b.ports||[]).length; } else if(sortKey==="vuln_count"){ av=a.vuln_count||0; bv=b.vuln_count||0; } else if(sortKey==="risk"){ av=(a.risk==null?-1:a.risk); bv=(b.risk==null?-1:b.risk); } else if(sortKey==="software"){ av=(a.software||[]).length; bv=(b.software||[]).length; } else { av=(a[sortKey]||"").toString().toLowerCase(); bv=(b[sortKey]||"").toString().toLowerCase(); } if(av<bv) return sortAsc?-1:1; if(av>bv) return sortAsc?1:-1; return 0; }); document.getElementById("assetCount").textContent=`${hosts.length} asset(s)`; render(hosts); } function riskColor(r){ if(r>=70) return "var(--danger)"; if(r>=40) return "var(--warn)"; return "var(--accent)"; } function render(hosts){ const tb=document.getElementById("tbody"); tb.innerHTML=""; if(!hosts.length){ tb.innerHTML='<tr><td colspan="12" class="muted">No assets.</td></tr>'; updateBulkBar(); return; } for(const h of hosts){ const tr=document.createElement("tr"); tr.className="host-row"+(expanded[h.ip]?" expanded":"")+(selected[h.ip]?" selected":""); const soft=(h.software||[]).length; const softCell=soft?`<span class="chip soft">${esc(h.software[0].name)}</span>`+ (soft>1?` <span class="muted">+${soft-1}</span>`:""):'<span class="muted">—</span>'; // v9: passive assets have no risk score (null) -> show n/a. let riskCell; if(h.risk==null){ riskCell='<span class="muted">n/a</span>'; } else { const r=h.risk||0; riskCell=`<span class="risk-bar"><i style="width:${r}%;background:${riskColor(r)}"></i></span>`+ `<span class="risk-num" style="color:${riskColor(r)}">${r}</span>`; } const vc=h.vuln_count||0; const vulnCell=h.passive?'<span class="muted">—</span>':(vc?`<span class="badge vuln">${vc}</span>`:`<span class="badge ok">0</span>`); const dock=(h.docker&&h.docker.is_docker) ? ` <span class="badge docker" title="${esc((h.docker.indicators||[]).join('; '))}">\u{1F433} Docker</span>` : ""; // v9: asset ID + passive badge const aid=h.asset_id?`<code class="asset-id">${esc(h.asset_id)}</code>`:'<span class="muted">—</span>'; const pbadge=h.passive?' <span class="badge passive" title="Discovered passively (no probes sent)">Passive</span>':''; const portsCell=h.passive?'<span class="muted">—</span>':`<span class="chip">${(h.ports||[]).length}</span>`; // v9: editable Type (click pencil to correct a mis-identified device) const typeCell=`<span class="type-text">${esc(h.device_type||"—")}</span>${dock}`+ (h.asset_id?` <button class="type-edit" title="Correct device type" onclick="editType(event,'${esc(h.asset_id)}','${esc(h.device_type||'')}')">✎</button>`:''); // v12: asset-group membership chips + (operator+) manage button const grps=h.groups||[]; const grpChips=grps.length?grps.map(g=>`<span class="chip grp">${esc(g.name)}</span>`).join(" "):'<span class="muted">—</span>'; const grpCell=grpChips+((window.NETSCAN_CAN_SCAN!==false && h.asset_id) ?` <button class="grp-edit" title="Manage asset groups" onclick="openAssetGroups(event,'${esc(h.asset_id)}')">✎</button>`:''); tr.innerHTML=`<td class="selcol"><input type="checkbox" class="rowsel" ${selected[h.ip]?"checked":""} onclick="event.stopPropagation();toggleRowSel('${esc(h.ip)}',this.checked)"></td>`+ `<td><span class="caret">▶</span></td>`+ `<td>${aid}</td>`+ `<td><code>${esc(h.ip)}</code>${pbadge}</td>`+ `<td>${esc(h.hostname)}</td>`+ `<td>${typeCell}</td>`+ `<td>${esc(h.os)}${h.os_accuracy?` <span class="muted">(${h.os_accuracy}%)</span>`:""}</td>`+ `<td>${softCell}</td>`+ `<td>${portsCell}</td>`+ `<td>${riskCell}</td>`+ `<td>${vulnCell}</td>`+ `<td class="grp-cell">${grpCell}</td>`; tr.addEventListener("click",()=>toggleDetail(h.ip)); tb.appendChild(tr); if(expanded[h.ip]){ const dr=document.createElement("tr"); dr.className="detail-row"; const td=document.createElement("td"); td.colSpan=12; td.innerHTML=detailHtml(h); dr.appendChild(td); tb.appendChild(dr); } } updateBulkBar(); } // =========================================================================== // v9.1: multi-select on the asset table // =========================================================================== function toggleRowSel(ip,on){ if(on) selected[ip]=true; else delete selected[ip]; renderSorted(); } function toggleSelectAll(box){ const q=(document.getElementById("filter")||{}).value||""; const hosts=currentHosts.filter(h=>matchesFilter(h,q)); if(box.checked) hosts.forEach(h=>{ selected[h.ip]=true; }); else hosts.forEach(h=>{ delete selected[h.ip]; }); renderSorted(); } function clearSelection(){ selected={}; const sa=document.getElementById("selectAll"); if(sa) sa.checked=false; renderSorted(); } function selectedIps(){ return Object.keys(selected).filter(ip=>selected[ip]); } function updateBulkBar(){ const ips=selectedIps(); const bar=document.getElementById("bulkActions"); if(!bar) return; bar.style.display=ips.length?"":"none"; const c=document.getElementById("bulkCount"); if(c) c.textContent=`${ips.length} asset(s) selected`; const sa=document.getElementById("selectAll"); if(sa){ const q=(document.getElementById("filter")||{}).value||""; const vis=currentHosts.filter(h=>matchesFilter(h,q)); sa.checked=vis.length>0 && vis.every(h=>selected[h.ip]); } } function bulkExport(fmt){ const ips=selectedIps(); if(!ips.length) return; // Export each selected host's focused report. ips.forEach((ip,i)=>setTimeout(()=>exportHost(null,ip,fmt),i*350)); setStatus("",`Exporting ${ips.length} host report(s) as ${fmt.toUpperCase()}…`); } function bulkRescan(){ const ips=selectedIps(); if(!ips.length) return; if(!confirm(`Re-scan ${ips.length} selected asset(s)?`)) return; const profile=document.getElementById("profile").value; const options=collectOptions(); ips.forEach(ip=>fetch(`/api/rescan/${ip}`,{method:"POST",headers:{"Content-Type":"application/json"}, body:JSON.stringify({profile,options})})); setStatus("run",`Queued re-scan for ${ips.length} asset(s).`); showProgress(true); document.getElementById("scanBtn").disabled=true; startTimer(); poll(); } // v9: edit a mis-identified device Type. Override is sticky (bound to asset ID). function editType(ev,assetId,current){ if(ev) ev.stopPropagation(); const val=prompt("Correct device type for asset "+assetId+"\n(e.g. printer, camera, router, nas, iot, phone, server). Leave blank to clear.",current||""); if(val===null) return; fetch(`/api/assets/${assetId}/type`,{method:"POST",headers:{"Content-Type":"application/json"}, body:JSON.stringify({device_type:val.trim()})}).then(r=>r.json()).then(d=>{ if(!d.ok){ alert(d.error||"failed"); return; } // Apply locally so the change shows immediately. (currentHosts||[]).forEach(h=>{ if(h.asset_id===assetId){ h.device_type=d.device_type||"unknown"; h.type_override=d.device_type||null; }}); renderSorted(); }).catch(e=>alert(e.message)); } function toggleDetail(ip){ expanded[ip]=!expanded[ip]; renderSorted(); } function detailHtml(h){ let html='<div class="detail">'; const ip=esc(h.ip); html+=`<h3>${ip} — ${esc(h.hostname)}`+ `<span class="host-actions">`+ `<button class="ghost" style="padding:4px 10px" onclick="rescan(event,'${ip}')">Re-scan</button>`+ (window.NETSCAN_CAN_SCAN!==false && h.asset_id && (h.vulns||[]).length ? `<button class="ghost" style="padding:4px 10px" onclick="openVulnTicket(event,'${esc(h.asset_id)}')" title="Gather this asset's vulnerabilities and choose which to send to Synapse Cortex as a ticket">🎫 Create ticket</button>` : '')+ `<span class="host-export" title="Export a report for just this host">Export:`+ ` <button class="ghost mini" onclick="exportHost(event,'${ip}','csv')">CSV</button>`+ ` <button class="ghost mini" onclick="exportHost(event,'${ip}','json')">JSON</button>`+ ` <button class="ghost mini" onclick="exportHost(event,'${ip}','pdf')">PDF</button>`+ `</span></span></h3>`; html+='<div class="kv">'; html+=`<div class="k">Asset ID</div><div><code>${esc(h.asset_id||"—")}</code>${h.passive?' <span class="badge passive">Passive</span>':''}${h.type_override?' <span class="muted">(type corrected)</span>':''}</div>`; html+=`<div class="k">Device type</div><div>${esc(h.device_type||"—")}</div>`; html+=`<div class="k">MAC / Vendor</div><div><code>${esc(h.mac)}</code> ${esc(h.vendor)}</div>`; html+=`<div class="k">OS</div><div>${esc(h.os)}${h.os_accuracy?` <span class="muted">(${h.os_accuracy}% confidence)</span>`:""}</div>`; if(h.risk==null) html+=`<div class="k">Risk score</div><div class="muted">n/a (passive)</div>`; else html+=`<div class="k">Risk score</div><div style="color:${riskColor(h.risk||0)};font-weight:600">${h.risk||0}/100</div>`; html+=`<div class="k">Open ports</div><div>${h.passive?'— <span class="muted">(passive)</span>':(h.ports||[]).length}</div>`; html+=`<div class="k">Vulnerabilities</div><div>${h.passive?'— <span class="muted">(passive)</span>':(h.vuln_count||0)}</div>`; if(h.passive && (h.advertised_services||[]).length) html+=`<div class="k">Advertised services</div><div>${esc(h.advertised_services.join(", "))}</div>`; if(h.docker&&h.docker.is_docker){ const cf=esc(h.docker.confidence||""); html+=`<div class="k">Docker host</div><div><span class="badge docker">\u{1F433} Yes</span> <span class="muted">(${cf} confidence${h.docker.version?", engine "+esc(h.docker.version):""}${h.docker.api_exposed?", API exposed":""})</span></div>`; } html+='</div>'; if(h.docker&&h.docker.is_docker){ html+='<h4>\u{1F433} Docker / Container Runtime</h4>'; html+='<div class="item docker-item">'; if(h.docker.version) html+=`<div><b>Engine version:</b> ${esc(h.docker.version)}</div>`; if(h.docker.api_exposed) html+='<div class="docker-warn">\u26A0 Docker API appears exposed on the network — restrict access immediately.</div>'; if((h.docker.ports||[]).length) html+=`<div><b>Docker ports:</b> ${esc(h.docker.ports.join(", "))}</div>`; if((h.docker.indicators||[]).length){ html+='<div style="margin-top:4px"><b>Indicators:</b></div><ul class="docker-ind">'; for(const ind of h.docker.indicators) html+=`<li>${esc(ind)}</li>`; html+='</ul>'; } html+='</div>'; // v10r1: deep Docker container/image/audit detail. html+=renderDockerDeep(h.docker); } // v9.1: patch level summary for the host if((h.patch_levels||[]).length){ html+='<h4>\u{1F9F0} Detected Patch / Build Levels</h4>'; for(const p of h.patch_levels){ html+=`<div class="item"><span class="sname">${esc(p.product||"")}</span> `+ `<span class="muted">${esc(p.version||"")}</span> `+ `<span class="badge patchlvl" title="Detected patch / package release">patch ${esc(p.patch)}</span> `+ `<span class="muted">on ${esc(p.port||"")}</span></div>`; } } if((h.vulns||[]).length){ html+='<h4>🛑 Vulnerabilities</h4>'; for(const v of h.vulns){ const cc=scoreClass(v.cvss); const cve=v.cve||(/^CVE-/i.test(v.id||"")?v.id:""); const lc=v.lifecycle||"open"; html+=`<div class="item vuln lc-${esc(lc)}">`; if(v.cvss) html+=`<span class="cvss ${cc}">CVSS ${esc(v.cvss)}</span>`; html+=`<span class="vid">${esc(v.id)}</span>`; if(v.kev) html+=' <span class="tag kev">KEV</span>'; if(v.exploit) html+=' <span class="tag exp">EXPLOIT</span>'; // v9.1: match-confidence badge (version-confirmed vs heuristic) if(v.match_basis==="version-confirmed") html+=' <span class="tag confirmed" title="Matched against the exact detected product + version/patch">✓ version-confirmed</span>'; else if(v.match_basis==="heuristic") html+=' <span class="tag heuristic" title="Heuristic match (distro version); confirm before acting">~ heuristic</span>'; // v9.1: lifecycle badge html+=` <span class="lc-badge lc-${esc(lc)}">${lcLabel(lc)}</span>`; if(v.patch) html+=` <span class="muted" style="font-size:11px">patch ${esc(v.patch)}</span>`; // CVE code line (linked to NVD when it's a real CVE id) if(cve) html+=`<div class="cve-line">CVE: <a href="https://nvd.nist.gov/vuln/detail/${esc(cve)}" target="_blank" rel="noopener">${esc(cve)}</a></div>`; if(v.description) html+=`<div class="muted" style="margin-top:4px">${esc(v.description)}</div>`; // Mitigation suggestion if(v.mitigation) html+=`<div class="mitigation"><span class="mit-label">\u{1F6E0} Mitigation:</span> ${esc(v.mitigation)}</div>`; if(v.lifecycle_note) html+=`<div class="muted" style="margin-top:3px;font-style:italic">Note: ${esc(v.lifecycle_note)}</div>`; const meta=[]; if(v.port&&v.port!=="host")meta.push("port "+esc(v.port)); if(v.source)meta.push(esc(v.source)); if(meta.length) html+=`<div class="muted" style="margin-top:3px">${meta.join(" · ")}</div>`; // v9.1: lifecycle + ticket actions (operator+) if(window.NETSCAN_CAN_SCAN){ const cid=esc(cve||v.id); html+=`<div class="vuln-actions">`+ `<button class="ghost mini" onclick="openLifecycle(event,'${esc(h.asset_id||"")}','${cid}','${esc(h.ip)}')">🔄 Set status</button>`+ `<button class="ghost mini" onclick="openTicket(event,'${esc(h.asset_id||"")}','${cid}','${esc(h.ip)}')">🎫 Create ticket</button>`+ `</div>`; } html+='</div>'; } } if((h.software||[]).length){ html+='<h4>📦 Software & Applications</h4>'; for(const s of h.software){ html+='<div class="item"><span class="sname">'+esc(s.name)+'</span>'+ ` <span class="muted">on ${esc(s.port)}${s.service?" ("+esc(s.service)+")":""}</span>`; if(s.extrainfo) html+=`<div class="muted" style="margin-top:3px">${esc(s.extrainfo)}</div>`; for(const c of (s.cpes||[])) html+=`<div class="cpe">${esc(c)}</div>`; html+='</div>'; } } if((h.port_details||[]).length){ html+='<h4>🔌 Open Ports</h4>'; for(const p of h.port_details){ const svc=[p.service,p.product,p.version].filter(Boolean).join(" "); html+='<div class="item"><span class="sname">'+esc(p.port)+'/'+esc(p.protocol)+'</span>'+ ` <span class="muted">${esc(svc||"unknown service")}</span>`; for(const sc of (p.scripts||[])) if(sc.output) html+=`<pre class="script"><b>${esc(sc.id)}</b>\n${esc(sc.output)}</pre>`; html+='</div>'; } } if((h.host_scripts||[]).length){ html+='<h4>🧩 Host Scripts</h4>'; for(const sc of h.host_scripts) if(sc.output) html+=`<pre class="script"><b>${esc(sc.id)}</b>\n${esc(sc.output)}</pre>`; } html+='</div>'; return html; } function rescan(ev,ip){ ev.stopPropagation(); const profile=document.getElementById("profile").value; const options=collectOptions(); fetch(`/api/rescan/${ip}`,{method:"POST",headers:{"Content-Type":"application/json"}, body:JSON.stringify({profile,options})}).then(r=>r.json()).then(d=>{ if(d.ok){ startTimer(); setStatus("run","Re-scanning "+ip+"…"); showProgress(true); document.getElementById("scanBtn").disabled=true; poll(); } }); } function exportData(fmt){ const url="/api/export/"+fmt+(currentScanId?`?scan_id=${currentScanId}`:""); window.location=url; } // v8: export a focused report for a single host. function exportHost(ev,ip,fmt){ if(ev) ev.stopPropagation(); const url=`/api/export/host/${ip}/${fmt}`+(currentScanId?`?scan_id=${currentScanId}`:""); window.location=url; } function switchTab(name){ document.querySelectorAll(".tab").forEach(t=>t.classList.toggle("active",t.dataset.tab===name)); ["assets","software","compliance","certs","ad","history","remediation","more"].forEach(t=>{ const el=document.getElementById("tab-"+t); if(el) el.style.display=(t===name)?"":"none"; }); if(name==="history") loadHistory(); if(name==="software") renderSoftware(); if(name==="compliance") renderCompliance(); if(name==="certs") renderCerts(); if(name==="ad") renderAd(); if(name==="remediation") renderRemediation(); if(name==="more") renderPatch(); } let certsSortKey="ip", certsSortAsc=true; function renderCerts(){ const body=document.getElementById("certsBody"); if(!body) return; const q=((document.getElementById("certsFilter")||{}).value||"").toLowerCase(); let rows=[]; (currentHosts||[]).forEach(h=>(h.certificates||[]).forEach(c=>rows.push({ip:h.ip,c:c}))); rows=rows.filter(r=>{ if(!q) return true; const c=r.c; return (r.ip+" "+(c.port||"")+" "+(c.subject||"")+" "+(c.issuer||"")+" "+(c.status||"")).toLowerCase().includes(q); }); rows.sort((a,b)=>{ let av,bv; if(certsSortKey==="ip"){ av=ipNum(a.ip); bv=ipNum(b.ip); } else if(certsSortKey==="days_left"){ av=a.c.days_left==null?1e9:a.c.days_left; bv=b.c.days_left==null?1e9:b.c.days_left; } else if(certsSortKey==="port"){ av=parseInt(a.c.port)||0; bv=parseInt(b.c.port)||0; } else { av=(a.c[certsSortKey]||"").toString().toLowerCase(); bv=(b.c[certsSortKey]||"").toString().toLowerCase(); } if(av<bv) return certsSortAsc?-1:1; if(av>bv) return certsSortAsc?1:-1; return 0; }); const cnt=document.getElementById("certsCount"); if(cnt) cnt.textContent=`${rows.length} certificate(s)`; if(!rows.length){ body.innerHTML='<tr><td colspan="7" class="muted">No certificates. Run a scan with “SSL/TLS certs” enabled.</td></tr>'; return; } const badge={expired:'sev-high',expiring:'sev-warn',weak:'sev-high',ok:''}; body.innerHTML=rows.map(r=>{ const c=r.c; const cls=badge[c.status]||''; const st=cls?`<span class="${cls}">${esc(c.status)}</span>`:esc(c.status); return `<tr>`+ `<td><code>${esc(r.ip)}</code></td>`+ `<td><code>${esc(c.port||'')}</code></td>`+ `<td>${esc(c.subject||'-')}</td>`+ `<td>${esc(c.issuer||'-')}</td>`+ `<td>${esc((c.not_after||'-').slice(0,10))}</td>`+ `<td>${c.days_left==null?'-':c.days_left}</td>`+ `<td>${st}</td></tr>`; }).join(""); } function renderAd(){ const list=document.getElementById("adList"); if(!list) return; const dcs=(currentHosts||[]).filter(h=>h.ad&&h.ad.is_dc); const cnt=document.getElementById("adCount"); if(cnt) cnt.textContent=`${dcs.length} domain controller(s) detected`; if(!dcs.length){ list.innerHTML='<div class="muted">No Active Directory data yet. Run a scan with “AD / DC audit” enabled.</div>'; return; } list.innerHTML=dcs.map(h=>{ const ad=h.ad; const findings=(ad.findings||[]).map(f=> `<li><span class="sev-${esc(f.severity)}">${esc(f.severity)}</span> `+ `<b>${esc(f.title)}</b> — ${esc(f.detail)}</li>`).join(""); return `<div class="panel" style="margin-bottom:10px">`+ `<h2 style="margin:0 0 6px">🏢 ${esc(h.ip)} <span class="muted" style="font-size:12px">`+ `domain: ${esc(ad.domain||'-')} · forest: ${esc(ad.forest||'-')}</span></h2>`+ (findings?`<ul style="margin:4px 0 0 18px">${findings}</ul>`:'<div class="muted">No hardening issues found.</div>')+ `</div>`; }).join(""); } function loadHistory(){ fetch("/api/history").then(r=>r.json()).then(d=>{ const el=document.getElementById("history"); if(!d.scans||!d.scans.length){ el.innerHTML='<div class="muted">No scans yet.</div>'; return; } el.innerHTML=d.scans.map(s=>{ const when=s.finished?new Date(s.finished*1000).toLocaleString():"running…"; const stype=(s.scan_type==="passive") ?'<span class="badge passive">Passive</span>':'<span class="badge ok">Active</span>'; return `<div class="history-row" onclick="viewScan(${s.id})">`+ `<span style="width:130px" class="muted">${esc(when)}</span>`+ `<span style="width:140px"><code>${esc(s.target)}</code></span>`+ `<span style="width:80px">${esc(s.profile)}</span>`+ `<span style="width:74px">${stype}</span>`+ `<span style="width:70px">${esc(s.status)}</span>`+ `<span style="width:70px">${s.host_count} hosts</span>`+ `<span>${s.vuln_count} vulns · ${esc(s.triggered_by)}</span></div>`; }).join(""); }); } function viewScan(id){ fetch("/api/dashboard?scan_id="+id).then(r=>r.json()).then(d=>{ currentHosts=d.hosts||[]; currentScanId=id; currentCompliance=d.compliance||null; currentGroups=d.asset_groups||[]; renderCards(d.summary,d.scan); renderTopVulns(d.top_vulnerabilities||[]); renderChanges(d.changes||[]); renderComplianceSummary(currentCompliance); lastChart.os=d.os_distribution||{}; lastChart.sev=d.severity_distribution||{}; renderChart("os"); renderChart("sev"); renderSorted(); switchTab("assets"); }); } // =========================================================================== // v9.1: CVE lifecycle + service-desk tickets // =========================================================================== function lcLabel(s){ return ({open:"Open",remediated:"✅ Remediated",accepted_risk:"⚠ Accepted Risk",false_positive:"🚫 False Positive"})[s]||s; } let _lcCtx=null; function openLifecycle(ev,assetId,cve,ip){ if(ev) ev.stopPropagation(); _lcCtx={assetId,cve,ip}; document.getElementById("lcContext").innerHTML=`<b>${esc(cve)}</b> on <code>${esc(ip)}</code> (asset ${esc(assetId||"-")})`; document.getElementById("lcNote").value=""; document.getElementById("lcAllAssets").checked=false; document.getElementById("lcTicket").innerHTML=""; lifecycleMsg(""); document.getElementById("lifecycleModal").style.display="flex"; } function closeLifecycle(){ const m=document.getElementById("lifecycleModal"); if(m) m.style.display="none"; } function lifecycleMsg(t,err){ const el=document.getElementById("lifecycleMsg"); if(el){ el.textContent=t||""; el.style.color=err?"var(--danger)":"var(--muted)"; } } function setLifecycle(state){ if(!_lcCtx) return; const note=document.getElementById("lcNote").value.trim(); const all=document.getElementById("lcAllAssets").checked; fetch("/api/cve/lifecycle",{method:"POST",headers:{"Content-Type":"application/json"}, body:JSON.stringify({cve:_lcCtx.cve,asset_id:all?"*":_lcCtx.assetId,state,note})}).then(r=>r.json()).then(d=>{ if(!d.ok){ lifecycleMsg(d.error||"failed",true); return; } lifecycleMsg("Status updated to "+lcLabel(state)+"."); setTimeout(()=>{ closeLifecycle(); loadDashboard(); },600); }).catch(e=>lifecycleMsg(e.message,true)); } function openTicket(ev,assetId,cve,ip){ if(ev) ev.stopPropagation(); _lcCtx={assetId,cve,ip}; document.getElementById("lcContext").innerHTML=`<b>${esc(cve)}</b> on <code>${esc(ip)}</code> (asset ${esc(assetId||"-")})`; document.getElementById("lcNote").value=""; document.getElementById("lcAllAssets").checked=false; lifecycleMsg("Loading integrations…"); fetch("/api/integrations").then(r=>r.json()).then(d=>{ const box=document.getElementById("lcTicket"); const enabled=(d.integrations||[]).filter(i=>i.enabled); if(!d.ok || !enabled.length){ box.innerHTML='<div class="muted">No enabled service-desk integrations. An admin can add one under 🔗 Integrations.</div>'; } else { box.innerHTML=`<label class="so-label">Open ticket in:</label> `+ `<select id="tk-integ">${enabled.map(i=>`<option value="${i.id}">${esc(i.name)} (${esc(i.platform)})</option>`).join("")}</select> `+ `<button class="ghost mini" onclick="submitTicket()">Create ticket</button>`+ `<div id="tkMsg" class="muted" style="margin-top:6px"></div>`; } lifecycleMsg(""); }); document.getElementById("lifecycleModal").style.display="flex"; } function submitTicket(){ if(!_lcCtx) return; const sel=document.getElementById("tk-integ"); if(!sel) return; const msg=document.getElementById("tkMsg"); if(msg){ msg.textContent="Creating ticket…"; } fetch("/api/tickets",{method:"POST",headers:{"Content-Type":"application/json"}, body:JSON.stringify({integration_id:parseInt(sel.value,10),cve:_lcCtx.cve, asset_id:_lcCtx.assetId, summary:`[NetscanXi] ${_lcCtx.cve} on ${_lcCtx.ip}`, description:`Vulnerability ${_lcCtx.cve} detected on asset ${_lcCtx.assetId} (${_lcCtx.ip}).`}) }).then(r=>r.json()).then(d=>{ if(!d.ok){ if(msg){ msg.textContent=d.error||"failed"; msg.style.color="var(--danger)"; } return; } if(msg){ msg.style.color="var(--accent)"; msg.innerHTML=`Ticket created: <a href="${esc(d.url||"#")}" target="_blank" rel="noopener">${esc(d.key||"opened")}</a>`; } }).catch(e=>{ if(msg){ msg.textContent=e.message; msg.style.color="var(--danger)"; } }); } document.querySelectorAll("th[data-key]").forEach(th=>{ th.addEventListener("click",()=>{ const k=th.dataset.key; if(sortKey===k) sortAsc=!sortAsc; else { sortKey=k; sortAsc=true; } renderSorted(); }); }); // ---- User management (admin only) ---- function openUsers(){ const m=document.getElementById("usersModal"); if(!m) return; m.style.display="flex"; loadUsers(); } function closeUsers(){ const m=document.getElementById("usersModal"); if(m) m.style.display="none"; } function usersMsg(t,err){ const el=document.getElementById("usersMsg"); if(el){ el.textContent=t||""; el.style.color=err?"var(--danger)":"var(--muted)"; } } function loadUsers(){ fetch("/api/users").then(r=>r.json()).then(d=>{ const el=document.getElementById("usersList"); if(!el) return; if(!d.ok){ el.innerHTML='<div class="muted">'+esc(d.error||"error")+'</div>'; return; } // Populate tenant datalist for the add-user form. const dl=document.getElementById("tenant-options"); if(dl && d.tenants) dl.innerHTML=d.tenants.map(t=>`<option value="${esc(t)}">`).join(""); if(!d.users.length){ el.innerHTML='<div class="muted">No users yet.</div>'; return; } const roles=d.roles||["viewer","operator","admin"]; el.innerHTML=d.users.map(u=>{ const last=u.last_login?new Date(u.last_login*1000).toLocaleString():"never"; const opts=roles.map(r=>`<option value="${r}" ${r===u.role?"selected":""}>${r}</option>`).join(""); const tenant=esc(u.tenant||"default"); const mfaState = u.mfa_required ? (u.mfa_enrolled ? "on \u2713" : "on \u26a0 not set up") : (u.mfa_enrolled ? "optional \u2713" : "off"); const resetBtn = u.mfa_enrolled ? `<button class="ghost" style="font-size:11px" title="Reset this user's MFA enrollment" onclick="resetMfa(${u.id},'${esc(u.username)}')">reset MFA</button>` : ""; return `<div class="user-row">`+ `<input class="uname-input" value="${esc(u.username)}" title="Edit username (press Enter or blur to save)" `+ `data-orig="${esc(u.username)}" onchange="renameUser(${u.id},this)">`+ `<select onchange="changeRole(${u.id},this.value)">${opts}</select>`+ `<input class="tenant-input" value="${tenant}" title="Tenant" `+ `onchange="changeTenant(${u.id},this.value)" style="width:96px;padding:4px 6px">`+ `<button class="ghost" style="font-size:11px" title="Set / reset this user's password" `+ `onclick="adminSetPassword(${u.id},'${esc(u.username)}')">\u{1F511} set password</button>`+ `<label class="muted" style="font-size:11px" title="Force MFA for this user">`+ `<input type="checkbox" ${u.mfa_required?"checked":""} onchange="toggleMfa(${u.id},this.checked)"> MFA</label>`+ `<span class="muted" style="font-size:11px">${mfaState}</span>`+ resetBtn+ `<span class="muted" style="font-size:11px">last: ${esc(last)}</span>`+ `<button class="ghost danger-x" title="Delete" onclick="deleteUser(${u.id},'${esc(u.username)}')">\u2715</button>`+ `</div>`; }).join(""); }); } function createUser(){ const username=document.getElementById("nu-username").value.trim(); const password=document.getElementById("nu-password").value; const role=document.getElementById("nu-role").value; const tenant=(document.getElementById("nu-tenant").value.trim())||"default"; const mfaEl=document.getElementById("nu-mfa"); const mfa_required=mfaEl?mfaEl.checked:false; fetch("/api/users",{method:"POST",headers:{"Content-Type":"application/json"}, body:JSON.stringify({username,password,role,tenant,mfa_required})}).then(r=>r.json()).then(d=>{ if(d.ok){ usersMsg(mfa_required?"User created (MFA required — they set it up at first login).":"User created."); document.getElementById("nu-username").value=""; document.getElementById("nu-password").value=""; document.getElementById("nu-tenant").value=""; if(mfaEl) mfaEl.checked=false; loadUsers(); } else usersMsg(d.error||"failed",true); }).catch(e=>usersMsg(e.message,true)); } function changeTenant(id,tenant){ fetch(`/api/users/${id}`,{method:"PATCH",headers:{"Content-Type":"application/json"}, body:JSON.stringify({tenant:tenant.trim()||"default"})}).then(r=>r.json()).then(d=>{ if(d.ok) usersMsg("Tenant updated."); else { usersMsg(d.error||"failed",true); } loadUsers(); }); } function toggleMfa(id,on){ fetch(`/api/users/${id}`,{method:"PATCH",headers:{"Content-Type":"application/json"}, body:JSON.stringify({mfa_required:on})}).then(r=>r.json()).then(d=>{ if(d.ok) usersMsg(on?"MFA now required for this user.":"MFA no longer required."); else usersMsg(d.error||"failed",true); loadUsers(); }); } function resetMfa(id,name){ if(!confirm("Reset MFA for '"+name+"'? They will re-enroll an authenticator on next login.")) return; fetch(`/api/users/${id}`,{method:"PATCH",headers:{"Content-Type":"application/json"}, body:JSON.stringify({mfa_reset:true})}).then(r=>r.json()).then(d=>{ if(d.ok){ usersMsg("MFA reset."); loadUsers(); } else usersMsg(d.error||"failed",true); }); } function changeRole(id,role){ fetch(`/api/users/${id}`,{method:"PATCH",headers:{"Content-Type":"application/json"}, body:JSON.stringify({role})}).then(r=>r.json()).then(d=>{ if(d.ok) usersMsg("Role updated."); else { usersMsg(d.error||"failed",true); loadUsers(); } }); } // v8-r2: admin rename a user's username inline. function renameUser(id,inp){ const name=(inp.value||"").trim(); const orig=inp.dataset.orig||""; if(name===orig) return; if(name.length<2){ usersMsg("Username too short.",true); inp.value=orig; return; } fetch(`/api/users/${id}`,{method:"PATCH",headers:{"Content-Type":"application/json"}, body:JSON.stringify({username:name})}).then(r=>r.json()).then(d=>{ if(d.ok){ usersMsg("Username updated."); loadUsers(); } else { usersMsg(d.error||"failed",true); inp.value=orig; } }).catch(e=>{ usersMsg(e.message,true); inp.value=orig; }); } // v8-r2: admin set / reset a password for a (possibly locked-out) user. function adminSetPassword(id,name){ const pw=prompt("Set a new password for '"+name+"' (min 8 characters):"); if(pw===null) return; // cancelled if(pw.length<8){ usersMsg("Password must be ≥ 8 characters.",true); return; } fetch(`/api/users/${id}`,{method:"PATCH",headers:{"Content-Type":"application/json"}, body:JSON.stringify({password:pw})}).then(r=>r.json()).then(d=>{ if(d.ok){ usersMsg("Password set for '"+name+"'."); loadUsers(); } else usersMsg(d.error||"failed",true); }).catch(e=>usersMsg(e.message,true)); } function deleteUser(id,name){ if(!confirm("Delete user '"+name+"'?")) return; fetch(`/api/users/${id}`,{method:"DELETE"}).then(r=>r.json()).then(d=>{ if(d.ok){ usersMsg("User deleted."); loadUsers(); } else usersMsg(d.error||"failed",true); }); } // =========================================================================== // v6: Software inventory, Compliance, Scheduled scans // =========================================================================== const FRAMEWORKS = ["PCI DSS","GDPR","ISO 27001","SOC 2","HIPAA","Cyber Essentials","NIST CSF","NCSC CAF"]; function renderComplianceSummary(comp){ // v9.2: regulatory compliance now renders inside the customisable chart tile. lastChart.compliance = comp || null; renderChart("comp"); } let swSortKey="host", swSortAsc=true; function renderSoftware(){ const body=document.getElementById("softwareBody"); if(!body) return; const q=((document.getElementById("softwareFilter")||{}).value||"").toLowerCase(); const rows=[]; (currentHosts||[]).forEach(h=>{ (h.software||[]).forEach(sw=>{ rows.push({host:h.ip, hostname:h.hostname, name:sw.name||sw.service||"", version:sw.version||"", service:sw.service||"", port:sw.port||""}); }); }); const filt=rows.filter(r=>!q || (r.host+" "+r.hostname+" "+r.name+" "+r.version+" "+r.service).toLowerCase().includes(q)); filt.sort((a,b)=>{ let av,bv; if(swSortKey==="host"){ av=ipNum(a.host); bv=ipNum(b.host); } else if(swSortKey==="port"){ av=parseInt(a.port)||0; bv=parseInt(b.port)||0; } else { av=(a[swSortKey]||"").toString().toLowerCase(); bv=(b[swSortKey]||"").toString().toLowerCase(); } if(av<bv) return swSortAsc?-1:1; if(av>bv) return swSortAsc?1:-1; return 0; }); const cnt=document.getElementById("softwareCount"); if(cnt) cnt.textContent=`${filt.length} application(s) across ${currentHosts.length} host(s)`; if(!filt.length){ body.innerHTML='<tr><td colspan="5" class="muted">No software detected. Run a scan with “Running services” enabled.</td></tr>'; return; } body.innerHTML=filt.map(r=>`<tr>`+ `<td><code>${esc(r.host)}</code></td>`+ `<td>${esc(r.name)||'<span class="muted">unknown</span>'}</td>`+ `<td>${esc(r.version)||'<span class="muted">-</span>'}</td>`+ `<td>${esc(r.service)}</td>`+ `<td><code>${esc(r.port)}</code></td></tr>`).join(""); } function renderCompliance(){ const body=document.getElementById("complianceBody"); if(!body) return; const q=((document.getElementById("complianceFilter")||{}).value||"").toLowerCase(); let hosts=(currentHosts||[]).filter(h=>{ if(!q) return true; const c=h.compliance||{status:""}; return (h.ip+" "+(h.hostname||"")+" "+(c.status||"")).toLowerCase().includes(q); }); const cnt=document.getElementById("complianceHostCount"); if(cnt) cnt.textContent=`${hosts.length} host(s)`; if(!hosts.length){ body.innerHTML='<tr><td colspan="13" class="muted">No scan data yet.</td></tr>'; return; } body.innerHTML=hosts.map(h=>{ const c=h.compliance||{status:"compliant",frameworks:{}}; const statusBadge=c.status==="at_risk" ? '<span class="badge warn">At risk</span>' : '<span class="badge ok">Compliant</span>'; const cells=FRAMEWORKS.map(fw=>{ const f=(c.frameworks||{})[fw]||{status:"pass"}; return f.status==="fail" ? '<td class="comp-fail" title="Fails one or more controls">✗ fail</td>' : '<td class="comp-pass">✓ pass</td>'; }).join(""); const findings=(h.weak_auth||[]).length + (h.vulns||[]).length; const aid=h.asset_id?`<code class="asset-id">${esc(h.asset_id)}</code>`:'<span class="muted">-</span>'; const exp=`<button class="ghost mini" title="Export this asset (CSV)" onclick="exportHost(event,'${esc(h.ip)}','csv')">CSV</button>`+ ` <button class="ghost mini" title="Export this asset (JSON)" onclick="exportHost(event,'${esc(h.ip)}','json')">JSON</button>`+ ` <button class="ghost mini" title="Export this asset (PDF report)" onclick="exportHost(event,'${esc(h.ip)}','pdf')">PDF</button>`; return `<tr class="comp-host-row" onclick="toggleCompDetail(this)" data-ip="${esc(h.ip)}">`+ `<td>${aid}</td><td><code>${esc(h.ip)}</code></td><td>${statusBadge}</td>${cells}`+ `<td>${findings}</td><td class="comp-export" onclick="event.stopPropagation()">${exp}</td></tr>`+ `<tr class="comp-detail" style="display:none"><td colspan="13">${complianceDetail(h)}</td></tr>`; }).join(""); } function complianceDetail(h){ const c=h.compliance||{frameworks:{}}; let html=''; const weak=h.weak_auth||[]; if(weak.length){ html+='<div class="cd-section"><b>Credential-exposure findings</b><ul>'+ weak.map(w=>`<li><span class="sev-${esc(w.severity)}">${esc(w.severity)}</span> `+ `${esc(w.title)} <code>${esc(w.port)}</code> — ${esc(w.detail)} `+ `<i class="muted">Fix: ${esc(w.remediation)}</i></li>`).join("")+'</ul></div>'; } FRAMEWORKS.forEach(fw=>{ const f=(c.frameworks||{})[fw]; if(f && f.status==="fail" && f.controls.length){ html+=`<div class="cd-section"><b>${esc(fw)}</b><ul>`+ f.controls.map(ct=>`<li><code>${esc(ct.control)}</code> — ${esc(ct.evidence)}</li>`).join("")+ '</ul></div>'; } }); return html || '<span class="muted">No compliance issues for this host.</span>'; } function toggleCompDetail(row){ const det=row.nextElementSibling; if(det && det.classList.contains("comp-detail")) det.style.display = det.style.display==="none" ? "" : "none"; } // ---- Scheduled scans ---- function openSchedules(){ const m=document.getElementById("schedulesModal"); if(!m) return; m.style.display="flex"; loadSchedules(); } function closeSchedules(){ const m=document.getElementById("schedulesModal"); if(m) m.style.display="none"; } function schedMsg(t,err){ const el=document.getElementById("schedulesMsg"); if(el){ el.textContent=t||""; el.style.color=err?"var(--danger)":"var(--muted)"; } } function loadSchedules(){ fetch("/api/schedules").then(r=>r.json()).then(d=>{ const el=document.getElementById("schedulesList"); if(!el) return; if(!d.ok){ el.innerHTML='<div class="muted">'+esc(d.error||"error")+'</div>'; return; } if(!d.schedules.length){ el.innerHTML='<div class="muted">No schedules yet.</div>'; return; } el.innerHTML=d.schedules.map(s=>{ const nxt=s.next_run?new Date(s.next_run*1000).toLocaleString():"-"; const o=s.options||{}; const tags=[o.creds&&'creds',o.ad_audit&&'AD',o.ssl_certs&&'SSL'].filter(Boolean); const extra=tags.length?(' · '+tags.join('/')):''; // v9: describe weekly day/time schedule, else interval; + scan type. const DOW=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]; let cadence; if(s.days&&s.days.length){ const dd=s.days.map(d=>DOW[d]||d).join(","); const hh=String(s.hour||0).padStart(2,"0"), mm=String(s.minute||0).padStart(2,"0"); cadence=`${dd} @ ${hh}:${mm}`; } else { cadence=`every ${s.interval_minutes}m`; } const stype=(s.scan_type==="passive") ?'<span class="badge passive">Passive</span>':'<span class="badge ok">Active</span>'; return `<div class="user-row">`+ `<span class="u-name">${esc(s.name)}</span> ${stype}`+ `<span class="muted" style="font-size:11px"><code>${esc(s.target||"(auto)")}</code> · ${esc(s.profile)}${extra}</span>`+ `<span class="muted" style="font-size:11px">${esc(cadence)}</span>`+ `<label class="muted" style="font-size:11px"><input type="checkbox" ${s.enabled?"checked":""} onchange="toggleSchedule(${s.id},this.checked)"> on</label>`+ `<span class="muted" style="font-size:11px">next: ${esc(nxt)}</span>`+ `<button class="ghost" style="font-size:11px" onclick="runSchedule(${s.id})">run now</button>`+ `<button class="ghost danger-x" title="Delete" onclick="deleteSchedule(${s.id},'${esc(s.name)}')">\u2715</button>`+ `</div>`; }).join(""); }); } function createSchedule(){ const name=document.getElementById("ns-name").value.trim(); const target=document.getElementById("ns-target").value.trim(); const profile=document.getElementById("ns-profile").value; const scan_type=(document.getElementById("ns-scantype")||{}).value||"active"; const interval_minutes=parseInt(document.getElementById("ns-interval").value,10)||0; const creds=document.getElementById("ns-creds").checked; const ad_audit=(document.getElementById("ns-ad")||{}).checked||false; const ssl_certs=(document.getElementById("ns-ssl")||{}).checked||false; // v9: collect ticked days + time const days=Array.from(document.querySelectorAll(".ns-day:checked")).map(c=>parseInt(c.value,10)); const hourV=document.getElementById("ns-hour").value; const minuteV=document.getElementById("ns-minute").value; const hour=hourV===""?0:parseInt(hourV,10); const minute=minuteV===""?0:parseInt(minuteV,10); // Require EITHER ticked days (weekly) OR a valid interval. if(!days.length && (!interval_minutes||interval_minutes<1)){ schedMsg("Tick at least one day (with a time), or set an interval in minutes.",true); return; } const payload={name,target,profile,scan_type, interval_minutes:interval_minutes||1440, options:{creds,ad_audit,ssl_certs}}; if(days.length){ payload.days=days; payload.hour=hour; payload.minute=minute; } fetch("/api/schedules",{method:"POST",headers:{"Content-Type":"application/json"}, body:JSON.stringify(payload)}).then(r=>r.json()).then(d=>{ if(d.ok){ schedMsg("Schedule created."); document.getElementById("ns-name").value=""; document.getElementById("ns-target").value=""; document.getElementById("ns-interval").value=""; document.getElementById("ns-hour").value=""; document.getElementById("ns-minute").value=""; document.querySelectorAll(".ns-day:checked").forEach(c=>c.checked=false); document.getElementById("ns-creds").checked=false; if(document.getElementById("ns-ad")) document.getElementById("ns-ad").checked=false; if(document.getElementById("ns-ssl")) document.getElementById("ns-ssl").checked=false; loadSchedules(); } else schedMsg(d.error||"failed",true); }).catch(e=>schedMsg(e.message,true)); } function toggleSchedule(id,on){ fetch(`/api/schedules/${id}`,{method:"PATCH",headers:{"Content-Type":"application/json"}, body:JSON.stringify({enabled:on})}).then(r=>r.json()).then(d=>{ if(d.ok) schedMsg(on?"Schedule enabled.":"Schedule disabled."); else schedMsg(d.error||"failed",true); loadSchedules(); }); } function runSchedule(id){ fetch(`/api/schedules/${id}/run`,{method:"POST"}).then(r=>r.json()).then(d=>{ if(d.ok){ schedMsg("Scan queued for "+(d.target||"target")+"."); } else schedMsg(d.error||"failed",true); }); } function deleteSchedule(id,name){ if(!confirm("Delete schedule '"+name+"'?")) return; fetch(`/api/schedules/${id}`,{method:"DELETE"}).then(r=>r.json()).then(d=>{ if(d.ok){ schedMsg("Schedule deleted."); loadSchedules(); } else schedMsg(d.error||"failed",true); }); } // ---- MFA enrollment / management ---- function mfaMsg(t,err){ const el=document.getElementById("mfaMsg"); if(el){ el.textContent=t||""; el.style.color=err?"var(--danger)":"var(--muted)"; } } function _show(id,on){ const el=document.getElementById(id); if(el) el.style.display=on?"":"none"; } function openMfa(){ const m=document.getElementById("mfaModal"); if(!m) return; m.style.display="flex"; mfaMsg(""); cpMsg(""); clearPwFields(); loadMfaStatus(); } function closeMfa(){ const m=document.getElementById("mfaModal"); if(m) m.style.display="none"; } // v8-r2: self-service change-password. function cpMsg(t,err){ const el=document.getElementById("cpMsg"); if(el){ el.textContent=t||""; el.style.color=err?"var(--danger)":"var(--muted)"; } } function clearPwFields(){ ["cp-current","cp-new","cp-confirm"].forEach(id=>{ const e=document.getElementById(id); if(e) e.value=""; }); } function changeMyPassword(){ const cur=(document.getElementById("cp-current")||{}).value||""; const nw=(document.getElementById("cp-new")||{}).value||""; const cf=(document.getElementById("cp-confirm")||{}).value||""; if(nw.length<8){ cpMsg("New password must be ≥ 8 characters.",true); return; } if(nw!==cf){ cpMsg("New password and confirmation do not match.",true); return; } fetch("/api/account/password",{method:"POST",headers:{"Content-Type":"application/json"}, body:JSON.stringify({current_password:cur,new_password:nw})}).then(r=>r.json()).then(d=>{ if(d.ok){ cpMsg("Password updated."); clearPwFields(); } else cpMsg(d.error||"failed",true); }).catch(e=>cpMsg(e.message,true)); } function loadMfaStatus(){ _show("mfaEnroll",false); _show("mfaBackup",false); _show("mfaManage",false); fetch("/api/mfa/status").then(r=>r.json()).then(d=>{ const st=document.getElementById("mfaStatus"); if(!st) return; if(!d.ok){ st.textContent=d.error||"error"; return; } if(d.enrolled){ st.innerHTML='✅ MFA is <b>enabled</b> on your account.'+ (d.required?' <span class="muted">(required by an admin)</span>':'')+ ` <span class="muted">· ${d.backup_remaining} backup code(s) left</span>`; _show("mfaManage",true); // If admin enforces it, you can't self-disable. const btn=document.getElementById("mfaDisableBtn"); if(btn) btn.style.display=d.required?"none":""; } else { st.innerHTML=d.required ? '⚠️ MFA is <b>required</b> for your account — set it up now.' : 'MFA is not enabled. Add an authenticator app for stronger security.'; beginMfa(); } }); } function beginMfa(){ fetch("/api/mfa/enroll/begin",{method:"POST"}).then(r=>r.json()).then(d=>{ if(!d.ok){ mfaMsg(d.error||"failed",true); return; } document.getElementById("mfaSecret").textContent=d.secret; // cache-bust the QR (secret lives in session server-side) document.getElementById("mfaQr").src="/api/mfa/enroll/qr.png?t="+Date.now(); _show("mfaEnroll",true); const inp=document.getElementById("mfaConfirmCode"); if(inp){ inp.value=""; inp.focus(); } }); } function confirmMfa(){ const code=document.getElementById("mfaConfirmCode").value.trim(); fetch("/api/mfa/enroll/confirm",{method:"POST",headers:{"Content-Type":"application/json"}, body:JSON.stringify({code})}).then(r=>r.json()).then(d=>{ if(!d.ok){ mfaMsg(d.error||"code did not verify",true); return; } mfaMsg("MFA enabled."); _show("mfaEnroll",false); showBackupCodes(d.backup_codes||[]); window.NETSCAN_MUST_ENROLL=false; }).catch(e=>mfaMsg(e.message,true)); } function showBackupCodes(codes){ document.getElementById("mfaBackupCodes").textContent=codes.join("\n"); _show("mfaBackup",true); } function regenBackup(){ if(!confirm("Regenerate backup codes? Your old codes stop working.")) return; fetch("/api/mfa/backup/regenerate",{method:"POST"}).then(r=>r.json()).then(d=>{ if(!d.ok){ mfaMsg(d.error||"failed",true); return; } mfaMsg("New backup codes generated."); showBackupCodes(d.backup_codes||[]); }); } function disableMfa(){ if(!confirm("Disable MFA on your account?")) return; fetch("/api/mfa/disable",{method:"POST"}).then(r=>r.json()).then(d=>{ if(!d.ok){ mfaMsg(d.error||"failed",true); return; } mfaMsg("MFA disabled."); loadMfaStatus(); }); } // Auto-prompt enrollment when an admin has required it but the user hasn't set it up. if(window.NETSCAN_HAS_ACCOUNT && window.NETSCAN_MUST_ENROLL){ setTimeout(openMfa, 400); } // ---- v8: sortable Software / Certificates columns ---- document.querySelectorAll("#softwareTable th[data-skey]").forEach(th=>{ th.addEventListener("click",()=>{ const k=th.dataset.skey; if(swSortKey===k) swSortAsc=!swSortAsc; else { swSortKey=k; swSortAsc=true; } renderSoftware(); }); }); document.querySelectorAll("#certsTable th[data-ckey]").forEach(th=>{ th.addEventListener("click",()=>{ const k=th.dataset.ckey; if(certsSortKey===k) certsSortAsc=!certsSortAsc; else { certsSortKey=k; certsSortAsc=true; } renderCerts(); }); }); // =========================================================================== // v8: Activity / audit log (admin) // =========================================================================== let activityRows=[]; function openActivity(){ const m=document.getElementById("activityModal"); if(!m) return; m.style.display="flex"; loadActivity(); } function closeActivity(){ const m=document.getElementById("activityModal"); if(m) m.style.display="none"; } function activityMsg(t,err){ const el=document.getElementById("activityMsg"); if(el){ el.textContent=t||""; el.style.color=err?"var(--danger)":"var(--muted)"; } } function loadActivity(){ const sel=document.getElementById("activityTenant"); const tenant=sel?sel.value:""; const url="/api/activity"+(tenant?("?tenant="+encodeURIComponent(tenant)):""); fetch(url).then(r=>r.json()).then(d=>{ if(!d.ok){ activityMsg(d.error||"error",true); return; } activityRows=d.activity||[]; // Populate tenant dropdown once. if(sel && sel.options.length<=1 && d.tenants){ const cur=sel.value; sel.innerHTML='<option value="">All tenants</option>'+ d.tenants.map(t=>`<option value="${esc(t)}">${esc(t)}</option>`).join(""); sel.value=cur; } activityMsg(`${activityRows.length} event(s)`); renderActivity(); }).catch(e=>activityMsg(e.message,true)); } const ACTION_LABEL={login:"🔓 login",logout:"⎋ logout",login_failed:"⛔ login failed", scan:"🔍 scan",rescan:"🔁 re-scan",export:"📤 export",export_host:"📄 host export", user_create:"➕ user added",user_tenant:"🏢 tenant change",schedule_run:"⏱ schedule run", user_rename:"✏️ username change",user_password_reset:"🔑 admin password reset", password_change:"🔑 password changed",password_change_failed:"⛔ password change failed"}; function renderActivity(){ const body=document.getElementById("activityBody"); if(!body) return; const q=((document.getElementById("activityFilter")||{}).value||"").toLowerCase(); const rows=activityRows.filter(a=>!q || ((a.username||"")+" "+(a.action||"")+" "+(a.detail||"")+" "+(a.tenant||"")+" "+(a.ip||"")).toLowerCase().includes(q)); if(!rows.length){ body.innerHTML='<tr><td colspan="6" class="muted">No activity recorded.</td></tr>'; return; } body.innerHTML=rows.map(a=>{ const when=a.ts?new Date(a.ts*1000).toLocaleString():"-"; const act=ACTION_LABEL[a.action]||esc(a.action); const cls=a.action==="login_failed"?' class="act-fail"':(a.action==="login"||a.action==="logout"?' class="act-auth"':''); return `<tr${cls}>`+ `<td class="muted" style="white-space:nowrap">${esc(when)}</td>`+ `<td>${esc(a.username||"—")}</td>`+ `<td><code>${esc(a.tenant||"default")}</code></td>`+ `<td>${act}</td>`+ `<td class="muted">${esc(a.detail||"")}</td>`+ `<td class="muted"><code>${esc(a.ip||"")}</code></td></tr>`; }).join(""); } // =========================================================================== // v9.1: Global search (top nav) // =========================================================================== let _gsTimer=null; function onGlobalSearch(){ const inp=document.getElementById("globalSearch"); if(!inp) return; const q=inp.value.trim(); const box=document.getElementById("globalSearchResults"); if(_gsTimer) clearTimeout(_gsTimer); if(q.length<1){ if(box){ box.style.display="none"; box.innerHTML=""; } return; } _gsTimer=setTimeout(()=>{ fetch("/api/search?q="+encodeURIComponent(q)).then(r=>r.json()).then(d=>{ if(!box) return; const res=d.results||[]; if(!res.length){ box.innerHTML='<div class="gs-empty muted">No matches in the latest scan.</div>'; box.style.display=""; return; } const icon={asset:"\u{1F5A5}",vuln:"\u{1F6D1}",software:"\u{1F4E6}"}; box.innerHTML=res.map(r=>`<div class="gs-item" onclick="gsGoto('${esc(r.ip)}')">`+ `<span class="gs-type">${icon[r.type]||""}</span>`+ `<span class="gs-label">${esc(r.label)}</span>`+ `<span class="gs-detail muted">${esc(r.detail||"")}</span></div>`).join(""); box.style.display=""; }).catch(()=>{}); },220); } function gsGoto(ip){ const box=document.getElementById("globalSearchResults"); if(box) box.style.display="none"; const gi=document.getElementById("globalSearch"); if(gi) gi.value=""; switchTab("assets"); expanded[ip]=true; renderSorted(); setTimeout(()=>{ const rows=[...document.querySelectorAll("#tbody tr.host-row")]; const tgt=rows.find(tr=>tr.querySelector("code") && tr.querySelector("code").textContent===ip); if(tgt) tgt.scrollIntoView({behavior:"smooth",block:"center"}); },60); } document.addEventListener("click",e=>{ const gs=document.querySelector(".global-search"); if(gs && !gs.contains(e.target)){ const b=document.getElementById("globalSearchResults"); if(b) b.style.display="none"; } }); // =========================================================================== // v9.1: Service-desk integrations admin // =========================================================================== function openIntegrations(){ const m=document.getElementById("integrationsModal"); if(!m) return; m.style.display="flex"; integHints(); loadIntegrations(); } function closeIntegrations(){ const m=document.getElementById("integrationsModal"); if(m) m.style.display="none"; } function integMsg(t,err){ const el=document.getElementById("integrationsMsg"); if(el){ el.textContent=t||""; el.style.color=err?"var(--danger)":"var(--muted)"; } } const CORTEX_DEFAULT_URL="http://localhost:8000"; function integHints(){ const p=(document.getElementById("ni-platform")||{}).value; const hints={ jira:"Jira Cloud: Base URL https://acme.atlassian.net \u00b7 user = your email \u00b7 secret = API token \u00b7 project = project key (e.g. SEC).", servicenow:"ServiceNow: Base URL https://acme.service-now.com \u00b7 user/password \u00b7 project = table (default 'incident').", zendesk:"Zendesk: Base URL https://acme.zendesk.com \u00b7 user = email/token \u00b7 secret = API token \u00b7 project = group (optional).", cortex:"Synapse Cortex: Base URL defaults to "+CORTEX_DEFAULT_URL+" (NetscanXi appends /api/ingest/tickets) \u00b7 secret = Cortex API key (Admin \u2192 Integrations) \u00b7 project = default priority low/medium/high/critical (optional, default high). User is not used." }; const el=document.getElementById("integHint"); if(el) el.textContent=hints[p]||""; // Default the Cortex ingest URL so the admin doesn't have to know it; only // pre-fill when the field is empty so we never clobber a typed value. const urlEl=document.getElementById("ni-url"); if(urlEl && p==="cortex" && !urlEl.value.trim()) urlEl.value=CORTEX_DEFAULT_URL; } function loadIntegrations(){ fetch("/api/integrations").then(r=>r.json()).then(d=>{ const el=document.getElementById("integrationsList"); if(!el) return; if(!d.ok){ el.innerHTML='<div class="muted">'+esc(d.error||"error")+'</div>'; return; } if(!d.integrations.length){ el.innerHTML='<div class="muted">No integrations yet.</div>'; return; } el.innerHTML=d.integrations.map(i=>{ const last=i.last_used?new Date(i.last_used*1000).toLocaleString():"never"; return `<div class="user-row">`+ `<span class="u-name">${esc(i.name)}</span> <span class="badge ok">${esc(i.platform)}</span>`+ `<span class="muted" style="font-size:11px"><code>${esc(i.base_url)}</code></span>`+ `<label class="muted" style="font-size:11px"><input type="checkbox" ${i.enabled?"checked":""} onchange="toggleIntegration(${i.id},this.checked)"> on</label>`+ `<span class="muted" style="font-size:11px">used: ${esc(last)}</span>`+ `<button class="ghost" style="font-size:11px" onclick="testIntegration(${i.id})">test</button>`+ `<button class="ghost danger-x" title="Delete" onclick="deleteIntegration(${i.id},'${esc(i.name)}')">\u2715</button>`+ `</div>`; }).join(""); }); } function createIntegration(){ const payload={ platform:document.getElementById("ni-platform").value, name:document.getElementById("ni-name").value.trim(), base_url:document.getElementById("ni-url").value.trim(), auth_user:document.getElementById("ni-user").value.trim(), auth_secret:document.getElementById("ni-secret").value, project_key:document.getElementById("ni-project").value.trim(), }; if(!payload.base_url){ integMsg("Base URL is required.",true); return; } fetch("/api/integrations",{method:"POST",headers:{"Content-Type":"application/json"}, body:JSON.stringify(payload)}).then(r=>r.json()).then(d=>{ if(d.ok){ integMsg("Integration added."); ["ni-name","ni-url","ni-user","ni-secret","ni-project"].forEach(id=>document.getElementById(id).value=""); loadIntegrations(); } else integMsg(d.error||"failed",true); }).catch(e=>integMsg(e.message,true)); } function toggleIntegration(id,on){ fetch(`/api/integrations/${id}`,{method:"PATCH",headers:{"Content-Type":"application/json"}, body:JSON.stringify({enabled:on})}).then(r=>r.json()).then(d=>{ if(!d.ok) integMsg(d.error||"failed",true); loadIntegrations(); }); } function testIntegration(id){ integMsg("Testing connection\u2026"); fetch(`/api/integrations/${id}/test`,{method:"POST"}).then(r=>r.json()).then(d=>{ if(d.ok) integMsg("\u2705 "+(d.detail||"Connection OK.")); else integMsg("\u274c "+(d.error||"connection failed"),true); }).catch(e=>integMsg(e.message,true)); } function deleteIntegration(id,name){ if(!confirm("Delete integration '"+name+"'?")) return; fetch(`/api/integrations/${id}`,{method:"DELETE"}).then(r=>r.json()).then(d=>{ if(d.ok){ integMsg("Deleted."); loadIntegrations(); } else integMsg(d.error||"failed",true); }); } // =========================================================================== // v9.1: Admin settings - data retention policy // =========================================================================== function openAdminSettings(){ const m=document.getElementById("adminModal"); if(!m) return; m.style.display="flex"; loadRetention(); } function closeAdminSettings(){ const m=document.getElementById("adminModal"); if(m) m.style.display="none"; } function adminMsg(t,err){ const el=document.getElementById("adminMsg"); if(el){ el.textContent=t||""; el.style.color=err?"var(--danger)":"var(--muted)"; } } function loadRetention(){ fetch("/api/settings/retention").then(r=>r.json()).then(d=>{ if(!d.ok){ adminMsg(d.error||"error",true); return; } const p=d.policy||{}; document.getElementById("ret-age").value=p.max_age_days||""; document.getElementById("ret-scans").value=p.max_scans||""; document.getElementById("ret-auto").checked=!!p.auto_apply; const c=document.getElementById("retScanCount"); if(c) c.textContent=`Currently storing ${d.scan_count} scan(s).`; adminMsg(""); }); } function saveRetention(applyNow){ const payload={ max_age_days:parseInt(document.getElementById("ret-age").value,10)||0, max_scans:parseInt(document.getElementById("ret-scans").value,10)||0, auto_apply:document.getElementById("ret-auto").checked, apply_now:!!applyNow, }; fetch("/api/settings/retention",{method:"POST",headers:{"Content-Type":"application/json"}, body:JSON.stringify(payload)}).then(r=>r.json()).then(d=>{ if(!d.ok){ adminMsg(d.error||"failed",true); return; } adminMsg(applyNow?`Policy saved \u00b7 purged ${d.removed} old scan(s).`:"Policy saved."); loadRetention(); if(applyNow) loadDashboard(); }).catch(e=>adminMsg(e.message,true)); } // =========================================================================== // v13: Synapse Sonar sync - PUSH config/test + PULL (outbound) API // =========================================================================== function openSonar(){ const m=document.getElementById("sonarModal"); if(!m) return; m.style.display="flex"; sonarResult(""); loadSonar(); loadOutbound(); } function closeSonar(){ const m=document.getElementById("sonarModal"); if(m) m.style.display="none"; } function copyText(id){ const el=document.getElementById(id); if(!el||!el.value) return; el.select(); if(navigator.clipboard) navigator.clipboard.writeText(el.value).catch(()=>{}); else document.execCommand("copy"); } // ---- PUSH: NetscanXi -> Sonar ---- function sonarMsg(t,err){ const el=document.getElementById("sonarMsg"); if(el){ el.textContent=t||""; el.style.color=err?"var(--danger)":"var(--muted)"; } } function sonarResult(t,ok){ const el=document.getElementById("sonar-result"); if(el){ el.textContent=t||""; el.style.color=ok?"var(--ok,#2e9e5b)":"var(--danger)"; } } function loadSonar(){ fetch("/api/settings/sonar").then(r=>r.json()).then(d=>{ if(!d.ok){ sonarMsg(d.error||"error",true); return; } const c=d.config||{}; document.getElementById("sonar-url").value=c.url||""; document.getElementById("sonar-key").value=""; document.getElementById("sonar-enabled").checked=!!c.enabled; document.getElementById("sonar-verify").checked=c.verify_tls!==false; const ks=document.getElementById("sonar-key-state"); if(ks) ks.textContent=c.key_set?"An API key is saved · leave blank to keep it.":"No API key saved yet."; sonarMsg(""); }).catch(e=>sonarMsg(e.message,true)); } function sonarPayload(){ return { url:document.getElementById("sonar-url").value.trim(), api_key:document.getElementById("sonar-key").value, enabled:document.getElementById("sonar-enabled").checked, verify_tls:document.getElementById("sonar-verify").checked, }; } function saveSonar(){ const payload=sonarPayload(); if(!payload.url){ sonarMsg("API URL is required.",true); return; } fetch("/api/settings/sonar",{method:"POST",headers:{"Content-Type":"application/json"}, body:JSON.stringify(payload)}).then(r=>r.json()).then(d=>{ if(!d.ok){ sonarMsg(d.error||"failed",true); return; } sonarMsg("Settings saved."); loadSonar(); }).catch(e=>sonarMsg(e.message,true)); } function testSonar(){ sonarResult("Testing…"); const el=document.getElementById("sonar-result"); if(el) el.style.color="var(--muted)"; sonarMsg(""); fetch("/api/settings/sonar/test",{method:"POST",headers:{"Content-Type":"application/json"}, body:JSON.stringify(sonarPayload())}).then(r=>r.json()).then(d=>{ if(d.ok){ sonarResult("✅ OK Connected",true); sonarMsg(d.detail||""); } else { sonarResult("❌ Failed to Connect",false); sonarMsg(d.error||"connection failed",true); } }).catch(e=>{ sonarResult("❌ Failed to Connect",false); sonarMsg(e.message,true); }); } function pushSonar(){ sonarMsg("Sending latest scan…"); fetch("/api/sonar/push",{method:"POST"}).then(r=>r.json()).then(d=>{ if(d.ok){ const s=d.summary||{}; sonarMsg(`Sent ${d.sent||0} finding(s). Sonar: ${s.assetsTouched||0} asset(s), ${s.vulnsUpserted||0} vuln(s).`); } else sonarMsg(d.error||"push failed",true); }).catch(e=>sonarMsg(e.message,true)); } // ---- PULL: Sonar <- NetscanXi (outbound API this instance exposes) ---- function outboundMsg(t,err){ const el=document.getElementById("outboundMsg"); if(el){ el.textContent=t||""; el.style.color=err?"var(--danger)":"var(--muted)"; } } function applyOutbound(c){ document.getElementById("outbound-url").value=c.endpoint_url||""; document.getElementById("outbound-enabled").checked=!!c.enabled; const st=document.getElementById("outbound-key-state"); if(st) st.textContent=c.key_set?"· configured":"· not issued"; const gen=document.getElementById("outbound-gen-btn"); if(gen) gen.textContent=c.key_set?"Regenerate API key":"Generate API key"; } function loadOutbound(){ document.getElementById("outbound-key").value=""; fetch("/api/settings/outbound").then(r=>r.json()).then(d=>{ if(!d.ok){ outboundMsg(d.error||"error",true); return; } applyOutbound(d.config||{}); outboundMsg(""); }).catch(e=>outboundMsg(e.message,true)); } function genOutboundKey(){ if(!confirm("Generate a new API key? Any existing key stops working immediately.")) return; outboundMsg("Generating…"); fetch("/api/settings/outbound/key",{method:"POST"}).then(r=>r.json()).then(d=>{ if(!d.ok){ outboundMsg(d.error||"failed",true); return; } applyOutbound(d.config||{}); document.getElementById("outbound-key").value=d.api_key||""; outboundMsg("Key generated. Copy it now and paste the URL + key into Synapse Sonar — it won't be shown again."); }).catch(e=>outboundMsg(e.message,true)); } function toggleOutbound(on){ fetch("/api/settings/outbound",{method:"POST",headers:{"Content-Type":"application/json"}, body:JSON.stringify({enabled:on})}).then(r=>r.json()).then(d=>{ if(!d.ok){ outboundMsg(d.error||"failed",true); return; } applyOutbound(d.config||{}); outboundMsg(on?"Pull API enabled.":"Pull API disabled."); }).catch(e=>outboundMsg(e.message,true)); } function revokeOutbound(){ if(!confirm("Revoke the API key and disable the pull API? Synapse Sonar will stop syncing from here.")) return; fetch("/api/settings/outbound/key",{method:"DELETE"}).then(r=>r.json()).then(d=>{ if(!d.ok){ outboundMsg(d.error||"failed",true); return; } applyOutbound(d.config||{}); document.getElementById("outbound-key").value=""; outboundMsg("Key revoked. Generate a new one to re-enable syncing."); }).catch(e=>outboundMsg(e.message,true)); } // =========================================================================== // v13: Synapse Cortex asset feed - PUSH only (mirrors the Sonar push block // above; there is no pull/outbound direction for Cortex) // =========================================================================== function openCortex(){ const m=document.getElementById("cortexModal"); if(!m) return; m.style.display="flex"; cortexResult(""); loadCortex(); } function closeCortex(){ const m=document.getElementById("cortexModal"); if(m) m.style.display="none"; } function cortexMsg(t,err){ const el=document.getElementById("cortexMsg"); if(el){ el.textContent=t||""; el.style.color=err?"var(--danger)":"var(--muted)"; } } function cortexResult(t,ok){ const el=document.getElementById("cortex-result"); if(el){ el.textContent=t||""; el.style.color=ok?"var(--ok,#2e9e5b)":"var(--danger)"; } } function loadCortex(){ fetch("/api/settings/cortex").then(r=>r.json()).then(d=>{ if(!d.ok){ cortexMsg(d.error||"error",true); return; } const c=d.config||{}; document.getElementById("cortex-url").value=c.url||""; document.getElementById("cortex-key").value=""; document.getElementById("cortex-enabled").checked=!!c.enabled; document.getElementById("cortex-verify").checked=c.verify_tls!==false; const ks=document.getElementById("cortex-key-state"); if(ks) ks.textContent=c.key_set?"An API key is saved · leave blank to keep it.":"No API key saved yet."; cortexMsg(""); }).catch(e=>cortexMsg(e.message,true)); } function cortexPayload(){ return { url:document.getElementById("cortex-url").value.trim(), api_key:document.getElementById("cortex-key").value, enabled:document.getElementById("cortex-enabled").checked, verify_tls:document.getElementById("cortex-verify").checked, }; } function saveCortex(){ const payload=cortexPayload(); if(!payload.url){ cortexMsg("API URL is required.",true); return; } fetch("/api/settings/cortex",{method:"POST",headers:{"Content-Type":"application/json"}, body:JSON.stringify(payload)}).then(r=>r.json()).then(d=>{ if(!d.ok){ cortexMsg(d.error||"failed",true); return; } cortexMsg("Settings saved."); loadCortex(); }).catch(e=>cortexMsg(e.message,true)); } function testCortex(){ cortexResult("Testing…"); const el=document.getElementById("cortex-result"); if(el) el.style.color="var(--muted)"; cortexMsg(""); fetch("/api/settings/cortex/test",{method:"POST",headers:{"Content-Type":"application/json"}, body:JSON.stringify(cortexPayload())}).then(r=>r.json()).then(d=>{ if(d.ok){ cortexResult("✅ OK Connected",true); cortexMsg(d.detail||""); } else { cortexResult("❌ Failed to Connect",false); cortexMsg(d.error||"connection failed",true); } }).catch(e=>{ cortexResult("❌ Failed to Connect",false); cortexMsg(e.message,true); }); } function pushCortex(){ cortexMsg("Sending latest scan…"); fetch("/api/cortex/push",{method:"POST"}).then(r=>r.json()).then(d=>{ if(d.ok){ let msg=`Sent ${d.sent||0} asset(s). Cortex: ${d.created||0} created, ${d.updated||0} updated.`; if(d.failed){ const ex=(d.errors&&d.errors[0])?` (e.g. ${d.errors[0].asset_id}: ${d.errors[0].error})`:""; msg+=` — ${d.failed} failed${ex}`; } cortexMsg(msg, !!d.failed); } else cortexMsg(d.error||"push failed",true); }).catch(e=>cortexMsg(e.message,true)); } // v13: per-item Cortex ticket - sends ONE selected Remediation Tracking item to // Cortex as a ticket (same API the old bulk auto-send used). Invoked from the // "🧠 Cortex Ticket" button on each row of the Remediation Tracking tab. function sendCortexTicket(ev,remId){ if(ev) ev.stopPropagation(); const btn=ev&&ev.currentTarget; const label=btn?btn.textContent:""; if(btn){ btn.disabled=true; btn.textContent="Sending…"; } const done=()=>{ if(btn){ btn.disabled=false; btn.textContent=label; } }; fetch("/api/cortex/ticket",{method:"POST",headers:{"Content-Type":"application/json"}, body:JSON.stringify({remediation_id:remId})}).then(r=>r.json()).then(d=>{ done(); if(!d.ok){ remMsg("Cortex ticket failed: "+(d.error||"unknown error"),true); return; } if(d.created) remMsg("Cortex ticket created."); else remMsg("A Cortex ticket already exists for this item — left unchanged."); }).catch(e=>{ done(); remMsg("Cortex ticket failed: "+e.message,true); }); } // v13: vulnerability ticket - gather an asset's vulnerabilities, let the user // pick which to send, then raise a Synapse Cortex ticket. Opened from the // "🎫 Create ticket" button in an asset's detail panel (Assets tab). let _vtHost=null; function openVulnTicket(ev,assetId){ if(ev) ev.stopPropagation(); const h=(currentHosts||[]).find(x=>x.asset_id===assetId); if(!h){ alert("Asset not found in the current scan. Reload the dashboard and try again."); return; } const vulns=(h.vulns||[]).filter(v=>(v.cve||v.id)); if(!vulns.length){ alert("This asset has no vulnerabilities to ticket."); return; } _vtHost=h; vtResult(""); vtMsg(""); const ctx=document.getElementById("vt-context"); if(ctx) ctx.innerHTML=`<b>${esc(h.hostname||h.ip)}</b> <span class="muted">(asset ${esc(h.asset_id)} · ${esc(h.ip)})</span> — ${vulns.length} vulnerabilit${vulns.length===1?"y":"ies"} found. Select which to include, then send to Synapse Cortex.`; const sorted=vulns.slice().sort((a,b)=>((b.kev?1:0)-(a.kev?1:0))||(parseFloat(b.cvss||0)-parseFloat(a.cvss||0))); const box=document.getElementById("vt-list"); box.innerHTML=sorted.map(v=>{ const cve=esc(v.cve||v.id); const cvss=v.cvss?`CVSS ${esc(v.cvss)}`:""; const kev=v.kev?' <span class="tag kev">KEV</span>':''; const exp=v.exploit?' <span class="tag exp">EXPLOIT</span>':''; const prod=[v.product,v.version].filter(Boolean).map(esc).join(" "); const sub=[prod, (v.port&&v.port!=="host")?("port "+esc(v.port)):""].filter(Boolean).join(" · "); return `<label style="display:flex;gap:8px;align-items:flex-start;padding:5px 3px;border-bottom:1px solid var(--border,#222)">`+ `<input type="checkbox" class="vt-chk" value="${cve}" checked onchange="vtUpdateCount()" style="margin-top:3px">`+ `<span style="flex:1"><b>${cve}</b> <span class="muted">${cvss}</span>${kev}${exp}`+ (sub?`<div class="muted" style="font-size:11px">${sub}</div>`:"")+`</span></label>`; }).join(""); vtUpdateCount(); const m=document.getElementById("vulnTicketModal"); if(m) m.style.display="flex"; } function closeVulnTicket(){ const m=document.getElementById("vulnTicketModal"); if(m) m.style.display="none"; } function _vtChecks(){ return Array.prototype.slice.call(document.querySelectorAll(".vt-chk")); } function vtToggleAll(on){ _vtChecks().forEach(c=>{ c.checked=on; }); vtUpdateCount(); } function vtUpdateCount(){ const n=_vtChecks().filter(c=>c.checked).length; const el=document.getElementById("vt-count"); if(el) el.textContent=`${n} selected`; } function vtResult(t,ok){ const el=document.getElementById("vt-result"); if(el){ el.textContent=t||""; el.style.color=ok?"var(--ok,#2e9e5b)":"var(--danger)"; } } function vtMsg(t,err){ const el=document.getElementById("vt-msg"); if(el){ el.textContent=t||""; el.style.color=err?"var(--danger)":"var(--muted)"; } } function submitVulnTicket(){ if(!_vtHost) return; const cves=_vtChecks().filter(c=>c.checked).map(c=>c.value); if(!cves.length){ vtMsg("Select at least one vulnerability to send.",true); return; } vtResult("Sending…"); const r=document.getElementById("vt-result"); if(r) r.style.color="var(--muted)"; vtMsg(""); fetch("/api/cortex/vuln-ticket",{method:"POST",headers:{"Content-Type":"application/json"}, body:JSON.stringify({asset_id:_vtHost.asset_id, cves})}).then(res=>res.json()).then(d=>{ if(!d.ok){ vtResult("❌ Failed",false); vtMsg(d.error||"send failed",true); return; } if(d.created){ vtResult("✅ Sent to Cortex",true); vtMsg(`Ticket created with ${cves.length} vulnerabilit${cves.length===1?"y":"ies"}.`); } else if(d.skipped){ vtResult("Already exists",true); vtMsg("A vulnerability ticket already exists for this asset in Cortex — left unchanged. (Cortex tickets are create-only.)"); } else { vtResult("Sent",true); vtMsg("Sent to Cortex."); } }).catch(e=>{ vtResult("❌ Failed",false); vtMsg(e.message,true); }); } // =========================================================================== // v9.1: Dashboard customization - drag / pin / hide / persist // =========================================================================== const DASH_DEFAULT=["cards","docker","charts","vulns"]; let dashEdit=false; function getLayout(){ let order=DASH_DEFAULT.slice(), hidden=[], pinned=[]; try{ const raw=localStorage.getItem("netscan-dash"); if(raw){ const o=JSON.parse(raw); order=o.order||order; hidden=o.hidden||[]; pinned=o.pinned||[]; } }catch(e){} return {order,hidden,pinned}; } function saveLayout(l){ try{ localStorage.setItem("netscan-dash",JSON.stringify(l)); }catch(e){} fetch("/api/dashboard/layout",{method:"POST",headers:{"Content-Type":"application/json"}, body:JSON.stringify({layout:l.order})}).catch(()=>{}); } function applyDashLayout(){ const grid=document.getElementById("dashGrid"); if(!grid) return; const l=getLayout(); const ordered=[...l.pinned, ...l.order.filter(c=>!l.pinned.includes(c))]; ordered.forEach(c=>{ const el=document.getElementById("comp-"+c); if(el) grid.appendChild(el); }); DASH_DEFAULT.forEach(c=>{ const el=document.getElementById("comp-"+c); if(!el) return; // v10r1: a component flagged data-empty="1" (e.g. Docker with no docker // hosts) stays hidden regardless of layout preference. const forceHide=el.dataset.empty==="1"; el.style.display=(l.hidden.includes(c)||forceHide)?"none":""; el.classList.toggle("pinned",l.pinned.includes(c)); }); const hb=document.getElementById("dashHidden"); if(hb){ hb.innerHTML=l.hidden.length?("Hidden: "+l.hidden.map(c=> `<button class="ghost mini" onclick="showComp('${c}')">+ ${c}</button>`).join(" ")):""; } } function toggleDashEdit(){ dashEdit=!dashEdit; document.getElementById("dashGrid").classList.toggle("editing",dashEdit); const b=document.getElementById("dashEditBtn"); if(b) b.textContent=dashEdit?"\u2713 Done":"\u270e Customise"; if(dashEdit) enableDrag(); } function hideComp(c){ const l=getLayout(); if(!l.hidden.includes(c)) l.hidden.push(c); l.pinned=l.pinned.filter(x=>x!==c); saveLayout(l); applyDashLayout(); } function showComp(c){ const l=getLayout(); l.hidden=l.hidden.filter(x=>x!==c); saveLayout(l); applyDashLayout(); } function pinComp(c){ const l=getLayout(); if(l.pinned.includes(c)) l.pinned=l.pinned.filter(x=>x!==c); else l.pinned.push(c); saveLayout(l); applyDashLayout(); } function resetDashLayout(){ try{ localStorage.removeItem("netscan-dash"); }catch(e){} applyDashLayout(); } function enableDrag(){ const grid=document.getElementById("dashGrid"); if(!grid) return; grid.querySelectorAll(".dash-comp").forEach(el=>{ el.setAttribute("draggable","true"); el.ondragstart=e=>{ e.dataTransfer.setData("text/plain",el.dataset.comp); el.classList.add("dragging"); }; el.ondragend=()=>el.classList.remove("dragging"); el.ondragover=e=>{ e.preventDefault(); }; el.ondrop=e=>{ e.preventDefault(); const from=e.dataTransfer.getData("text/plain"); const to=el.dataset.comp; if(from===to) return; const l=getLayout(); let order=[...grid.querySelectorAll(".dash-comp")].map(x=>x.dataset.comp); order=order.filter(x=>x!==from); const idx=order.indexOf(to); order.splice(idx,0,from); l.order=order; saveLayout(l); applyDashLayout(); enableDrag(); }; }); } function initDashLayout(){ fetch("/api/dashboard/layout").then(r=>r.json()).then(d=>{ if(d.ok && Array.isArray(d.layout) && d.layout.length){ const l=getLayout(); l.order=d.layout; saveLayout(l); } }).catch(()=>{}).finally(applyDashLayout); } initDashLayout(); initCharts(); loadDashboard(); // =========================================================================== // v12: Asset groups - admin CRUD + per-asset assignment (tenant-separated) // =========================================================================== function openGroupsAdmin(){ const m=document.getElementById("groupsAdminModal"); if(!m) return; m.style.display="flex"; loadGroupsAdmin(); } function closeGroupsAdmin(){ const m=document.getElementById("groupsAdminModal"); if(m) m.style.display="none"; } function gaMsg(t,err){ const el=document.getElementById("groupsAdminMsg"); if(el){ el.textContent=t||""; el.style.color=err?"var(--danger)":"var(--muted)"; } } function loadGroupsAdmin(){ fetch("/api/asset-groups").then(r=>r.json()).then(d=>{ const el=document.getElementById("groupsAdminList"); if(!el) return; const groups=d.groups||[]; currentGroups=groups; if(!groups.length){ el.innerHTML='<div class="muted">No groups yet.</div>'; return; } el.innerHTML=groups.map(g=>`<div class="user-row">`+ `<span class="u-name">${esc(g.name)}</span>`+ (g.description?` <span class="muted" style="font-size:11px">${esc(g.description)}</span>`:"")+ ` <span class="muted" style="font-size:11px">${g.member_count} asset(s)</span>`+ ` <button class="ghost danger-x" title="Delete group" onclick="deleteGroup(${g.id},'${esc(g.name)}')">\u2715</button>`+ `</div>`).join(""); }); } function createGroup(){ const name=(document.getElementById("ng-name")||{}).value.trim(); const description=(document.getElementById("ng-desc")||{}).value.trim(); if(!name){ gaMsg("Group name is required.",true); return; } fetch("/api/asset-groups",{method:"POST",headers:{"Content-Type":"application/json"}, body:JSON.stringify({name,description})}).then(r=>r.json()).then(d=>{ if(d.ok){ gaMsg("Group created."); document.getElementById("ng-name").value=""; document.getElementById("ng-desc").value=""; loadGroupsAdmin(); } else gaMsg(d.error||"failed",true); }).catch(e=>gaMsg(e.message,true)); } function deleteGroup(id,name){ if(!confirm("Delete group '"+name+"'? Assets will be unassigned from it.")) return; fetch(`/api/asset-groups/${id}`,{method:"DELETE"}).then(r=>r.json()).then(d=>{ if(d.ok){ gaMsg("Deleted."); loadGroupsAdmin(); loadDashboard(); } else gaMsg(d.error||"failed",true); }); } function openAssetGroups(ev,assetId){ if(ev) ev.stopPropagation(); agAsset=assetId; const m=document.getElementById("assetGroupsModal"); if(!m) return; const ctx=document.getElementById("agContext"); if(ctx) ctx.innerHTML=`Assign asset <code>${esc(assetId)}</code> to groups:`; const msg=document.getElementById("assetGroupsMsg"); if(msg) msg.textContent=""; const host=(currentHosts||[]).find(h=>h.asset_id===assetId); const memberIds=new Set(((host&&host.groups)||[]).map(g=>g.id)); const list=document.getElementById("agList"); if(!currentGroups.length){ list.innerHTML='<div class="muted">No groups defined yet. An admin can create them via \u{1F5C2} Asset Groups in the toolbar.</div>'; } else { list.innerHTML=currentGroups.map(g=> `<label class="ag-item"><input type="checkbox" value="${g.id}" ${memberIds.has(g.id)?"checked":""}> ${esc(g.name)}`+ (g.description?` <span class="muted">\u2014 ${esc(g.description)}</span>`:"")+`</label>`).join(""); } m.style.display="flex"; } function closeAssetGroups(){ const m=document.getElementById("assetGroupsModal"); if(m) m.style.display="none"; } function saveAssetGroups(){ if(!agAsset) return; const ids=Array.from(document.querySelectorAll("#agList input[type=checkbox]:checked")).map(c=>parseInt(c.value)); fetch(`/api/assets/${encodeURIComponent(agAsset)}/groups`,{method:"POST",headers:{"Content-Type":"application/json"}, body:JSON.stringify({group_ids:ids})}).then(r=>r.json()).then(d=>{ const msg=document.getElementById("assetGroupsMsg"); if(!d.ok){ if(msg){ msg.textContent=d.error||"failed"; msg.style.color="var(--danger)"; } return; } const host=(currentHosts||[]).find(h=>h.asset_id===agAsset); if(host) host.groups=d.groups||[]; closeAssetGroups(); renderSorted(); }).catch(e=>{ const msg=document.getElementById("assetGroupsMsg"); if(msg) msg.textContent=e.message; }); } // =========================================================================== // v12: Remediation Tracking (tenant-separated) // =========================================================================== function remMsg(t,err){ const el=document.getElementById("remediationMsg"); if(el){ el.textContent=t||""; el.style.color=err?"var(--danger)":"var(--muted)"; } } function populateRemAssets(){ const sel=document.getElementById("rem-asset"); if(!sel) return; const cur=sel.value; const opts=(currentHosts||[]).filter(h=>h.asset_id).map(h=> `<option value="${esc(h.asset_id)}">${esc(h.asset_id)} \u2014 ${esc(h.ip)}${(h.hostname&&h.hostname!=='-')?(" ("+esc(h.hostname)+")"):""}</option>`).join(""); sel.innerHTML = opts || '<option value="">(run a scan to list assets)</option>'; if(cur) sel.value=cur; } function renderRemediation(){ populateRemAssets(); fetch("/api/remediation").then(r=>r.json()).then(d=>{ if(!d.ok){ remMsg(d.error||"error",true); return; } remItems=d.items||[]; _renderRemTable(); }).catch(e=>remMsg(e.message,true)); } function _renderRemTable(){ const body=document.getElementById("remediationBody"); if(!body) return; const q=((document.getElementById("remFilter")||{}).value||"").toLowerCase(); const sf=(document.getElementById("remStatusFilter")||{}).value||""; const items=remItems.filter(it=>{ if(sf && it.status!==sf) return false; if(!q) return true; return (it.asset_id+" "+(it.ip||"")+" "+(it.title||"")+" "+(it.status||"")+" "+(it.assignee||"")+" "+(it.priority||"")).toLowerCase().includes(q); }); const cnt=document.getElementById("remCount"); if(cnt) cnt.textContent=`${items.length} item(s)`; const canEdit = window.NETSCAN_CAN_SCAN!==false; const cols = canEdit ? 11 : 10; if(!items.length){ body.innerHTML=`<tr><td colspan="${cols}" class="muted">No remediation items.</td></tr>`; remUpdateBulkBtn(); return; } const STATES=[["open","Open"],["in_progress","In progress"],["blocked","Blocked"],["resolved","Resolved"]]; const PRIOS=[["low","Low"],["medium","Medium"],["high","High"],["critical","Critical"]]; body.innerHTML=items.map(it=>{ const due=it.due_date?esc(it.due_date):'<span class="muted">\u2014</span>'; const upd=it.updated_at?new Date(it.updated_at*1000).toLocaleDateString():""; const statusCell=canEdit ? `<select class="rem-status st-${esc(it.status)}" onchange="updateRemediation(${it.id},'status',this.value)">`+ STATES.map(s=>`<option value="${s[0]}" ${it.status===s[0]?"selected":""}>${s[1]}</option>`).join("")+`</select>` : `<span class="badge rem-${esc(it.status)}">${esc(it.status)}</span>`; const prioCell=canEdit ? `<select class="rem-prio pr-${esc(it.priority)}" onchange="updateRemediation(${it.id},'priority',this.value)">`+ PRIOS.map(p=>`<option value="${p[0]}" ${it.priority===p[0]?"selected":""}>${p[1]}</option>`).join("")+`</select>` : `<span class="pr-${esc(it.priority)}">${esc(it.priority)}</span>`; const del=canEdit?`<button class="ghost danger-x" title="Delete" onclick="deleteRemediation(${it.id})">\u2715</button>`:""; const cortexBtn=canEdit?`<button class="ghost" title="Send this item to Synapse Cortex as a ticket" onclick="sendCortexTicket(event,${it.id})">\ud83e\udde0 Cortex Ticket</button>`:""; const ipCell=it.ip?`<code>${esc(it.ip)}</code>`:'<span class="muted">\u2014</span>'; const sel=canEdit?`<td><input type="checkbox" class="rem-check" value="${it.id}" onclick="remUpdateBulkBtn()"></td>`:""; const cc=Number(it.comment_count||0); const cmtCell=`<button class="ghost" id="rem-cmt-btn-${it.id}" title="Show/hide comments" onclick="toggleRemComments(${it.id})">\uD83D\uDCAC ${cc}</button>`; return `<tr data-rem="${it.id}">`+ sel+ `<td><code class="asset-id">${esc(it.asset_id)}</code></td>`+ `<td>${ipCell}</td>`+ `<td>${esc(it.title)}${it.cve?` <span class="muted">(${esc(it.cve)})</span>`:""}${it.detail?`<div class="muted" style="font-size:11px">${esc(it.detail)}</div>`:""}</td>`+ `<td>${prioCell}</td>`+ `<td>${statusCell}</td>`+ `<td>${it.assignee?esc(it.assignee):'<span class="muted">\u2014</span>'}</td>`+ `<td>${due}</td>`+ `<td>${cmtCell}</td>`+ `<td class="muted">${esc(upd)}</td>`+ `<td class="rem-actions" style="white-space:nowrap">${cortexBtn}${del}</td>`+ `</tr>`+ `<tr class="rem-comments-row" id="rem-comments-${it.id}" style="display:none"><td colspan="${cols}"><div class="rem-comments" id="rem-comments-box-${it.id}"></div></td></tr>`; }).join(""); remUpdateBulkBtn(); } // --- v13: multi-select bulk delete --- function _remChecks(){ return Array.prototype.slice.call(document.querySelectorAll(".rem-check")); } function remToggleAll(box){ _remChecks().forEach(c=>{ c.checked=box.checked; }); remUpdateBulkBtn(); } function remUpdateBulkBtn(){ const checks=_remChecks(); const sel=checks.filter(c=>c.checked).length; const btn=document.getElementById("remBulkDel"); if(btn){ btn.disabled=(sel===0); btn.textContent=sel?`\uD83D\uDDD1 Delete selected (${sel})`:"\uD83D\uDDD1 Delete selected"; } const all=document.getElementById("remSelectAll"); if(all){ all.checked=(checks.length>0 && sel===checks.length); all.indeterminate=(sel>0 && sel<checks.length); } } function bulkDeleteRemediation(){ const ids=_remChecks().filter(c=>c.checked).map(c=>parseInt(c.value,10)); if(!ids.length) return; if(!confirm(`Delete ${ids.length} remediation item(s)? This also removes their comments and cannot be undone.`)) return; fetch("/api/remediation/bulk-delete",{method:"POST",headers:{"Content-Type":"application/json"}, body:JSON.stringify({ids})}).then(r=>r.json()).then(d=>{ if(d.ok){ remMsg(`Deleted ${d.removed} item(s).`); renderRemediation(); } else remMsg(d.error||"failed",true); }).catch(e=>remMsg(e.message,true)); } // --- v13: per-item comment thread --- function toggleRemComments(id){ const row=document.getElementById("rem-comments-"+id); if(!row) return; const open=row.style.display!=="none"; if(open){ row.style.display="none"; return; } row.style.display=""; loadRemComments(id); } function loadRemComments(id){ const box=document.getElementById("rem-comments-box-"+id); if(!box) return; box.innerHTML='<span class="muted">Loading\u2026</span>'; fetch(`/api/remediation/${id}/comments`).then(r=>r.json()).then(d=>{ if(!d.ok){ box.innerHTML=`<span style="color:var(--danger)">${esc(d.error||"error")}</span>`; return; } renderRemComments(id, d.comments||[]); }).catch(e=>{ box.innerHTML=`<span style="color:var(--danger)">${esc(e.message)}</span>`; }); } function renderRemComments(id, comments){ const box=document.getElementById("rem-comments-box-"+id); if(!box) return; const canEdit = window.NETSCAN_CAN_SCAN!==false; const list = comments.length ? comments.map(c=>{ const when=c.created_at?new Date(c.created_at*1000).toLocaleString():""; const del=canEdit?` <a class="ghost danger-x" title="Delete comment" onclick="deleteRemComment(${c.id},${id})">\u2715</a>`:""; return `<div class="rem-comment" style="padding:4px 0;border-top:1px solid var(--border)">`+ `<div style="white-space:pre-wrap">${esc(c.body)}</div>`+ `<div class="muted" style="font-size:11px">${esc(c.author||"unknown")} \u00b7 ${esc(when)}${del}</div>`+ `</div>`; }).join("") : '<div class="muted" style="font-size:12px">No comments yet.</div>'; const adder = canEdit ? `<div style="display:flex;gap:6px;margin-top:8px">`+ `<input type="text" id="rem-cmt-input-${id}" placeholder="Add a comment\u2026" style="flex:1 1 auto" onkeydown="if(event.key==='Enter')addRemComment(${id})">`+ `<button onclick="addRemComment(${id})">Comment</button></div>` : ""; box.innerHTML=`<div style="font-size:13px">${list}</div>${adder}`; const badge=document.getElementById("rem-cmt-btn-"+id); if(badge) badge.textContent="\uD83D\uDCAC "+comments.length; } function addRemComment(id){ const inp=document.getElementById("rem-cmt-input-"+id); if(!inp) return; const body=(inp.value||"").trim(); if(!body) return; fetch(`/api/remediation/${id}/comments`,{method:"POST",headers:{"Content-Type":"application/json"}, body:JSON.stringify({body})}).then(r=>r.json()).then(d=>{ if(!d.ok){ remMsg(d.error||"failed",true); return; } inp.value=""; loadRemComments(id); // reloads thread + updates the count badge }).catch(e=>remMsg(e.message,true)); } function deleteRemComment(cid, id){ if(!confirm("Delete this comment?")) return; fetch(`/api/remediation/comments/${cid}`,{method:"DELETE"}).then(r=>r.json()).then(d=>{ if(!d.ok){ remMsg(d.error||"failed",true); return; } loadRemComments(id); // reloads thread + updates the count badge }).catch(e=>remMsg(e.message,true)); } function addRemediation(){ const asset_id=(document.getElementById("rem-asset")||{}).value||""; const title=((document.getElementById("rem-title")||{}).value||"").trim(); if(!asset_id){ remMsg("Select an asset.",true); return; } if(!title){ remMsg("Enter a remediation task.",true); return; } const payload={asset_id,title, priority:(document.getElementById("rem-priority")||{}).value||"medium", assignee:((document.getElementById("rem-assignee")||{}).value||"").trim(), due_date:(document.getElementById("rem-due")||{}).value||""}; fetch("/api/remediation",{method:"POST",headers:{"Content-Type":"application/json"}, body:JSON.stringify(payload)}).then(r=>r.json()).then(d=>{ if(d.ok){ remMsg("Remediation item added."); ["rem-title","rem-assignee","rem-due"].forEach(id=>{ const e=document.getElementById(id); if(e) e.value=""; }); renderRemediation(); } else remMsg(d.error||"failed",true); }).catch(e=>remMsg(e.message,true)); } function updateRemediation(id,field,value){ const body={}; body[field]=value; fetch(`/api/remediation/${id}`,{method:"PATCH",headers:{"Content-Type":"application/json"}, body:JSON.stringify(body)}).then(r=>r.json()).then(d=>{ if(!d.ok) remMsg(d.error||"failed",true); renderRemediation(); }).catch(e=>remMsg(e.message,true)); } function deleteRemediation(id){ if(!confirm("Delete this remediation item?")) return; fetch(`/api/remediation/${id}`,{method:"DELETE"}).then(r=>r.json()).then(d=>{ if(d.ok) renderRemediation(); else remMsg(d.error||"failed",true); }).catch(e=>remMsg(e.message,true)); } // =========================================================================== // v13: Patch and Remedy (More tab) - OS-level updates/upgrades over SSH, plus // optional Docker image updates. Credentials are entered per run and POSTed // once; they are never stored. // =========================================================================== function _dockerHosts(){ return (currentHosts||[]).filter(h=>h.asset_id && h.docker && h.docker.is_docker); } function _allAssets(){ return (currentHosts||[]).filter(h=>h.asset_id); } function _patchType(){ return (document.getElementById("patch-type")||{}).value||"os"; } function renderPatch(){ // Populate the asset dropdown. OS patching targets ANY scanned asset; Docker // patching targets Docker hosts. (Fixes the asset list not pulling through.) const aSel=document.getElementById("patch-asset"); if(aSel){ const list = (_patchType()==="docker") ? _dockerHosts() : _allAssets(); const label = (_patchType()==="docker") ? "no Docker assets in the latest scan" : "run a scan to list assets"; aSel.innerHTML = list.length ? list.map(h=>`<option value="${esc(h.asset_id)}">${esc(h.asset_id)} \u2014 ${esc(h.ip)}${(h.hostname&&h.hostname!=='-')?(" ("+esc(h.hostname)+")"):""}${(h.os&&h.os!=='unknown')?(" \u00b7 "+esc(h.os)):""}</option>`).join("") : `<option value="">(${label})</option>`; } const gSel=document.getElementById("patch-group"); if(gSel){ gSel.innerHTML = (currentGroups||[]).length ? (currentGroups||[]).map(g=>`<option value="${g.id}">${esc(g.name)}</option>`).join("") : '<option value="">(no groups)</option>'; } onPatchModeChange(); } function onPatchTypeChange(){ const t=_patchType(); const os=document.getElementById("patch-os-creds"), dk=document.getElementById("patch-docker-creds"); if(os) os.style.display=(t==="os")?"":"none"; if(dk) dk.style.display=(t==="docker")?"":"none"; renderPatch(); // re-list assets for the chosen type } function onPatchModeChange(){ const m=(document.getElementById("patch-mode")||{}).value||"asset"; const a=document.getElementById("patch-asset"), g=document.getElementById("patch-group"); if(a) a.style.display=(m==="asset")?"":"none"; if(g) g.style.display=(m==="group")?"":"none"; } function _patchBody(){ const mode=(document.getElementById("patch-mode")||{}).value||"asset"; const body={mode}; if(mode==="asset") body.asset_id=(document.getElementById("patch-asset")||{}).value||""; if(mode==="group") body.group_id=parseInt((document.getElementById("patch-group")||{}).value||"0",10); return body; } function _patchMsg(html){ const el=document.getElementById("patchResult"); if(el) el.innerHTML=html; } // --- Dispatchers (choose OS or Docker by the patch-type select) --- function patchPreview(){ return (_patchType()==="docker") ? planDockerPatch() : planOsPatch(); } function patchRun(){ return (_patchType()==="docker") ? runDockerPatch() : runOsPatch(); } // --- OS (SSH) patching --- function planOsPatch(){ const body=_patchBody(); _patchMsg('<span class="muted">Building preview\u2026</span>'); fetch("/api/patch/os/plan",{method:"POST",headers:{"Content-Type":"application/json"}, body:JSON.stringify(body)}).then(r=>r.json()).then(d=>{ if(!d.ok){ _patchMsg(`<span style="color:var(--danger)">${esc(d.error||"failed")}</span>`); return; } if(!d.plan.length){ _patchMsg('<span class="muted">No matching assets.</span>'); return; } const warn = d.ssh_available ? "" : '<p style="color:var(--warn);font-size:12px">\u26a0\ufe0f SSH support (paramiko) is not installed on the NetscanXi host \u2014 OS patching will report an error until it is added.</p>'; const rows=d.plan.map(p=>`<tr><td><code class="asset-id">${esc(p.asset_id||"")}</code></td><td>${esc(p.ip||"")}</td>`+ `<td>${esc(p.hostname||"")}</td><td>${esc(p.os||"unknown")}</td>`+ `<td class="muted">${esc(p.pkg_hint||"detect on connect")}</td></tr>`).join(""); _patchMsg(warn+`<p class="muted" style="font-size:12px">Dry run \u2014 ${d.target_count} asset(s). Nothing was changed; SSH is not contacted in preview.</p>`+ `<table><thead><tr><th>Asset ID</th><th>IP</th><th>Host</th><th>Detected OS</th><th>Package manager</th></tr></thead><tbody>${rows}</tbody></table>`); }).catch(e=>_patchMsg(`<span style="color:var(--danger)">${esc(e.message)}</span>`)); } function runOsPatch(){ const body=_patchBody(); if(body.mode==="asset" && !body.asset_id){ _patchMsg('<span style="color:var(--danger)">Select an asset.</span>'); return; } const userEl=document.getElementById("patch-ssh-user"), passEl=document.getElementById("patch-ssh-pass"), sudoEl=document.getElementById("patch-sudo-pass"); const user=((userEl||{}).value||"").trim(); if(!user){ _patchMsg('<span style="color:var(--danger)">Enter an SSH username.</span>'); return; } body.ssh={ username:user, password:(passEl||{}).value||"", port:parseInt((document.getElementById("patch-ssh-port")||{}).value||"22",10)||22, sudo_password:(sudoEl||{}).value||"" }; body.dist_upgrade=!!(document.getElementById("patch-distupgrade")||{}).checked; body.simulate=!!(document.getElementById("patch-simulate")||{}).checked; const verb=body.simulate?"Simulate OS updates":(body.dist_upgrade?"Apply a full distribution upgrade":"Apply OS updates & upgrades"); if(!confirm(verb+" on the targeted asset(s) over SSH now?")) return; _patchMsg('<span class="muted">Connecting over SSH and patching\u2026 this can take several minutes.</span>'); fetch("/api/patch/os",{method:"POST",headers:{"Content-Type":"application/json"}, body:JSON.stringify(body)}).then(r=>r.json()).then(d=>{ // Scrub password fields as soon as the request is away. if(passEl) passEl.value=""; if(sudoEl) sudoEl.value=""; if(!d.ok){ _patchMsg(`<span style="color:var(--danger)">${esc(d.error||"failed")}</span>`); return; } const rows=(d.results||[]).map(r=>{ const ok=r.ok; const log=esc((r.log||"").slice(-1200)).replace(/\n/g,"<br>"); return `<tr><td><code class="asset-id">${esc(r.asset_id||"")}</code></td><td>${esc(r.ip||"")}</td>`+ `<td>${ok?'<span class="badge rem-resolved">resolved</span>':'<span class="badge rem-blocked">blocked</span>'}</td>`+ `<td>${esc(r.manager||"")}${typeof r.updated_count==='number'?` \u00b7 ${r.updated_count} pkg(s)`:""}${r.error?(' \u2014 <span style="color:var(--danger)">'+esc(r.error)+'</span>'):""}`+ `${log?`<details><summary class="muted" style="cursor:pointer">log</summary><pre style="white-space:pre-wrap;font-size:11px">${log}</pre></details>`:""}</td>`+ `<td class="muted">#${r.remediation_id||""}</td></tr>`; }).join(""); _patchMsg(`<p style="font-size:12px">${d.ok_hosts}/${d.target_count} asset(s) patched OK${d.simulated?" (simulated)":""}. `+ `Remediation items were created/updated \u2014 <a class="ghost" onclick="switchTab('remediation')">open the tracker</a>.</p>`+ `<table><thead><tr><th>Asset ID</th><th>IP</th><th>Result</th><th>Detail</th><th>Rem.</th></tr></thead><tbody>${rows}</tbody></table>`); renderRemediation(); }).catch(e=>{ if(passEl) passEl.value=""; if(sudoEl) sudoEl.value=""; _patchMsg(`<span style="color:var(--danger)">${esc(e.message)}</span>`); }); } // --- Docker image patching --- function planDockerPatch(){ const body=_patchBody(); _patchMsg('<span class="muted">Building preview\u2026</span>'); fetch("/api/patch/docker/plan",{method:"POST",headers:{"Content-Type":"application/json"}, body:JSON.stringify(body)}).then(r=>r.json()).then(d=>{ if(!d.ok){ _patchMsg(`<span style="color:var(--danger)">${esc(d.error||"failed")}</span>`); return; } if(!d.plan.length){ _patchMsg('<span class="muted">No matching Docker assets.</span>'); return; } const rows=d.plan.map(p=>`<tr><td><code class="asset-id">${esc(p.asset_id||"")}</code></td><td>${esc(p.ip||"")}</td>`+ `<td>${p.container_count}</td><td>${(p.images||[]).map(esc).join("<br>")||'<span class="muted">\u2014</span>'}</td>`+ `<td class="muted">${p.endpoint?esc(p.endpoint):'<span style="color:var(--danger)">unreachable</span>'}</td></tr>`).join(""); _patchMsg(`<p class="muted" style="font-size:12px">Dry run \u2014 ${d.target_count} asset(s). Nothing was changed.</p>`+ `<table><thead><tr><th>Asset ID</th><th>IP</th><th>Running</th><th>Images to update</th><th>Endpoint</th></tr></thead><tbody>${rows}</tbody></table>`); }).catch(e=>_patchMsg(`<span style="color:var(--danger)">${esc(e.message)}</span>`)); } function runDockerPatch(){ const body=_patchBody(); if(body.mode==="asset" && !body.asset_id){ _patchMsg('<span style="color:var(--danger)">Select an asset.</span>'); return; } const passEl=document.getElementById("patch-reg-pass"); body.registry={ username:((document.getElementById("patch-reg-user")||{}).value||"").trim(), password:(passEl||{}).value||"", server:((document.getElementById("patch-reg-server")||{}).value||"").trim() }; body.recreate=!!(document.getElementById("patch-recreate")||{}).checked; if(!confirm("Run Docker image patch now? This pulls updated images on the targeted asset(s)"+(body.recreate?" and recreates their containers.":"."))) return; _patchMsg('<span class="muted">Patching\u2026 this can take a while for large images.</span>'); fetch("/api/patch/docker",{method:"POST",headers:{"Content-Type":"application/json"}, body:JSON.stringify(body)}).then(r=>r.json()).then(d=>{ // Scrub the password field as soon as the request is away. if(passEl) passEl.value=""; if(!d.ok){ _patchMsg(`<span style="color:var(--danger)">${esc(d.error||"failed")}</span>`); return; } const rows=(d.results||[]).map(r=>{ const ok=r.ok; const pulls=(r.pulled||[]).map(p=>`${p.ok?"\u2705":"\u274c"} ${esc(p.image)}${p.ok?"":(" \u2014 "+esc(p.error||""))}`).join("<br>")||'<span class="muted">\u2014</span>'; const recs=(r.recreated||[]).map(c=>`${c.ok?"\u2705":"\u274c"} ${esc(c.container)}${c.ok?"":(" \u2014 "+esc(c.error||""))}`).join("<br>"); return `<tr><td><code class="asset-id">${esc(r.asset_id||"")}</code></td><td>${esc(r.ip||"")}</td>`+ `<td>${ok?'<span class="badge rem-resolved">resolved</span>':'<span class="badge rem-blocked">blocked</span>'}</td>`+ `<td>${pulls}${recs?("<hr style='border-color:var(--border)'>"+recs):""}</td>`+ `<td class="muted">#${r.remediation_id||""}</td></tr>`; }).join(""); _patchMsg(`<p style="font-size:12px">${d.ok_hosts}/${d.target_count} asset(s) patched OK. `+ `Remediation items were created/updated \u2014 <a class="ghost" onclick="switchTab('remediation')">open the tracker</a>.</p>`+ `<table><thead><tr><th>Asset ID</th><th>IP</th><th>Result</th><th>Detail</th><th>Rem.</th></tr></thead><tbody>${rows}</tbody></table>`); renderRemediation(); }).catch(e=>{ if(passEl) passEl.value=""; _patchMsg(`<span style="color:var(--danger)">${esc(e.message)}</span>`); }); } |