app.js 142 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398
  1. // Proxmox RouterOS Frontend Application Logic
  2. let state = {
  3. interfaces: [],
  4. vlans: [],
  5. systemStatus: null,
  6. vpnStatus: null,
  7. routes: [],
  8. activeTab: 'dashboard',
  9. ifaceFilter: 'all',
  10. currentModalIface: null,
  11. isPolling: true,
  12. expandedParents: new Set(['eth0']),
  13. pppoeData: null,
  14. wgData: null,
  15. ipsecData: null,
  16. l2tpData: null,
  17. pptpData: null
  18. };
  19. const API_BASE = '/api';
  20. // Initialize on page load
  21. document.addEventListener('DOMContentLoaded', () => {
  22. const hash = window.location.hash.replace('#', '') || 'dashboard';
  23. navigate(hash);
  24. fetchData();
  25. // Live polling every 2.5 seconds
  26. setInterval(() => {
  27. if (state.isPolling) {
  28. fetchData(false);
  29. }
  30. }, 2500);
  31. });
  32. // Navigation Handler
  33. function navigate(tabName) {
  34. state.activeTab = tabName;
  35. window.location.hash = tabName;
  36. // Update nav links styling
  37. document.querySelectorAll('.nav-link').forEach(link => {
  38. link.className = 'nav-link flex items-center justify-between px-3 py-2 rounded-lg text-xs font-medium transition-all group text-slate-300 hover:bg-slate-800/80 hover:text-white';
  39. });
  40. const activeNav = document.getElementById(`nav-${tabName}`);
  41. if (activeNav) {
  42. activeNav.className = 'nav-link flex items-center justify-between px-3 py-2 rounded-lg text-xs font-medium transition-all group bg-brand-500/10 text-brand-400 border border-brand-500/20';
  43. }
  44. // Update page headers
  45. const titles = {
  46. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  47. interfaces: { title: 'Network Interfaces', sub: 'Hierarchical view of physical interfaces and nested 802.1Q VLANs' },
  48. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  49. routes: { title: 'Kernel Routing Table', sub: 'Active IPv4 / IPv6 Linux kernel routes and gateways' },
  50. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  51. wireguard: { title: 'WireGuard Kernel VPN', sub: 'Modern ultra-fast cryptographic VPN tunnel manager' },
  52. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  53. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  54. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  55. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' }
  56. };
  57. const header = titles[tabName] || titles.dashboard;
  58. document.getElementById('page-title').innerText = header.title;
  59. document.getElementById('page-subtitle').innerText = header.sub;
  60. // Toggle sections
  61. ['dashboard', 'interfaces', 'vlans', 'routes', 'pppoe', 'wireguard', 'ipsec', 'l2tp', 'pptp', 'persistence'].forEach(sec => {
  62. const el = document.getElementById(`section-${sec}`);
  63. if (el) {
  64. if (sec === tabName) {
  65. el.classList.remove('hidden');
  66. } else {
  67. el.classList.add('hidden');
  68. }
  69. }
  70. });
  71. if (tabName === 'firewall') loadFirewall();
  72. if (tabName === 'routes') loadRoutes();
  73. if (tabName === 'persistence') loadDebianConfig();
  74. if (tabName === 'pppoe') loadPPPoE();
  75. if (tabName === 'wireguard') loadWireGuard();
  76. if (tabName === 'ipsec') loadIPSec();
  77. if (tabName === 'l2tp') loadL2TP();
  78. if (tabName === 'pptp') loadPPTP();
  79. }
  80. // Fetch all core system, network and VPN telemetry
  81. async function fetchData(isManual = false) {
  82. const spinner = document.getElementById('refresh-spinner');
  83. if (isManual && spinner) spinner.classList.add('animate-spin');
  84. try {
  85. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes] = await Promise.all([
  86. fetch(`${API_BASE}/system/status`),
  87. fetch(`${API_BASE}/interfaces`),
  88. fetch(`${API_BASE}/vlans`),
  89. fetch(`${API_BASE}/vpn/status`),
  90. fetch(`${API_BASE}/firewall/summary`)
  91. ]);
  92. if (statusRes.ok) state.systemStatus = await statusRes.json();
  93. if (ifacesRes.ok) {
  94. const ifacesData = await ifacesRes.json();
  95. state.interfaces = Array.isArray(ifacesData) ? ifacesData : [];
  96. }
  97. if (vlansRes.ok) {
  98. const vlansData = await vlansRes.json();
  99. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  100. }
  101. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  102. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  103. updateSystemMetrics();
  104. updateBadges();
  105. if (state.activeTab === 'dashboard') renderDashboard();
  106. if (state.activeTab === 'interfaces') renderInterfacesList();
  107. if (state.activeTab === 'vlans') renderVlansList();
  108. if (state.activeTab === 'firewall') loadFirewall(false);
  109. if (state.activeTab === 'routes') loadRoutes(false);
  110. if (state.activeTab === 'pppoe') loadPPPoE(false);
  111. if (state.activeTab === 'wireguard') loadWireGuard(false);
  112. if (state.activeTab === 'ipsec') loadIPSec(false);
  113. if (state.activeTab === 'l2tp') loadL2TP(false);
  114. if (state.activeTab === 'pptp') loadPPTP(false);
  115. } catch (err) {
  116. console.error('Failed to fetch router state:', err);
  117. } finally {
  118. if (isManual && spinner) {
  119. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  120. }
  121. }
  122. }
  123. // Update Top KPI and Sidebar Telemetry
  124. function updateSystemMetrics() {
  125. const s = state.systemStatus;
  126. const v = state.vpnStatus;
  127. if (!s) return;
  128. // Sidebar
  129. document.getElementById('side-hostname').innerText = s.hostname || 'debian-lxc';
  130. document.getElementById('side-uptime').innerText = s.uptime_human || '0m';
  131. document.getElementById('side-gateway-ip').innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  132. if (s.cpu_load && s.cpu_load.length > 0) {
  133. document.getElementById('side-cpu-val').innerText = s.cpu_load[0];
  134. const cpuPct = Math.min(100, Math.round(parseFloat(s.cpu_load[0]) * 50));
  135. document.getElementById('side-cpu-bar').style.width = `${Math.max(5, cpuPct)}%`;
  136. }
  137. document.getElementById('side-ram-val').innerText = `${Math.round(s.mem_usage_pct || 0)}%`;
  138. document.getElementById('side-ram-bar').style.width = `${Math.max(5, Math.round(s.mem_usage_pct || 0))}%`;
  139. // Dashboard Stats
  140. document.getElementById('stat-ifaces-up').innerText = s.up_ifaces || 0;
  141. document.getElementById('stat-ifaces-total').innerText = `${s.total_ifaces || 0} Total`;
  142. document.getElementById('stat-ifaces-down').innerText = `${s.down_ifaces || 0} DOWN`;
  143. document.getElementById('stat-vlans-count').innerText = s.vlan_ifaces || 0;
  144. // VPN Status Indicators
  145. if (v) {
  146. const totalActive = v.total_active_tunnels || 0;
  147. const statVpnActive = document.getElementById('stat-vpn-active');
  148. if (statVpnActive) statVpnActive.innerText = totalActive;
  149. const tunnelsDot = document.getElementById('tunnels-dot');
  150. const tunnelsLabel = document.getElementById('tunnels-label');
  151. if (tunnelsDot && tunnelsLabel) {
  152. if (totalActive > 0) {
  153. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  154. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  155. } else {
  156. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  157. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  158. }
  159. }
  160. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  161. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  162. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  163. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  164. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  165. }
  166. // Total Live Bandwidth Rate
  167. let totalRx = 0;
  168. let totalTx = 0;
  169. (state.interfaces || []).forEach(i => {
  170. if (i.rate) {
  171. totalRx += i.rate.rx_bytes_sec || 0;
  172. totalTx += i.rate.tx_bytes_sec || 0;
  173. }
  174. });
  175. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  176. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  177. }
  178. function setDotBadge(id, active) {
  179. const el = document.getElementById(id);
  180. if (!el) return;
  181. if (active) {
  182. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  183. } else {
  184. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  185. }
  186. }
  187. function updateBadges() {
  188. document.getElementById('badge-ifaces-count').innerText = (state.interfaces || []).length;
  189. document.getElementById('badge-vlans-count').innerText = (state.vlans || []).length;
  190. if (state.fwSummary) {
  191. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  192. const badgeFw = document.getElementById('badge-firewall-count');
  193. if (badgeFw) badgeFw.innerText = totalFwRules;
  194. }
  195. }
  196. // Render Dashboard View
  197. function renderDashboard() {
  198. const matrix = document.getElementById('port-matrix');
  199. matrix.innerHTML = '';
  200. (state.interfaces || []).forEach(iface => {
  201. const isUp = iface.state === 'UP';
  202. const isVlan = iface.is_vlan;
  203. const portCard = document.createElement('div');
  204. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  205. isUp
  206. ? (isVlan ? 'bg-cyan-950/20 border-cyan-800/60 hover:border-cyan-500' : 'bg-slate-800/80 border-slate-700/80 hover:border-brand-500')
  207. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  208. }`;
  209. portCard.onclick = () => openIfaceModal(iface.name);
  210. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  211. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  212. portCard.innerHTML = `
  213. <div class="flex items-center justify-between mb-2">
  214. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  215. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  216. </div>
  217. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  218. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  219. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  220. <span>${iface.rate?.rx_human || '0 B/s'}</span>
  221. </div>
  222. `;
  223. matrix.appendChild(portCard);
  224. });
  225. const ifaceTbody = document.getElementById('quick-interfaces-table');
  226. ifaceTbody.innerHTML = '';
  227. (state.interfaces || []).slice(0, 6).forEach(i => {
  228. const isUp = i.state === 'UP';
  229. const tr = document.createElement('tr');
  230. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  231. tr.onclick = () => openIfaceModal(i.name);
  232. tr.innerHTML = `
  233. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  234. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  235. <span>${i.name}</span>
  236. </td>
  237. <td class="py-2.5 text-slate-300 font-sans"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300">${i.role || 'LAN'}</span></td>
  238. <td class="py-2.5 text-slate-300">${i.ipv4 && i.ipv4.length > 0 ? i.ipv4[0] : '<span class="text-slate-600">-</span>'}</td>
  239. <td class="py-2.5 text-right font-sans font-semibold ${isUp ? 'text-emerald-400' : 'text-rose-400'}">${i.state}</td>
  240. `;
  241. ifaceTbody.appendChild(tr);
  242. });
  243. const vlanTbody = document.getElementById('quick-vlans-table');
  244. vlanTbody.innerHTML = '';
  245. const vlans = state.vlans || [];
  246. if (vlans.length === 0) {
  247. vlanTbody.innerHTML = `<tr><td colspan="4" class="py-4 text-center text-slate-500 font-sans">No VLANs configured. Click "+ Add" above to create one.</td></tr>`;
  248. } else {
  249. vlans.slice(0, 6).forEach(v => {
  250. const tr = document.createElement('tr');
  251. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  252. tr.onclick = () => openIfaceModal(v.name);
  253. tr.innerHTML = `
  254. <td class="py-2.5"><span class="px-2 py-0.5 rounded text-[11px] bg-cyan-950 text-cyan-400 border border-cyan-800 font-bold">VLAN ${v.vlan_id}</span></td>
  255. <td class="py-2.5 text-white font-bold">${v.name}</td>
  256. <td class="py-2.5 text-slate-300">${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600">Unnumbered</span>'}</td>
  257. <td class="py-2.5 text-right text-slate-400">${v.parent_name || 'eth0'}</td>
  258. `;
  259. vlanTbody.appendChild(tr);
  260. });
  261. }
  262. }
  263. // Expand / Collapse Handlers
  264. function toggleExpand(parentName) {
  265. if (state.expandedParents.has(parentName)) {
  266. state.expandedParents.delete(parentName);
  267. } else {
  268. state.expandedParents.add(parentName);
  269. }
  270. renderInterfacesList();
  271. }
  272. function expandAllIfaces(expand) {
  273. if (expand) {
  274. (state.interfaces || []).forEach(i => {
  275. if (!i.is_vlan) state.expandedParents.add(i.name);
  276. });
  277. } else {
  278. state.expandedParents.clear();
  279. }
  280. renderInterfacesList();
  281. }
  282. // Filter and Render Hierarchical Interfaces List
  283. function filterIfaces(filter) {
  284. state.ifaceFilter = filter;
  285. document.querySelectorAll('.filter-btn').forEach(btn => {
  286. btn.className = 'filter-btn px-3 py-1.5 rounded-lg text-xs font-medium text-slate-400 hover:bg-slate-800 hover:text-white';
  287. });
  288. const activeBtn = document.getElementById(`filter-${filter}`);
  289. if (activeBtn) {
  290. activeBtn.className = 'filter-btn px-3 py-1.5 rounded-lg text-xs font-medium bg-slate-800 text-white border border-slate-700';
  291. }
  292. renderInterfacesList();
  293. }
  294. function renderInterfacesList() {
  295. const tbody = document.getElementById('interfaces-tree-tbody');
  296. const emptyState = document.getElementById('interfaces-empty-state');
  297. const summary = document.getElementById('ifaces-list-summary');
  298. const query = (document.getElementById('iface-search')?.value || '').toLowerCase();
  299. tbody.innerHTML = '';
  300. const allIfaces = state.interfaces || [];
  301. const allVlans = state.vlans || [];
  302. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  303. const filteredParents = parentIfaces.filter(parent => {
  304. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  305. if (query) {
  306. const matchParent = parent.name.toLowerCase().includes(query) || (parent.role || '').toLowerCase().includes(query);
  307. const matchVlan = childVlans.some(v => v.name.toLowerCase().includes(query) || String(v.vlan_id).includes(query) || (v.description || '').toLowerCase().includes(query));
  308. if (!matchParent && !matchVlan) return false;
  309. }
  310. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  311. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  312. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  313. return true;
  314. });
  315. if (summary) {
  316. summary.innerText = `${parentIfaces.length} Physical/Parent Links • ${allVlans.length} Active VLANs`;
  317. }
  318. if (filteredParents.length === 0) {
  319. emptyState?.classList.remove('hidden');
  320. return;
  321. }
  322. emptyState?.classList.add('hidden');
  323. filteredParents.forEach(parent => {
  324. const isUp = parent.state === 'UP';
  325. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  326. const isExpanded = state.expandedParents.has(parent.name);
  327. const parentRow = document.createElement('tr');
  328. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  329. parentRow.innerHTML = `
  330. <td class="py-3 px-3 text-center">
  331. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  332. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  333. <svg class="w-4 h-4 chevron-icon ${isExpanded ? 'chevron-open text-cyan-400' : 'text-slate-500'}" fill="none" stroke="currentColor" viewBox="0 0 24 24">
  334. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  335. </svg>
  336. </button>
  337. </td>
  338. <td class="py-3 px-4">
  339. <div class="flex items-center space-x-2.5">
  340. <div class="w-7 h-7 rounded-lg bg-slate-800 border border-slate-700/80 flex items-center justify-center text-[10px] font-bold text-slate-300">
  341. ${parent.type === 'loopback' ? 'LO' : 'NIC'}
  342. </div>
  343. <div>
  344. <div class="flex items-center gap-2">
  345. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400" onclick="toggleExpand('${parent.name}')">${parent.name}</span>
  346. ${childVlans.length > 0
  347. ? `<span onclick="toggleExpand('${parent.name}')" class="cursor-pointer text-[10px] bg-cyan-950 text-cyan-400 border border-cyan-800/60 px-2 py-0.5 rounded-full font-bold hover:bg-cyan-900 transition">${childVlans.length} VLAN${childVlans.length > 1 ? 's' : ''}</span>`
  348. : `<span onclick="toggleExpand('${parent.name}')" class="cursor-pointer text-[10px] bg-slate-800/60 text-slate-500 px-1.5 py-0.5 rounded font-mono hover:text-slate-300">0 VLANs</span>`
  349. }
  350. </div>
  351. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  352. </div>
  353. </div>
  354. </td>
  355. <td class="py-3 px-4 font-sans">
  356. <div class="flex items-center gap-1.5">
  357. <span class="px-2 py-0.5 rounded text-[10px] font-semibold bg-slate-800 text-slate-300 border border-slate-700/60">${parent.role || 'LAN'}</span>
  358. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  359. </div>
  360. </td>
  361. <td class="py-3 px-4">
  362. ${parent.ipv4 && parent.ipv4.length > 0
  363. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  364. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  365. }
  366. </td>
  367. <td class="py-3 px-4 text-slate-400 text-[11px]">
  368. <div>${parent.mac || 'N/A'}</div>
  369. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  370. </td>
  371. <td class="py-3 px-4 text-[11px]">
  372. <div class="flex items-center space-x-2">
  373. <span class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  374. <span class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  375. </div>
  376. </td>
  377. <td class="py-3 px-4 font-sans">
  378. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  379. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  380. isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30 hover:bg-rose-500/10 hover:text-rose-400 hover:border-rose-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30 hover:bg-emerald-500/10 hover:text-emerald-400'
  381. }" title="Click to toggle link status">
  382. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  383. <span>${parent.state}</span>
  384. </button>
  385. </td>
  386. <td class="py-3 px-4 text-right space-x-2 font-sans">
  387. <button onclick="openVlanModal('${parent.name}')"
  388. class="text-xs bg-cyan-950/60 hover:bg-cyan-900 text-cyan-300 font-semibold px-2.5 py-1 rounded-lg border border-cyan-800/70 shadow-sm transition">
  389. + Add VLAN
  390. </button>
  391. <button onclick="openIfaceModal('${parent.name}')"
  392. class="text-xs bg-slate-800 hover:bg-slate-700 text-white font-medium px-2.5 py-1 rounded-lg border border-slate-700 transition">
  393. Configure
  394. </button>
  395. </td>
  396. `;
  397. tbody.appendChild(parentRow);
  398. if (isExpanded) {
  399. const drawerRow = document.createElement('tr');
  400. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  401. const drawerCell = document.createElement('td');
  402. drawerCell.colSpan = 8;
  403. drawerCell.className = 'p-0';
  404. drawerCell.innerHTML = `
  405. <div class="py-4 pl-12 pr-6 border-l-4 border-cyan-500 bg-gradient-to-r from-cyan-950/20 via-slate-900/40 to-transparent">
  406. <div class="flex items-center justify-between mb-3">
  407. <div class="flex items-center space-x-3">
  408. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  409. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  410. </span>
  411. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  412. ${childVlans.length} Attached
  413. </span>
  414. </div>
  415. <button onclick="openVlanModal('${parent.name}')"
  416. class="flex items-center space-x-1.5 text-xs bg-cyan-600 hover:bg-cyan-500 text-white font-semibold px-3 py-1.5 rounded-lg shadow-md shadow-cyan-500/20 transition font-sans">
  417. <span>+ Create VLAN on ${parent.name}</span>
  418. </button>
  419. </div>
  420. ${childVlans.length === 0 ? `
  421. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  422. <p class="text-xs text-slate-400 mb-2">No 802.1Q tagged VLANs have been created under <strong class="text-white">${parent.name}</strong> yet.</p>
  423. <button onclick="openVlanModal('${parent.name}')" class="inline-flex items-center space-x-1.5 text-xs text-cyan-400 hover:text-cyan-300 bg-cyan-950/60 border border-cyan-800/70 px-3 py-1.5 rounded-lg transition font-medium">
  424. <span>+ Create Your First VLAN on ${parent.name}</span>
  425. </button>
  426. </div>
  427. ` : `
  428. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  429. <table class="w-full text-left text-xs font-mono">
  430. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  431. <tr>
  432. <th class="py-2.5 px-4">VLAN ID</th>
  433. <th class="py-2.5 px-4">Interface Device</th>
  434. <th class="py-2.5 px-4">Subnet Gateway</th>
  435. <th class="py-2.5 px-4">Role / Alias</th>
  436. <th class="py-2.5 px-4">MTU</th>
  437. <th class="py-2.5 px-4">Throughput</th>
  438. <th class="py-2.5 px-4">Status</th>
  439. <th class="py-2.5 px-4 text-right">Actions</th>
  440. </tr>
  441. </thead>
  442. <tbody class="divide-y divide-slate-800/70">
  443. ${childVlans.map(v => {
  444. const isVlanUp = v.state === 'UP';
  445. return `
  446. <tr class="hover:bg-slate-800/40 transition">
  447. <td class="py-2.5 px-4">
  448. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  449. VLAN ${v.vlan_id}
  450. </span>
  451. </td>
  452. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  453. <span class="text-cyan-500">└─</span>
  454. <span>${v.name}</span>
  455. </td>
  456. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  457. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  458. </td>
  459. <td class="py-2.5 px-4 font-sans text-slate-300">
  460. <span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 mr-1.5">${v.role || 'VLAN'}</span>
  461. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  462. </td>
  463. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  464. <td class="py-2.5 px-4 text-[11px]">
  465. <span class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  466. <span class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  467. </td>
  468. <td class="py-2.5 px-4 font-sans">
  469. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  470. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  471. isVlanUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30'
  472. }">
  473. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  474. <span>${v.state}</span>
  475. </button>
  476. </td>
  477. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  478. <button onclick="openIfaceModal('${v.name}')" class="text-xs bg-slate-800 hover:bg-slate-700 text-slate-200 px-2 py-0.5 rounded border border-slate-700">Edit</button>
  479. <button onclick="confirmDeleteVlan('${v.name}')" class="text-xs text-rose-400 hover:text-rose-300 hover:bg-rose-950/40 px-2 py-0.5 rounded transition">Delete</button>
  480. </td>
  481. </tr>
  482. `;
  483. }).join('')}
  484. </tbody>
  485. </table>
  486. </div>
  487. `}
  488. </div>
  489. `;
  490. drawerRow.appendChild(drawerCell);
  491. tbody.appendChild(drawerRow);
  492. }
  493. });
  494. }
  495. // Render VLANs Dedicated View
  496. function renderVlansList() {
  497. const tbody = document.getElementById('vlans-table-body');
  498. const emptyState = document.getElementById('vlans-empty-state');
  499. const countBadge = document.getElementById('vlans-table-count');
  500. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  501. tbody.innerHTML = '';
  502. const allVlans = state.vlans || [];
  503. countBadge.innerText = allVlans.length;
  504. const filtered = allVlans.filter(v => {
  505. if (!query) return true;
  506. return v.name.toLowerCase().includes(query) ||
  507. String(v.vlan_id).includes(query) ||
  508. (v.description || '').toLowerCase().includes(query) ||
  509. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  510. });
  511. if (allVlans.length === 0) {
  512. emptyState.classList.remove('hidden');
  513. return;
  514. }
  515. emptyState.classList.add('hidden');
  516. filtered.forEach(v => {
  517. const isUp = v.state === 'UP';
  518. const tr = document.createElement('tr');
  519. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  520. tr.innerHTML = `
  521. <td class="py-3 px-4">
  522. <span class="px-2.5 py-1 rounded-md text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800/70 shadow-sm">
  523. VLAN ${v.vlan_id}
  524. </span>
  525. </td>
  526. <td class="py-3 px-4 font-bold text-white">${v.name}</td>
  527. <td class="py-3 px-4 text-slate-300">
  528. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  529. </td>
  530. <td class="py-3 px-4 text-emerald-400 font-medium">
  531. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  532. </td>
  533. <td class="py-3 px-4 text-slate-300 font-sans">
  534. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  535. </td>
  536. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  537. <td class="py-3 px-4 font-sans">
  538. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  539. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  540. isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30'
  541. }">
  542. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  543. <span>${v.state}</span>
  544. </button>
  545. </td>
  546. <td class="py-3 px-4 text-right space-x-2 font-sans">
  547. <button onclick="openIfaceModal('${v.name}')" class="text-xs bg-slate-800 hover:bg-slate-700 text-slate-200 px-2.5 py-1 rounded border border-slate-700">Edit</button>
  548. <button onclick="confirmDeleteVlan('${v.name}')" class="text-xs text-rose-400 hover:text-rose-300 hover:bg-rose-950/40 px-2 py-1 rounded transition">Delete</button>
  549. </td>
  550. `;
  551. tbody.appendChild(tr);
  552. });
  553. }
  554. // Toggle interface UP / DOWN
  555. async function toggleInterfaceState(name, newState) {
  556. try {
  557. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  558. method: 'POST',
  559. headers: { 'Content-Type': 'application/json' },
  560. body: JSON.stringify({ state: newState })
  561. });
  562. const data = await res.json();
  563. if (res.ok) {
  564. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  565. fetchData(false);
  566. } else {
  567. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  568. }
  569. } catch (err) {
  570. showToast('Error', err.message, 'error');
  571. }
  572. }
  573. // ---------------- MikroTik Flag & Utilities ----------------
  574. function renderMikroTikFlag(running, disabled) {
  575. if (running) {
  576. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-emerald-500/20 text-emerald-400 border border-emerald-500/40 shadow-sm" title="Running (Connected)">R</span>`;
  577. }
  578. if (disabled) {
  579. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-rose-500/20 text-rose-400 border border-rose-500/40 shadow-sm" title="Disabled">X</span>`;
  580. }
  581. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] text-slate-500 bg-slate-800/80 border border-slate-700/60" title="Idle / Disconnected">-</span>`;
  582. }
  583. function copyToClipboard(text, label = 'Text') {
  584. navigator.clipboard.writeText(text).then(() => {
  585. showToast('Copied', `${label} copied to clipboard`, 'success');
  586. }).catch(() => {
  587. prompt('Copy value:', text);
  588. });
  589. }
  590. // ======================== PPPoE Multi-Instance ========================
  591. async function loadPPPoE(populateInputs = true) {
  592. try {
  593. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  594. const list = await res.json();
  595. state.pppoeList = Array.isArray(list) ? list : [];
  596. const badge = document.getElementById('pppoe-count-badge');
  597. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  598. const tbody = document.getElementById('pppoe-table-body');
  599. const empty = document.getElementById('pppoe-empty');
  600. if (!tbody) return;
  601. tbody.innerHTML = '';
  602. if (state.pppoeList.length === 0) {
  603. if (empty) empty.classList.remove('hidden');
  604. } else {
  605. if (empty) empty.classList.add('hidden');
  606. state.pppoeList.forEach(inst => {
  607. const tr = document.createElement('tr');
  608. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  609. tr.innerHTML = `
  610. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  611. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  612. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.interface}</td>
  613. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  614. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  615. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  616. <td class="py-2.5 px-3 text-center">
  617. <span class="px-2 py-0.5 rounded text-[10px] font-sans ${inst.default_route ? 'bg-blue-500/20 text-blue-300 border border-blue-500/30' : 'bg-slate-800 text-slate-500'}">
  618. ${inst.default_route ? 'Yes' : 'No'}
  619. </span>
  620. </td>
  621. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  622. ${inst.running ? `
  623. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  624. ` : `
  625. <button onclick="connectPPPoEInstance('${inst.name}')" class="text-xs bg-blue-600/30 hover:bg-blue-600/50 text-blue-300 px-2 py-0.5 rounded border border-blue-500/30">Connect</button>
  626. `}
  627. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  628. ${inst.disabled ? 'Enable' : 'Disable'}
  629. </button>
  630. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  631. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  632. </td>
  633. `;
  634. tbody.appendChild(tr);
  635. });
  636. }
  637. } catch (err) {
  638. console.error('Failed to load PPPoE:', err);
  639. }
  640. }
  641. function openAddPPPoEModal() {
  642. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  643. document.getElementById('pppoe-modal-edit-orig').value = '';
  644. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  645. document.getElementById('pppoe-modal-name').readOnly = false;
  646. document.getElementById('pppoe-modal-user').value = '';
  647. document.getElementById('pppoe-modal-pass').value = '';
  648. document.getElementById('pppoe-modal-service').value = '';
  649. document.getElementById('pppoe-modal-mtu').value = '1492';
  650. document.getElementById('pppoe-modal-defroute').checked = true;
  651. document.getElementById('pppoe-modal-reconnect').checked = true;
  652. document.getElementById('pppoe-modal-disabled').checked = false;
  653. // Populate interfaces
  654. const sel = document.getElementById('pppoe-modal-iface');
  655. sel.innerHTML = '';
  656. (state.interfaces || []).forEach(i => {
  657. if (i.name === 'lo') return;
  658. const opt = document.createElement('option');
  659. opt.value = i.name;
  660. opt.innerText = `${i.name} (${i.role || i.type})`;
  661. sel.appendChild(opt);
  662. });
  663. document.getElementById('pppoe-modal').classList.remove('hidden');
  664. }
  665. function openEditPPPoEModal(name) {
  666. const inst = (state.pppoeList || []).find(i => i.name === name);
  667. if (!inst) return;
  668. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  669. document.getElementById('pppoe-modal-edit-orig').value = name;
  670. document.getElementById('pppoe-modal-name').value = inst.name;
  671. document.getElementById('pppoe-modal-name').readOnly = true;
  672. document.getElementById('pppoe-modal-user').value = inst.username || '';
  673. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  674. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  675. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  676. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  677. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  678. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  679. const sel = document.getElementById('pppoe-modal-iface');
  680. sel.innerHTML = '';
  681. (state.interfaces || []).forEach(i => {
  682. if (i.name === 'lo') return;
  683. const opt = document.createElement('option');
  684. opt.value = i.name;
  685. opt.innerText = `${i.name} (${i.role || i.type})`;
  686. if (i.name === inst.interface) opt.selected = true;
  687. sel.appendChild(opt);
  688. });
  689. document.getElementById('pppoe-modal').classList.remove('hidden');
  690. }
  691. function closePPPoEModal() {
  692. document.getElementById('pppoe-modal').classList.add('hidden');
  693. }
  694. async function submitSavePPPoE(e) {
  695. e.preventDefault();
  696. const name = document.getElementById('pppoe-modal-name').value.trim();
  697. const iface = document.getElementById('pppoe-modal-iface').value;
  698. const user = document.getElementById('pppoe-modal-user').value.trim();
  699. const pass = document.getElementById('pppoe-modal-pass').value;
  700. const service = document.getElementById('pppoe-modal-service').value.trim();
  701. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  702. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  703. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  704. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  705. try {
  706. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  707. method: 'POST',
  708. headers: { 'Content-Type': 'application/json' },
  709. body: JSON.stringify({
  710. name,
  711. interface: iface,
  712. username: user,
  713. password: pass,
  714. service_name: service,
  715. mtu,
  716. default_route: defRoute,
  717. auto_reconnect: reconnect,
  718. disabled
  719. })
  720. });
  721. if (res.ok) {
  722. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  723. closePPPoEModal();
  724. loadPPPoE(false);
  725. fetchData(false);
  726. } else {
  727. const err = await res.json();
  728. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  729. }
  730. } catch (err) {
  731. showToast('Error', err.message, 'error');
  732. }
  733. }
  734. async function connectPPPoEInstance(name) {
  735. try {
  736. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  737. if (res.ok) {
  738. showToast('Connecting', `Dialing ${name}...`, 'info');
  739. setTimeout(() => loadPPPoE(false), 2000);
  740. }
  741. } catch (err) {
  742. showToast('Error', err.message, 'error');
  743. }
  744. }
  745. async function disconnectPPPoEInstance(name) {
  746. try {
  747. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  748. if (res.ok) {
  749. showToast('Disconnected', `${name} session terminated`, 'info');
  750. setTimeout(() => loadPPPoE(false), 1000);
  751. }
  752. } catch (err) {
  753. showToast('Error', err.message, 'error');
  754. }
  755. }
  756. async function togglePPPoEState(name, enable) {
  757. try {
  758. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  759. method: 'POST',
  760. headers: { 'Content-Type': 'application/json' },
  761. body: JSON.stringify({ enabled: enable })
  762. });
  763. if (res.ok) {
  764. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  765. loadPPPoE(false);
  766. }
  767. } catch (err) {
  768. showToast('Error', err.message, 'error');
  769. }
  770. }
  771. async function deletePPPoEInstance(name) {
  772. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  773. try {
  774. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  775. if (res.ok) {
  776. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  777. loadPPPoE(false);
  778. fetchData(false);
  779. }
  780. } catch (err) {
  781. showToast('Error', err.message, 'error');
  782. }
  783. }
  784. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  785. state.wgSubTab = 'ifaces';
  786. function switchWGSubTab(tab) {
  787. state.wgSubTab = tab;
  788. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  789. const peersPanel = document.getElementById('wg-subtab-peers');
  790. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  791. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  792. if (tab === 'ifaces') {
  793. ifacesPanel?.classList.remove('hidden');
  794. peersPanel?.classList.add('hidden');
  795. ifacesBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-rose-500 text-white transition flex items-center gap-2';
  796. peersBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  797. } else {
  798. ifacesPanel?.classList.add('hidden');
  799. peersPanel?.classList.remove('hidden');
  800. ifacesBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  801. peersBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-rose-500 text-white transition flex items-center gap-2';
  802. renderWGPeers();
  803. }
  804. }
  805. async function loadWireGuard(populateInputs = true) {
  806. try {
  807. const [ifacesRes, peersRes] = await Promise.all([
  808. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  809. fetch(`${API_BASE}/vpn/wireguard/peers`)
  810. ]);
  811. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  812. const peers = peersRes.ok ? await peersRes.json() : [];
  813. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  814. state.wgPeers = Array.isArray(peers) ? peers : [];
  815. // Badges
  816. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  817. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  818. const peersCountBadge = document.getElementById('wg-peers-count');
  819. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  820. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  821. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  822. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  823. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  824. // Render Interfaces
  825. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  826. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  827. if (ifacesTbody) {
  828. ifacesTbody.innerHTML = '';
  829. if (state.wgInterfaces.length === 0) {
  830. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  831. } else {
  832. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  833. state.wgInterfaces.forEach(iface => {
  834. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  835. const tr = document.createElement('tr');
  836. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  837. tr.innerHTML = `
  838. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  839. <td class="py-2.5 px-3 font-bold text-white">${iface.name}</td>
  840. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  841. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '-'}</td>
  842. <td class="py-2.5 px-3 text-slate-300 font-mono">
  843. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  844. ${(iface.public_key || '').substring(0, 10)}... 📋
  845. </span>
  846. </td>
  847. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  848. <td class="py-2.5 px-3 text-center">
  849. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  850. </td>
  851. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  852. ${iface.running ? `
  853. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300">Stop</button>
  854. ` : `
  855. <button onclick="startWGInterface('${iface.name}')" class="text-xs bg-rose-600/30 hover:bg-rose-600/50 text-rose-300 px-2 py-0.5 rounded border border-rose-500/30">Start</button>
  856. `}
  857. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  858. ${iface.disabled ? 'Enable' : 'Disable'}
  859. </button>
  860. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  861. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  862. </td>
  863. `;
  864. ifacesTbody.appendChild(tr);
  865. });
  866. }
  867. }
  868. // Populate filter dropdown in peers tab
  869. const filterSel = document.getElementById('wg-peers-filter-iface');
  870. if (filterSel) {
  871. const currentVal = filterSel.value;
  872. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  873. state.wgInterfaces.forEach(i => {
  874. const opt = document.createElement('option');
  875. opt.value = i.name;
  876. opt.innerText = i.name;
  877. if (i.name === currentVal) opt.selected = true;
  878. filterSel.appendChild(opt);
  879. });
  880. }
  881. renderWGPeers();
  882. } catch (err) {
  883. console.error('Failed to load WireGuard:', err);
  884. }
  885. }
  886. function renderWGPeers() {
  887. const filterSel = document.getElementById('wg-peers-filter-iface');
  888. const selectedIface = filterSel ? filterSel.value : '';
  889. const tbody = document.getElementById('wg-peers-table-body');
  890. const empty = document.getElementById('wg-peers-empty');
  891. if (!tbody) return;
  892. tbody.innerHTML = '';
  893. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  894. if (filtered.length === 0) {
  895. if (empty) empty.classList.remove('hidden');
  896. } else {
  897. if (empty) empty.classList.add('hidden');
  898. filtered.forEach(p => {
  899. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  900. const tr = document.createElement('tr');
  901. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  902. tr.innerHTML = `
  903. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  904. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${p.interface}</td>
  905. <td class="py-2.5 px-3 font-bold text-white font-sans">${p.name || 'Unnamed'}</td>
  906. <td class="py-2.5 px-3 text-slate-300 font-mono">
  907. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  908. ${p.public_key.substring(0, 10)}... 📋
  909. </span>
  910. </td>
  911. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  912. <td class="py-2.5 px-3 text-slate-400 font-mono">${p.endpoint_address ? (p.endpoint_address + (p.endpoint_port ? ':' + p.endpoint_port : '')) : '-'}</td>
  913. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  914. <td class="py-2.5 px-3 font-mono text-[11px]">
  915. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  916. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  917. </td>
  918. <td class="py-2.5 px-3 text-right font-sans">
  919. <button onclick="deleteWGPeer('${p.interface}', '${p.public_key}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  920. </td>
  921. `;
  922. tbody.appendChild(tr);
  923. });
  924. }
  925. }
  926. function openAddWGInterfaceModal() {
  927. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  928. document.getElementById('wg-iface-modal-edit-orig').value = '';
  929. document.getElementById('wg-iface-modal-name').value = `wg${(state.wgInterfaces || []).length}`;
  930. document.getElementById('wg-iface-modal-name').readOnly = false;
  931. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  932. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  933. document.getElementById('wg-iface-modal-mtu').value = '1420';
  934. document.getElementById('wg-iface-modal-pubkey').value = '';
  935. document.getElementById('wg-iface-modal-privkey').value = '';
  936. document.getElementById('wg-iface-modal-disabled').checked = false;
  937. generateWGInterfaceKeys();
  938. document.getElementById('wg-iface-modal').classList.remove('hidden');
  939. }
  940. function openEditWGInterfaceModal(name) {
  941. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  942. if (!iface) return;
  943. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  944. document.getElementById('wg-iface-modal-edit-orig').value = name;
  945. document.getElementById('wg-iface-modal-name').value = iface.name;
  946. document.getElementById('wg-iface-modal-name').readOnly = true;
  947. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  948. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  949. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  950. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  951. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  952. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  953. document.getElementById('wg-iface-modal').classList.remove('hidden');
  954. }
  955. function closeAddWGInterfaceModal() {
  956. document.getElementById('wg-iface-modal').classList.add('hidden');
  957. }
  958. async function generateWGInterfaceKeys() {
  959. try {
  960. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  961. const keys = await res.json();
  962. if (res.ok) {
  963. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  964. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  965. }
  966. } catch (err) {
  967. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  968. }
  969. }
  970. async function submitSaveWGInterface(e) {
  971. e.preventDefault();
  972. const name = document.getElementById('wg-iface-modal-name').value.trim();
  973. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  974. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  975. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  976. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  977. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  978. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  979. try {
  980. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  981. method: 'POST',
  982. headers: { 'Content-Type': 'application/json' },
  983. body: JSON.stringify({
  984. name,
  985. listen_port: port,
  986. address: addr,
  987. mtu,
  988. public_key: pub,
  989. private_key: priv,
  990. disabled
  991. })
  992. });
  993. if (res.ok) {
  994. showToast('WireGuard Saved', `Interface ${name} configured`, 'success');
  995. closeAddWGInterfaceModal();
  996. loadWireGuard(false);
  997. fetchData(false);
  998. }
  999. } catch (err) {
  1000. showToast('Error', err.message, 'error');
  1001. }
  1002. }
  1003. async function startWGInterface(name) {
  1004. try {
  1005. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1006. if (res.ok) {
  1007. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1008. loadWireGuard(false);
  1009. fetchData(false);
  1010. }
  1011. } catch (err) {
  1012. showToast('Error', err.message, 'error');
  1013. }
  1014. }
  1015. async function stopWGInterface(name) {
  1016. try {
  1017. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1018. if (res.ok) {
  1019. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1020. loadWireGuard(false);
  1021. fetchData(false);
  1022. }
  1023. } catch (err) {
  1024. showToast('Error', err.message, 'error');
  1025. }
  1026. }
  1027. async function toggleWGInterfaceState(name, enable) {
  1028. try {
  1029. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1030. method: 'POST',
  1031. headers: { 'Content-Type': 'application/json' },
  1032. body: JSON.stringify({ enabled: enable })
  1033. });
  1034. if (res.ok) {
  1035. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1036. loadWireGuard(false);
  1037. }
  1038. } catch (err) {
  1039. showToast('Error', err.message, 'error');
  1040. }
  1041. }
  1042. async function deleteWGInterface(name) {
  1043. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}?`)) return;
  1044. try {
  1045. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1046. if (res.ok) {
  1047. showToast('Deleted', `Interface ${name} removed`, 'success');
  1048. loadWireGuard(false);
  1049. fetchData(false);
  1050. }
  1051. } catch (err) {
  1052. showToast('Error', err.message, 'error');
  1053. }
  1054. }
  1055. function openAddWGPeerModal() {
  1056. const sel = document.getElementById('wg-peer-modal-iface');
  1057. sel.innerHTML = '';
  1058. (state.wgInterfaces || []).forEach(i => {
  1059. const opt = document.createElement('option');
  1060. opt.value = i.name;
  1061. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1062. sel.appendChild(opt);
  1063. });
  1064. if ((state.wgInterfaces || []).length === 0) {
  1065. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1066. openAddWGInterfaceModal();
  1067. return;
  1068. }
  1069. document.getElementById('wg-peer-modal-name').value = '';
  1070. document.getElementById('wg-peer-modal-pubkey').value = '';
  1071. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1072. document.getElementById('wg-peer-modal-endpoint').value = '';
  1073. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1074. document.getElementById('wg-peer-modal-preshared').value = '';
  1075. document.getElementById('wg-peer-modal-disabled').checked = false;
  1076. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1077. }
  1078. function closeAddWGPeerModal() {
  1079. document.getElementById('wg-peer-modal').classList.add('hidden');
  1080. }
  1081. async function submitSaveWGPeer(e) {
  1082. e.preventDefault();
  1083. const iface = document.getElementById('wg-peer-modal-iface').value;
  1084. const name = document.getElementById('wg-peer-modal-name').value.trim();
  1085. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1086. const allowed = document.getElementById('wg-peer-modal-allowedips').value.split(',').map(s => s.trim());
  1087. const ep = document.getElementById('wg-peer-modal-endpoint').value.trim();
  1088. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 25;
  1089. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  1090. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  1091. let epAddr = ep;
  1092. let epPort = 0;
  1093. if (ep.includes(':')) {
  1094. const parts = ep.split(':');
  1095. epAddr = parts[0];
  1096. epPort = parseInt(parts[1], 10) || 0;
  1097. }
  1098. try {
  1099. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  1100. method: 'POST',
  1101. headers: { 'Content-Type': 'application/json' },
  1102. body: JSON.stringify({
  1103. interface: iface,
  1104. name,
  1105. public_key: pub,
  1106. allowed_ips: allowed,
  1107. endpoint_address: epAddr,
  1108. endpoint_port: epPort,
  1109. persistent_keepalive: keepalive,
  1110. preshared_key: psk,
  1111. disabled
  1112. })
  1113. });
  1114. if (res.ok) {
  1115. showToast('Peer Saved', `Peer ${name} added to ${iface}`, 'success');
  1116. closeAddWGPeerModal();
  1117. loadWireGuard(false);
  1118. }
  1119. } catch (err) {
  1120. showToast('Error', err.message, 'error');
  1121. }
  1122. }
  1123. async function deleteWGPeer(iface, pubkey) {
  1124. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  1125. try {
  1126. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/${encodeURIComponent(iface)}/${encodeURIComponent(pubkey)}`, {
  1127. method: 'DELETE'
  1128. });
  1129. if (res.ok) {
  1130. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  1131. loadWireGuard(false);
  1132. }
  1133. } catch (err) {
  1134. showToast('Error', err.message, 'error');
  1135. }
  1136. }
  1137. // ======================== IPSec Multi-Tunnel ========================
  1138. async function loadIPSec(populateInputs = true) {
  1139. try {
  1140. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1141. const list = await res.json();
  1142. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1143. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1144. const badge = document.getElementById('ipsec-sas-badge');
  1145. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1146. const tbody = document.getElementById('ipsec-table-body');
  1147. const empty = document.getElementById('ipsec-empty');
  1148. if (!tbody) return;
  1149. tbody.innerHTML = '';
  1150. if (state.ipsecTunnels.length === 0) {
  1151. if (empty) empty.classList.remove('hidden');
  1152. } else {
  1153. if (empty) empty.classList.add('hidden');
  1154. state.ipsecTunnels.forEach(c => {
  1155. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1156. const tr = document.createElement('tr');
  1157. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1158. tr.innerHTML = `
  1159. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isEstablished, c.disabled)}</td>
  1160. <td class="py-2.5 px-4 font-bold text-white">${c.name}</td>
  1161. <td class="py-2.5 px-4 text-emerald-400 font-mono">${c.local_subnet || '-'}</td>
  1162. <td class="py-2.5 px-4 text-slate-300 font-mono">${c.remote_addrs || '-'}</td>
  1163. <td class="py-2.5 px-4 text-cyan-400 font-mono">${c.remote_subnet || '-'}</td>
  1164. <td class="py-2.5 px-4 font-sans">
  1165. <span class="px-2 py-0.5 rounded-full text-[10px] font-semibold ${
  1166. isEstablished ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-slate-800 text-slate-400'
  1167. }">${c.status || (isEstablished ? 'ESTABLISHED' : 'DISCONNECTED')}</span>
  1168. </td>
  1169. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  1170. ${isEstablished ? `
  1171. <button onclick="stopIPSecTunnel('${c.name}')" class="text-xs text-rose-400 hover:text-rose-300">Terminate</button>
  1172. ` : `
  1173. <button onclick="startIPSecTunnel('${c.name}')" class="text-xs bg-amber-600/30 hover:bg-amber-600/50 text-amber-300 px-2 py-0.5 rounded border border-amber-500/30">Initiate</button>
  1174. `}
  1175. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1176. ${c.disabled ? 'Enable' : 'Disable'}
  1177. </button>
  1178. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1179. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1180. </td>
  1181. `;
  1182. tbody.appendChild(tr);
  1183. });
  1184. }
  1185. } catch (err) {
  1186. console.error('Failed to load IPSec:', err);
  1187. }
  1188. }
  1189. function openAddIPSecModal() {
  1190. document.getElementById('ipsec-modal-title').innerText = 'Configure IPSec IKEv2 Tunnel';
  1191. document.getElementById('ipsec-modal-name').value = `ipsec-${(state.ipsecTunnels || []).length + 1}`;
  1192. document.getElementById('ipsec-modal-name').readOnly = false;
  1193. document.getElementById('ipsec-modal-localts').value = '192.168.10.0/24';
  1194. document.getElementById('ipsec-modal-remotets').value = '192.168.20.0/24';
  1195. document.getElementById('ipsec-modal-remotegw').value = '';
  1196. document.getElementById('ipsec-modal-psk').value = '';
  1197. document.getElementById('ipsec-modal-ikeprop').value = 'aes256-sha256-modp2048,default';
  1198. document.getElementById('ipsec-modal-espprop').value = 'aes256-sha256-modp2048,default';
  1199. document.getElementById('ipsec-modal-autostart').checked = true;
  1200. document.getElementById('ipsec-modal-disabled').checked = false;
  1201. document.getElementById('ipsec-modal').classList.remove('hidden');
  1202. }
  1203. function openEditIPSecModal(name) {
  1204. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  1205. if (!conn) return;
  1206. document.getElementById('ipsec-modal-title').innerText = `Edit IPSec Tunnel: ${name}`;
  1207. document.getElementById('ipsec-modal-name').value = conn.name;
  1208. document.getElementById('ipsec-modal-name').readOnly = true;
  1209. document.getElementById('ipsec-modal-localts').value = conn.local_subnet || '';
  1210. document.getElementById('ipsec-modal-remotets').value = conn.remote_subnet || '';
  1211. document.getElementById('ipsec-modal-remotegw').value = conn.remote_addrs || '';
  1212. document.getElementById('ipsec-modal-psk').value = conn.preshared_key || '';
  1213. document.getElementById('ipsec-modal-ikeprop').value = conn.ike_proposals || 'aes256-sha256-modp2048,default';
  1214. document.getElementById('ipsec-modal-espprop').value = conn.esp_proposals || 'aes256-sha256-modp2048,default';
  1215. document.getElementById('ipsec-modal-autostart').checked = conn.auto_start ?? true;
  1216. document.getElementById('ipsec-modal-disabled').checked = !!conn.disabled;
  1217. document.getElementById('ipsec-modal').classList.remove('hidden');
  1218. }
  1219. function closeAddIPSecModal() {
  1220. document.getElementById('ipsec-modal').classList.add('hidden');
  1221. }
  1222. async function submitSaveIPSec(e) {
  1223. e.preventDefault();
  1224. const name = document.getElementById('ipsec-modal-name').value.trim();
  1225. const localts = document.getElementById('ipsec-modal-localts').value.trim();
  1226. const remotets = document.getElementById('ipsec-modal-remotets').value.trim();
  1227. const remotegw = document.getElementById('ipsec-modal-remotegw').value.trim();
  1228. const psk = document.getElementById('ipsec-modal-psk').value;
  1229. const ike = document.getElementById('ipsec-modal-ikeprop').value.trim();
  1230. const esp = document.getElementById('ipsec-modal-espprop').value.trim();
  1231. const autostart = document.getElementById('ipsec-modal-autostart').checked;
  1232. const disabled = document.getElementById('ipsec-modal-disabled').checked;
  1233. try {
  1234. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  1235. method: 'POST',
  1236. headers: { 'Content-Type': 'application/json' },
  1237. body: JSON.stringify({
  1238. name,
  1239. local_addrs: '%any',
  1240. remote_addrs: remotegw,
  1241. local_subnet: localts,
  1242. remote_subnet: remotets,
  1243. preshared_key: psk,
  1244. ike_proposals: ike,
  1245. esp_proposals: esp,
  1246. auto_start: autostart,
  1247. disabled
  1248. })
  1249. });
  1250. if (res.ok) {
  1251. showToast('IPSec Saved', `Tunnel ${name} configured`, 'success');
  1252. closeAddIPSecModal();
  1253. loadIPSec(false);
  1254. fetchData(false);
  1255. }
  1256. } catch (err) {
  1257. showToast('Error', err.message, 'error');
  1258. }
  1259. }
  1260. async function startIPSecTunnel(name) {
  1261. try {
  1262. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1263. if (res.ok) {
  1264. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  1265. setTimeout(() => loadIPSec(false), 2000);
  1266. }
  1267. } catch (err) {
  1268. showToast('Error', err.message, 'error');
  1269. }
  1270. }
  1271. async function stopIPSecTunnel(name) {
  1272. try {
  1273. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1274. if (res.ok) {
  1275. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  1276. loadIPSec(false);
  1277. }
  1278. } catch (err) {
  1279. showToast('Error', err.message, 'error');
  1280. }
  1281. }
  1282. async function toggleIPSecState(name, enable) {
  1283. try {
  1284. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  1285. method: 'POST',
  1286. headers: { 'Content-Type': 'application/json' },
  1287. body: JSON.stringify({ enabled: enable })
  1288. });
  1289. if (res.ok) {
  1290. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  1291. loadIPSec(false);
  1292. }
  1293. } catch (err) {
  1294. showToast('Error', err.message, 'error');
  1295. }
  1296. }
  1297. async function deleteIPSecConn(name) {
  1298. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  1299. try {
  1300. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1301. if (res.ok) {
  1302. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  1303. loadIPSec(false);
  1304. fetchData(false);
  1305. }
  1306. } catch (err) {
  1307. showToast('Error', err.message, 'error');
  1308. }
  1309. }
  1310. // ======================== L2TP Multi-Instance ========================
  1311. async function loadL2TP(populateInputs = true) {
  1312. try {
  1313. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  1314. const list = await res.json();
  1315. state.l2tpList = Array.isArray(list) ? list : [];
  1316. const badge = document.getElementById('l2tp-count-badge');
  1317. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  1318. const tbody = document.getElementById('l2tp-table-body');
  1319. const empty = document.getElementById('l2tp-empty');
  1320. if (!tbody) return;
  1321. tbody.innerHTML = '';
  1322. if (state.l2tpList.length === 0) {
  1323. if (empty) empty.classList.remove('hidden');
  1324. } else {
  1325. if (empty) empty.classList.add('hidden');
  1326. state.l2tpList.forEach(inst => {
  1327. const tr = document.createElement('tr');
  1328. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1329. tr.innerHTML = `
  1330. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1331. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1332. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.connect_to}</td>
  1333. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1334. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1335. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1336. <td class="py-2.5 px-3 text-center">
  1337. <span class="px-2 py-0.5 rounded text-[10px] font-sans ${inst.default_route ? 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30' : 'bg-slate-800 text-slate-500'}">
  1338. ${inst.default_route ? 'Yes' : 'No'}
  1339. </span>
  1340. </td>
  1341. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1342. ${inst.running ? `
  1343. <button onclick="disconnectL2TPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1344. ` : `
  1345. <button onclick="connectL2TPInstance('${inst.name}')" class="text-xs bg-cyan-600/30 hover:bg-cyan-600/50 text-cyan-300 px-2 py-0.5 rounded border border-cyan-500/30">Connect</button>
  1346. `}
  1347. <button onclick="toggleL2TPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1348. ${inst.disabled ? 'Enable' : 'Disable'}
  1349. </button>
  1350. <button onclick="openEditL2TPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1351. <button onclick="deleteL2TPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1352. </td>
  1353. `;
  1354. tbody.appendChild(tr);
  1355. });
  1356. }
  1357. } catch (err) {
  1358. console.error('Failed to load L2TP:', err);
  1359. }
  1360. }
  1361. function openAddL2TPModal() {
  1362. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  1363. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  1364. document.getElementById('l2tp-modal-name').readOnly = false;
  1365. document.getElementById('l2tp-modal-server').value = '';
  1366. document.getElementById('l2tp-modal-user').value = '';
  1367. document.getElementById('l2tp-modal-pass').value = '';
  1368. document.getElementById('l2tp-modal-ipsec').value = '';
  1369. document.getElementById('l2tp-modal-defroute').checked = true;
  1370. document.getElementById('l2tp-modal-disabled').checked = false;
  1371. document.getElementById('l2tp-modal').classList.remove('hidden');
  1372. }
  1373. function openEditL2TPModal(name) {
  1374. const inst = (state.l2tpList || []).find(i => i.name === name);
  1375. if (!inst) return;
  1376. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  1377. document.getElementById('l2tp-modal-name').value = inst.name;
  1378. document.getElementById('l2tp-modal-name').readOnly = true;
  1379. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  1380. document.getElementById('l2tp-modal-user').value = inst.username || '';
  1381. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  1382. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  1383. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  1384. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  1385. document.getElementById('l2tp-modal').classList.remove('hidden');
  1386. }
  1387. function closeL2TPModal() {
  1388. document.getElementById('l2tp-modal').classList.add('hidden');
  1389. }
  1390. async function submitSaveL2TP(e) {
  1391. e.preventDefault();
  1392. const name = document.getElementById('l2tp-modal-name').value.trim();
  1393. const server = document.getElementById('l2tp-modal-server').value.trim();
  1394. const user = document.getElementById('l2tp-modal-user').value.trim();
  1395. const pass = document.getElementById('l2tp-modal-pass').value;
  1396. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  1397. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  1398. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  1399. try {
  1400. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  1401. method: 'POST',
  1402. headers: { 'Content-Type': 'application/json' },
  1403. body: JSON.stringify({
  1404. name,
  1405. connect_to: server,
  1406. username: user,
  1407. password: pass,
  1408. ipsec_secret: ipsec,
  1409. default_route: defRoute,
  1410. disabled
  1411. })
  1412. });
  1413. if (res.ok) {
  1414. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  1415. closeL2TPModal();
  1416. loadL2TP(false);
  1417. fetchData(false);
  1418. }
  1419. } catch (err) {
  1420. showToast('Error', err.message, 'error');
  1421. }
  1422. }
  1423. async function connectL2TPInstance(name) {
  1424. try {
  1425. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1426. if (res.ok) {
  1427. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  1428. setTimeout(() => loadL2TP(false), 2000);
  1429. }
  1430. } catch (err) {
  1431. showToast('Error', err.message, 'error');
  1432. }
  1433. }
  1434. async function disconnectL2TPInstance(name) {
  1435. try {
  1436. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1437. if (res.ok) {
  1438. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  1439. loadL2TP(false);
  1440. }
  1441. } catch (err) {
  1442. showToast('Error', err.message, 'error');
  1443. }
  1444. }
  1445. async function toggleL2TPState(name, enable) {
  1446. try {
  1447. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  1448. method: 'POST',
  1449. headers: { 'Content-Type': 'application/json' },
  1450. body: JSON.stringify({ enabled: enable })
  1451. });
  1452. if (res.ok) {
  1453. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1454. loadL2TP(false);
  1455. }
  1456. } catch (err) {
  1457. showToast('Error', err.message, 'error');
  1458. }
  1459. }
  1460. async function deleteL2TPInstance(name) {
  1461. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  1462. try {
  1463. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1464. if (res.ok) {
  1465. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  1466. loadL2TP(false);
  1467. fetchData(false);
  1468. }
  1469. } catch (err) {
  1470. showToast('Error', err.message, 'error');
  1471. }
  1472. }
  1473. // ======================== PPTP Multi-Instance ========================
  1474. async function loadPPTP(populateInputs = true) {
  1475. try {
  1476. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  1477. const list = await res.json();
  1478. state.pptpList = Array.isArray(list) ? list : [];
  1479. const badge = document.getElementById('pptp-count-badge');
  1480. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  1481. const tbody = document.getElementById('pptp-table-body');
  1482. const empty = document.getElementById('pptp-empty');
  1483. if (!tbody) return;
  1484. tbody.innerHTML = '';
  1485. if (state.pptpList.length === 0) {
  1486. if (empty) empty.classList.remove('hidden');
  1487. } else {
  1488. if (empty) empty.classList.add('hidden');
  1489. state.pptpList.forEach(inst => {
  1490. const tr = document.createElement('tr');
  1491. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1492. tr.innerHTML = `
  1493. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1494. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1495. <td class="py-2.5 px-3 text-purple-400 font-mono">${inst.connect_to}</td>
  1496. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1497. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1498. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1499. <td class="py-2.5 px-3 text-center">
  1500. <span class="px-2 py-0.5 rounded text-[10px] font-sans ${inst.require_mppe ? 'bg-purple-500/20 text-purple-300 border border-purple-500/30' : 'bg-slate-800 text-slate-500'}">
  1501. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  1502. </span>
  1503. </td>
  1504. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1505. ${inst.running ? `
  1506. <button onclick="disconnectPPTPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1507. ` : `
  1508. <button onclick="connectPPTPInstance('${inst.name}')" class="text-xs bg-purple-600/30 hover:bg-purple-600/50 text-purple-300 px-2 py-0.5 rounded border border-purple-500/30">Connect</button>
  1509. `}
  1510. <button onclick="togglePPTPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1511. ${inst.disabled ? 'Enable' : 'Disable'}
  1512. </button>
  1513. <button onclick="openEditPPTPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1514. <button onclick="deletePPTPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1515. </td>
  1516. `;
  1517. tbody.appendChild(tr);
  1518. });
  1519. }
  1520. } catch (err) {
  1521. console.error('Failed to load PPTP:', err);
  1522. }
  1523. }
  1524. function openAddPPTPModal() {
  1525. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  1526. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  1527. document.getElementById('pptp-modal-name').readOnly = false;
  1528. document.getElementById('pptp-modal-server').value = '';
  1529. document.getElementById('pptp-modal-user').value = '';
  1530. document.getElementById('pptp-modal-pass').value = '';
  1531. document.getElementById('pptp-modal-mppe').checked = true;
  1532. document.getElementById('pptp-modal-defroute').checked = true;
  1533. document.getElementById('pptp-modal-disabled').checked = false;
  1534. document.getElementById('pptp-modal').classList.remove('hidden');
  1535. }
  1536. function openEditPPTPModal(name) {
  1537. const inst = (state.pptpList || []).find(i => i.name === name);
  1538. if (!inst) return;
  1539. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  1540. document.getElementById('pptp-modal-name').value = inst.name;
  1541. document.getElementById('pptp-modal-name').readOnly = true;
  1542. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  1543. document.getElementById('pptp-modal-user').value = inst.username || '';
  1544. document.getElementById('pptp-modal-pass').value = inst.password || '';
  1545. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  1546. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  1547. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  1548. document.getElementById('pptp-modal').classList.remove('hidden');
  1549. }
  1550. function closePPTPModal() {
  1551. document.getElementById('pptp-modal').classList.add('hidden');
  1552. }
  1553. async function submitSavePPTP(e) {
  1554. e.preventDefault();
  1555. const name = document.getElementById('pptp-modal-name').value.trim();
  1556. const server = document.getElementById('pptp-modal-server').value.trim();
  1557. const user = document.getElementById('pptp-modal-user').value.trim();
  1558. const pass = document.getElementById('pptp-modal-pass').value;
  1559. const mppe = document.getElementById('pptp-modal-mppe').checked;
  1560. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  1561. const disabled = document.getElementById('pptp-modal-disabled').checked;
  1562. try {
  1563. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  1564. method: 'POST',
  1565. headers: { 'Content-Type': 'application/json' },
  1566. body: JSON.stringify({
  1567. name,
  1568. connect_to: server,
  1569. username: user,
  1570. password: pass,
  1571. require_mppe: mppe,
  1572. default_route: defRoute,
  1573. auto_reconnect: true,
  1574. disabled
  1575. })
  1576. });
  1577. if (res.ok) {
  1578. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  1579. closePPTPModal();
  1580. loadPPTP(false);
  1581. fetchData(false);
  1582. }
  1583. } catch (err) {
  1584. showToast('Error', err.message, 'error');
  1585. }
  1586. }
  1587. async function connectPPTPInstance(name) {
  1588. try {
  1589. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1590. if (res.ok) {
  1591. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  1592. setTimeout(() => loadPPTP(false), 2000);
  1593. }
  1594. } catch (err) {
  1595. showToast('Error', err.message, 'error');
  1596. }
  1597. }
  1598. async function disconnectPPTPInstance(name) {
  1599. try {
  1600. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1601. if (res.ok) {
  1602. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  1603. loadPPTP(false);
  1604. }
  1605. } catch (err) {
  1606. showToast('Error', err.message, 'error');
  1607. }
  1608. }
  1609. async function togglePPTPState(name, enable) {
  1610. try {
  1611. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  1612. method: 'POST',
  1613. headers: { 'Content-Type': 'application/json' },
  1614. body: JSON.stringify({ enabled: enable })
  1615. });
  1616. if (res.ok) {
  1617. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1618. loadPPTP(false);
  1619. }
  1620. } catch (err) {
  1621. showToast('Error', err.message, 'error');
  1622. }
  1623. }
  1624. async function deletePPTPInstance(name) {
  1625. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  1626. try {
  1627. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1628. if (res.ok) {
  1629. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  1630. loadPPTP(false);
  1631. fetchData(false);
  1632. }
  1633. } catch (err) {
  1634. showToast('Error', err.message, 'error');
  1635. }
  1636. }
  1637. // ---------------- Modal & Helper Functions ----------------
  1638. function openVlanModal(defaultParent = '') {
  1639. const select = document.getElementById('vlan-parent');
  1640. select.innerHTML = '';
  1641. const allIfaces = state.interfaces || [];
  1642. const eligible = allIfaces.filter(i => !i.is_vlan && i.name !== 'lo');
  1643. if (eligible.length === 0) {
  1644. allIfaces.forEach(i => eligible.push(i));
  1645. }
  1646. eligible.forEach(i => {
  1647. const opt = document.createElement('option');
  1648. opt.value = i.name;
  1649. opt.innerText = `${i.name} (${i.role || 'Interface'} - ${i.state})`;
  1650. if (i.name === defaultParent) opt.selected = true;
  1651. select.appendChild(opt);
  1652. });
  1653. document.getElementById('vlan-id').value = '';
  1654. document.getElementById('vlan-name').value = '';
  1655. document.getElementById('vlan-ip').value = '';
  1656. document.getElementById('vlan-desc').value = '';
  1657. autoSuggestVlanName();
  1658. document.getElementById('vlan-modal').classList.remove('hidden');
  1659. }
  1660. function closeVlanModal() {
  1661. document.getElementById('vlan-modal').classList.add('hidden');
  1662. }
  1663. function autoSuggestVlanName() {
  1664. const parent = document.getElementById('vlan-parent').value;
  1665. const id = document.getElementById('vlan-id').value;
  1666. const nameInput = document.getElementById('vlan-name');
  1667. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  1668. }
  1669. function setSubnetPreset(cidr) {
  1670. const ipInput = document.getElementById('vlan-ip');
  1671. const id = document.getElementById('vlan-id').value || '10';
  1672. ipInput.value = `192.168.${id}.1${cidr}`;
  1673. }
  1674. async function submitCreateVlan(e) {
  1675. e.preventDefault();
  1676. const btn = document.getElementById('vlan-submit-btn');
  1677. btn.disabled = true;
  1678. btn.innerText = 'Creating...';
  1679. const parent = document.getElementById('vlan-parent').value;
  1680. const id = parseInt(document.getElementById('vlan-id').value, 10);
  1681. const name = document.getElementById('vlan-name').value.trim();
  1682. const ip = document.getElementById('vlan-ip').value.trim();
  1683. const role = document.getElementById('vlan-role').value;
  1684. const desc = document.getElementById('vlan-desc').value.trim();
  1685. try {
  1686. const res = await fetch(`${API_BASE}/vlans`, {
  1687. method: 'POST',
  1688. headers: { 'Content-Type': 'application/json' },
  1689. body: JSON.stringify({
  1690. parent_name: parent,
  1691. vlan_id: id,
  1692. name: name,
  1693. ip_address: ip,
  1694. role: role,
  1695. description: desc,
  1696. mtu: 1500,
  1697. auto_up: true
  1698. })
  1699. });
  1700. const data = await res.json();
  1701. if (res.ok) {
  1702. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  1703. state.expandedParents.add(parent);
  1704. closeVlanModal();
  1705. await fetchData(true);
  1706. if (state.activeTab !== 'interfaces') navigate('interfaces');
  1707. } else {
  1708. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  1709. }
  1710. } catch (err) {
  1711. showToast('Error', err.message, 'error');
  1712. } finally {
  1713. btn.disabled = false;
  1714. btn.innerText = 'Create VLAN';
  1715. }
  1716. }
  1717. async function confirmDeleteVlan(name) {
  1718. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  1719. try {
  1720. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1721. if (res.ok) {
  1722. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  1723. closeIfaceModal();
  1724. fetchData(true);
  1725. }
  1726. } catch (err) {
  1727. showToast('Error', err.message, 'error');
  1728. }
  1729. }
  1730. function openIfaceModal(name) {
  1731. const iface = (state.interfaces || []).find(i => i.name === name);
  1732. if (!iface) return;
  1733. state.currentModalIface = iface.name;
  1734. document.getElementById('modal-iface-name').innerText = iface.name;
  1735. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  1736. document.getElementById('modal-iface-mtu').value = iface.mtu;
  1737. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  1738. document.getElementById('modal-iface-desc').value = iface.description || '';
  1739. const delBtn = document.getElementById('modal-delete-vlan-btn');
  1740. if (iface.is_vlan) {
  1741. delBtn.classList.remove('hidden');
  1742. } else {
  1743. delBtn.classList.add('hidden');
  1744. }
  1745. renderModalIPs(iface);
  1746. document.getElementById('iface-modal').classList.remove('hidden');
  1747. }
  1748. function renderModalIPs(iface) {
  1749. const container = document.getElementById('modal-ip-list');
  1750. container.innerHTML = '';
  1751. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  1752. if (addrs.length === 0) {
  1753. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  1754. return;
  1755. }
  1756. addrs.forEach(addr => {
  1757. const row = document.createElement('div');
  1758. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  1759. row.innerHTML = `
  1760. <span class="text-white">${addr}</span>
  1761. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  1762. `;
  1763. container.appendChild(row);
  1764. });
  1765. }
  1766. function closeIfaceModal() {
  1767. document.getElementById('iface-modal').classList.add('hidden');
  1768. state.currentModalIface = null;
  1769. }
  1770. async function setIfaceState(name, newState) {
  1771. await toggleInterfaceState(name, newState);
  1772. const updated = (state.interfaces || []).find(i => i.name === name);
  1773. if (updated) openIfaceModal(name);
  1774. }
  1775. async function applyMTU() {
  1776. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  1777. try {
  1778. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  1779. method: 'POST',
  1780. headers: { 'Content-Type': 'application/json' },
  1781. body: JSON.stringify({ mtu })
  1782. });
  1783. if (res.ok) {
  1784. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  1785. fetchData(false);
  1786. }
  1787. } catch (err) {
  1788. showToast('Error', err.message, 'error');
  1789. }
  1790. }
  1791. async function addInterfaceIP() {
  1792. const ip = document.getElementById('modal-new-ip').value.trim();
  1793. if (!ip) return;
  1794. try {
  1795. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  1796. method: 'POST',
  1797. headers: { 'Content-Type': 'application/json' },
  1798. body: JSON.stringify({ ip })
  1799. });
  1800. if (res.ok) {
  1801. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  1802. document.getElementById('modal-new-ip').value = '';
  1803. await fetchData(false);
  1804. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  1805. if (iface) renderModalIPs(iface);
  1806. }
  1807. } catch (err) {
  1808. showToast('Error', err.message, 'error');
  1809. }
  1810. }
  1811. async function removeInterfaceIP(ip) {
  1812. if (!confirm(`Remove IP ${ip}?`)) return;
  1813. try {
  1814. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  1815. method: 'DELETE',
  1816. headers: { 'Content-Type': 'application/json' },
  1817. body: JSON.stringify({ ip })
  1818. });
  1819. if (res.ok) {
  1820. showToast('IP Removed', `Removed ${ip}`, 'success');
  1821. await fetchData(false);
  1822. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  1823. if (iface) renderModalIPs(iface);
  1824. }
  1825. } catch (err) {
  1826. showToast('Error', err.message, 'error');
  1827. }
  1828. }
  1829. async function saveInterfaceMetadata() {
  1830. const role = document.getElementById('modal-iface-role').value;
  1831. const desc = document.getElementById('modal-iface-desc').value.trim();
  1832. try {
  1833. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/metadata`, {
  1834. method: 'POST',
  1835. headers: { 'Content-Type': 'application/json' },
  1836. body: JSON.stringify({ role, description: desc })
  1837. });
  1838. if (res.ok) {
  1839. showToast('Saved', 'Metadata updated', 'success');
  1840. closeIfaceModal();
  1841. fetchData(false);
  1842. }
  1843. } catch (err) {
  1844. showToast('Error', err.message, 'error');
  1845. }
  1846. }
  1847. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  1848. state.fwSubTab = 'filter';
  1849. state.routesSubTab = 'routes';
  1850. function renderRuleFlag(disabled, hasComment) {
  1851. let flags = '';
  1852. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  1853. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  1854. return flags || '<span class="text-slate-600">-</span>';
  1855. }
  1856. function renderActionBadge(action) {
  1857. const act = (action || '').toLowerCase();
  1858. let color = 'bg-slate-800 text-slate-300';
  1859. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  1860. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  1861. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  1862. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  1863. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  1864. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  1865. }
  1866. function switchFWSubTab(tab) {
  1867. state.fwSubTab = tab;
  1868. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'connections'];
  1869. tabs.forEach(t => {
  1870. const panel = document.getElementById(`fw-subtab-${t}`);
  1871. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  1872. if (panel) {
  1873. if (t === tab) panel.classList.remove('hidden');
  1874. else panel.classList.add('hidden');
  1875. }
  1876. if (btn) {
  1877. if (t === tab) {
  1878. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-emerald-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  1879. } else {
  1880. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2 whitespace-nowrap';
  1881. }
  1882. }
  1883. });
  1884. const addBtn = document.getElementById('fw-primary-add-btn');
  1885. if (addBtn) {
  1886. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  1887. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  1888. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  1889. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  1890. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  1891. }
  1892. if (tab === 'connections') loadConnections();
  1893. }
  1894. function openCurrentFWModal() {
  1895. if (state.fwSubTab === 'filter') openAddFilterModal();
  1896. else if (state.fwSubTab === 'nat') openAddNATModal();
  1897. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  1898. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  1899. else if (state.fwSubTab === 'connections') loadConnections();
  1900. }
  1901. async function loadFirewall(populateDropdowns = true) {
  1902. try {
  1903. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes] = await Promise.all([
  1904. fetch(`${API_BASE}/firewall/summary`),
  1905. fetch(`${API_BASE}/firewall/filter`),
  1906. fetch(`${API_BASE}/firewall/nat`),
  1907. fetch(`${API_BASE}/firewall/mangle`),
  1908. fetch(`${API_BASE}/firewall/address-lists`)
  1909. ]);
  1910. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  1911. if (filterRes.ok) state.filterRules = await filterRes.json();
  1912. if (natRes.ok) state.natRules = await natRes.json();
  1913. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  1914. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  1915. // Badges
  1916. document.getElementById('fw-badge-filter').innerText = (state.filterRules || []).length;
  1917. document.getElementById('fw-badge-nat').innerText = (state.natRules || []).length;
  1918. document.getElementById('fw-badge-mangle').innerText = (state.mangleRules || []).length;
  1919. document.getElementById('fw-badge-addrlist').innerText = (state.addressLists || []).length;
  1920. renderFilterRules();
  1921. renderNATRules();
  1922. renderMangleRules();
  1923. renderAddressLists();
  1924. if (state.fwSubTab === 'connections') {
  1925. loadConnections();
  1926. }
  1927. } catch (err) {
  1928. console.error('Failed to load firewall:', err);
  1929. }
  1930. }
  1931. // ----------------- Filter Rules -----------------
  1932. function renderFilterRules() {
  1933. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  1934. const tbody = document.getElementById('filter-table-body');
  1935. const empty = document.getElementById('filter-empty');
  1936. if (!tbody) return;
  1937. tbody.innerHTML = '';
  1938. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  1939. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  1940. if (rules.length === 0) {
  1941. empty?.classList.remove('hidden');
  1942. return;
  1943. }
  1944. empty?.classList.add('hidden');
  1945. rules.forEach((r, idx) => {
  1946. const tr = document.createElement('tr');
  1947. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  1948. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  1949. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  1950. tr.innerHTML = `
  1951. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  1952. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  1953. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  1954. <td class="py-2.5 px-3 text-slate-300">${r.src_address || r.src_address_list ? (r.src_address || `list:${r.src_address_list}`) : '<span class="text-slate-600">0.0.0.0/0</span>'}</td>
  1955. <td class="py-2.5 px-3 text-slate-300">${r.dst_address || r.dst_address_list ? (r.dst_address || `list:${r.dst_address_list}`) : '<span class="text-slate-600">0.0.0.0/0</span>'}</td>
  1956. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  1957. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  1958. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  1959. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  1960. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  1961. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  1962. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  1963. </td>
  1964. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  1965. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  1966. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  1967. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  1968. <button onclick="toggleFilterRuleState('${r.id}', ${!r.disabled})" class="text-xs ${r.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${r.disabled ? 'Enable' : 'Disable'}</button>
  1969. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1970. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1971. </td>
  1972. `;
  1973. tbody.appendChild(tr);
  1974. });
  1975. }
  1976. function populateInterfaceSelect(selectId, currentVal = '') {
  1977. const sel = document.getElementById(selectId);
  1978. if (!sel) return;
  1979. sel.innerHTML = '<option value="">(Any Interface)</option>';
  1980. (state.interfaces || []).forEach(i => {
  1981. const opt = document.createElement('option');
  1982. opt.value = i.name;
  1983. opt.innerText = `${i.name} (${i.role || i.type})`;
  1984. if (i.name === currentVal) opt.selected = true;
  1985. sel.appendChild(opt);
  1986. });
  1987. }
  1988. function populateAddressListSelect(selectId, currentVal = '') {
  1989. const sel = document.getElementById(selectId);
  1990. if (!sel) return;
  1991. sel.innerHTML = '<option value="">(None)</option>';
  1992. const set = new Set((state.addressLists || []).map(a => a.name));
  1993. set.forEach(name => {
  1994. const opt = document.createElement('option');
  1995. opt.value = name;
  1996. opt.innerText = name;
  1997. if (name === currentVal) opt.selected = true;
  1998. sel.appendChild(opt);
  1999. });
  2000. }
  2001. function openAddFilterModal() {
  2002. document.getElementById('filter-modal-title').innerText = 'Add Firewall Filter Rule';
  2003. document.getElementById('filter-modal-id').value = '';
  2004. document.getElementById('filter-modal-chain').value = 'forward';
  2005. document.getElementById('filter-modal-action').value = 'accept';
  2006. document.getElementById('filter-modal-proto').value = 'all';
  2007. document.getElementById('filter-modal-src').value = '';
  2008. document.getElementById('filter-modal-dst').value = '';
  2009. document.getElementById('filter-modal-sport').value = '';
  2010. document.getElementById('filter-modal-dport').value = '';
  2011. document.getElementById('filter-modal-connmark').value = '';
  2012. document.getElementById('filter-modal-comment').value = '';
  2013. document.getElementById('filter-modal-disabled').checked = false;
  2014. document.getElementById('filter-modal-cs-established').checked = false;
  2015. document.getElementById('filter-modal-cs-related').checked = false;
  2016. document.getElementById('filter-modal-cs-new').checked = false;
  2017. document.getElementById('filter-modal-cs-invalid').checked = false;
  2018. populateInterfaceSelect('filter-modal-iniface');
  2019. populateInterfaceSelect('filter-modal-outiface');
  2020. populateAddressListSelect('filter-modal-srclist');
  2021. populateAddressListSelect('filter-modal-dstlist');
  2022. toggleFilterActionFields();
  2023. document.getElementById('filter-modal').classList.remove('hidden');
  2024. }
  2025. function openEditFilterModal(id) {
  2026. const r = (state.filterRules || []).find(rule => rule.id === id);
  2027. if (!r) return;
  2028. document.getElementById('filter-modal-title').innerText = `Edit Filter Rule (#${r.order})`;
  2029. document.getElementById('filter-modal-id').value = r.id;
  2030. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  2031. document.getElementById('filter-modal-action').value = r.action || 'accept';
  2032. document.getElementById('filter-modal-proto').value = r.protocol || 'all';
  2033. document.getElementById('filter-modal-src').value = r.src_address || '';
  2034. document.getElementById('filter-modal-dst').value = r.dst_address || '';
  2035. document.getElementById('filter-modal-sport').value = r.src_port || '';
  2036. document.getElementById('filter-modal-dport').value = r.dst_port || '';
  2037. document.getElementById('filter-modal-connmark').value = r.connection_mark || '';
  2038. document.getElementById('filter-modal-comment').value = r.comment || '';
  2039. document.getElementById('filter-modal-disabled').checked = !!r.disabled;
  2040. const states = r.connection_state || [];
  2041. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  2042. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  2043. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  2044. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  2045. populateInterfaceSelect('filter-modal-iniface', r.in_interface);
  2046. populateInterfaceSelect('filter-modal-outiface', r.out_interface);
  2047. populateAddressListSelect('filter-modal-srclist', r.src_address_list);
  2048. populateAddressListSelect('filter-modal-dstlist', r.dst_address_list);
  2049. toggleFilterActionFields();
  2050. document.getElementById('filter-modal').classList.remove('hidden');
  2051. }
  2052. function closeFilterModal() {
  2053. document.getElementById('filter-modal').classList.add('hidden');
  2054. }
  2055. function toggleFilterActionFields() {
  2056. const act = document.getElementById('filter-modal-action').value;
  2057. const rejectBox = document.getElementById('filter-action-reject-box');
  2058. if (rejectBox) {
  2059. if (act === 'reject') rejectBox.classList.remove('hidden');
  2060. else rejectBox.classList.add('hidden');
  2061. }
  2062. }
  2063. async function submitSaveFilterRule(e) {
  2064. e.preventDefault();
  2065. const id = document.getElementById('filter-modal-id').value;
  2066. const chain = document.getElementById('filter-modal-chain').value;
  2067. const action = document.getElementById('filter-modal-action').value;
  2068. const proto = document.getElementById('filter-modal-proto').value;
  2069. const src = document.getElementById('filter-modal-src').value.trim();
  2070. const dst = document.getElementById('filter-modal-dst').value.trim();
  2071. const sport = document.getElementById('filter-modal-sport').value.trim();
  2072. const dport = document.getElementById('filter-modal-dport').value.trim();
  2073. const inIface = document.getElementById('filter-modal-iniface').value;
  2074. const outIface = document.getElementById('filter-modal-outiface').value;
  2075. const connmark = document.getElementById('filter-modal-connmark').value.trim();
  2076. const srclist = document.getElementById('filter-modal-srclist').value;
  2077. const dstlist = document.getElementById('filter-modal-dstlist').value;
  2078. const comment = document.getElementById('filter-modal-comment').value.trim();
  2079. const disabled = document.getElementById('filter-modal-disabled').checked;
  2080. const rejectWith = document.getElementById('filter-modal-rejectwith')?.value || '';
  2081. const states = [];
  2082. if (document.getElementById('filter-modal-cs-established').checked) states.push('established');
  2083. if (document.getElementById('filter-modal-cs-related').checked) states.push('related');
  2084. if (document.getElementById('filter-modal-cs-new').checked) states.push('new');
  2085. if (document.getElementById('filter-modal-cs-invalid').checked) states.push('invalid');
  2086. try {
  2087. const res = await fetch(`${API_BASE}/firewall/filter`, {
  2088. method: 'POST',
  2089. headers: { 'Content-Type': 'application/json' },
  2090. body: JSON.stringify({
  2091. id,
  2092. chain,
  2093. action,
  2094. reject_with: rejectWith,
  2095. protocol: proto,
  2096. src_address: src,
  2097. dst_address: dst,
  2098. src_port: sport,
  2099. dst_port: dport,
  2100. in_interface: inIface,
  2101. out_interface: outIface,
  2102. connection_state: states,
  2103. connection_mark: connmark,
  2104. src_address_list: srclist,
  2105. dst_address_list: dstlist,
  2106. comment,
  2107. disabled
  2108. })
  2109. });
  2110. if (res.ok) {
  2111. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  2112. closeFilterModal();
  2113. loadFirewall(false);
  2114. } else {
  2115. const err = await res.json();
  2116. showToast('Error', err.message, 'error');
  2117. }
  2118. } catch (err) {
  2119. showToast('Error', err.message, 'error');
  2120. }
  2121. }
  2122. async function moveFilterRule(id, dir) {
  2123. try {
  2124. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  2125. method: 'POST',
  2126. headers: { 'Content-Type': 'application/json' },
  2127. body: JSON.stringify({ direction: dir })
  2128. });
  2129. if (res.ok) loadFirewall(false);
  2130. } catch (err) {
  2131. showToast('Error', err.message, 'error');
  2132. }
  2133. }
  2134. async function toggleFilterRuleState(id, disabled) {
  2135. try {
  2136. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  2137. method: 'POST',
  2138. headers: { 'Content-Type': 'application/json' },
  2139. body: JSON.stringify({ disabled })
  2140. });
  2141. if (res.ok) loadFirewall(false);
  2142. } catch (err) {
  2143. showToast('Error', err.message, 'error');
  2144. }
  2145. }
  2146. async function deleteFilterRule(id) {
  2147. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  2148. try {
  2149. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2150. if (res.ok) {
  2151. showToast('Deleted', 'Filter rule removed', 'success');
  2152. loadFirewall(false);
  2153. }
  2154. } catch (err) {
  2155. showToast('Error', err.message, 'error');
  2156. }
  2157. }
  2158. // ----------------- NAT Rules -----------------
  2159. function renderNATRules() {
  2160. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  2161. const tbody = document.getElementById('nat-table-body');
  2162. const empty = document.getElementById('nat-empty');
  2163. if (!tbody) return;
  2164. tbody.innerHTML = '';
  2165. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2166. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  2167. if (rules.length === 0) {
  2168. empty?.classList.remove('hidden');
  2169. return;
  2170. }
  2171. empty?.classList.add('hidden');
  2172. rules.forEach((r, idx) => {
  2173. const tr = document.createElement('tr');
  2174. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2175. const toTarget = [r.to_addresses, r.to_ports].filter(Boolean).join(':');
  2176. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  2177. tr.innerHTML = `
  2178. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2179. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2180. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  2181. <td class="py-2.5 px-3 text-slate-300">${r.src_address || '<span class="text-slate-600">0.0.0.0/0</span>'}</td>
  2182. <td class="py-2.5 px-3 text-slate-300">${r.dst_address || '<span class="text-slate-600">0.0.0.0/0</span>'}</td>
  2183. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  2184. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2185. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2186. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${toTarget || '-'}</td>
  2187. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2188. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2189. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2190. </td>
  2191. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2192. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2193. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2194. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2195. <button onclick="toggleNATRuleState('${r.id}', ${!r.disabled})" class="text-xs ${r.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${r.disabled ? 'Enable' : 'Disable'}</button>
  2196. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2197. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2198. </td>
  2199. `;
  2200. tbody.appendChild(tr);
  2201. });
  2202. }
  2203. function openAddNATModal() {
  2204. document.getElementById('nat-modal-title').innerText = 'Add NAT Rule';
  2205. document.getElementById('nat-modal-id').value = '';
  2206. document.getElementById('nat-modal-chain').value = 'srcnat';
  2207. document.getElementById('nat-modal-action').value = 'masquerade';
  2208. document.getElementById('nat-modal-toaddr').value = '';
  2209. document.getElementById('nat-modal-toport').value = '';
  2210. document.getElementById('nat-modal-proto').value = 'all';
  2211. document.getElementById('nat-modal-src').value = '';
  2212. document.getElementById('nat-modal-dst').value = '';
  2213. document.getElementById('nat-modal-dport').value = '';
  2214. document.getElementById('nat-modal-comment').value = '';
  2215. document.getElementById('nat-modal-disabled').checked = false;
  2216. populateInterfaceSelect('nat-modal-iniface');
  2217. populateInterfaceSelect('nat-modal-outiface');
  2218. toggleNATActionFields();
  2219. document.getElementById('nat-modal').classList.remove('hidden');
  2220. }
  2221. function openEditNATModal(id) {
  2222. const r = (state.natRules || []).find(rule => rule.id === id);
  2223. if (!r) return;
  2224. document.getElementById('nat-modal-title').innerText = `Edit NAT Rule (#${r.order})`;
  2225. document.getElementById('nat-modal-id').value = r.id;
  2226. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  2227. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  2228. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  2229. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  2230. document.getElementById('nat-modal-proto').value = r.protocol || 'all';
  2231. document.getElementById('nat-modal-src').value = r.src_address || '';
  2232. document.getElementById('nat-modal-dst').value = r.dst_address || '';
  2233. document.getElementById('nat-modal-dport').value = r.dst_port || '';
  2234. document.getElementById('nat-modal-comment').value = r.comment || '';
  2235. document.getElementById('nat-modal-disabled').checked = !!r.disabled;
  2236. populateInterfaceSelect('nat-modal-iniface', r.in_interface);
  2237. populateInterfaceSelect('nat-modal-outiface', r.out_interface);
  2238. toggleNATActionFields();
  2239. document.getElementById('nat-modal').classList.remove('hidden');
  2240. }
  2241. function closeNATModal() {
  2242. document.getElementById('nat-modal').classList.add('hidden');
  2243. }
  2244. function toggleNATChainFields() {
  2245. const ch = document.getElementById('nat-modal-chain').value;
  2246. const actSel = document.getElementById('nat-modal-action');
  2247. if (ch === 'srcnat' && actSel.value === 'dst-nat') {
  2248. actSel.value = 'masquerade';
  2249. } else if (ch === 'dstnat' && actSel.value === 'masquerade') {
  2250. actSel.value = 'dst-nat';
  2251. }
  2252. toggleNATActionFields();
  2253. }
  2254. function toggleNATActionFields() {
  2255. const act = document.getElementById('nat-modal-action').value;
  2256. const toBox = document.getElementById('nat-action-to-box');
  2257. if (toBox) {
  2258. if (act === 'masquerade' || act === 'accept') toBox.classList.add('hidden');
  2259. else toBox.classList.remove('hidden');
  2260. }
  2261. }
  2262. async function submitSaveNATRule(e) {
  2263. e.preventDefault();
  2264. const id = document.getElementById('nat-modal-id').value;
  2265. const chain = document.getElementById('nat-modal-chain').value;
  2266. const action = document.getElementById('nat-modal-action').value;
  2267. const toaddr = document.getElementById('nat-modal-toaddr').value.trim();
  2268. const toport = document.getElementById('nat-modal-toport').value.trim();
  2269. const proto = document.getElementById('nat-modal-proto').value;
  2270. const src = document.getElementById('nat-modal-src').value.trim();
  2271. const dst = document.getElementById('nat-modal-dst').value.trim();
  2272. const dport = document.getElementById('nat-modal-dport').value.trim();
  2273. const inIface = document.getElementById('nat-modal-iniface').value;
  2274. const outIface = document.getElementById('nat-modal-outiface').value;
  2275. const comment = document.getElementById('nat-modal-comment').value.trim();
  2276. const disabled = document.getElementById('nat-modal-disabled').checked;
  2277. try {
  2278. const res = await fetch(`${API_BASE}/firewall/nat`, {
  2279. method: 'POST',
  2280. headers: { 'Content-Type': 'application/json' },
  2281. body: JSON.stringify({
  2282. id,
  2283. chain,
  2284. action,
  2285. to_addresses: toaddr,
  2286. to_ports: toport,
  2287. protocol: proto,
  2288. src_address: src,
  2289. dst_address: dst,
  2290. dst_port: dport,
  2291. in_interface: inIface,
  2292. out_interface: outIface,
  2293. comment,
  2294. disabled
  2295. })
  2296. });
  2297. if (res.ok) {
  2298. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  2299. closeNATModal();
  2300. loadFirewall(false);
  2301. }
  2302. } catch (err) {
  2303. showToast('Error', err.message, 'error');
  2304. }
  2305. }
  2306. async function moveNATRule(id, dir) {
  2307. try {
  2308. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  2309. method: 'POST',
  2310. headers: { 'Content-Type': 'application/json' },
  2311. body: JSON.stringify({ direction: dir })
  2312. });
  2313. if (res.ok) loadFirewall(false);
  2314. } catch (err) {
  2315. showToast('Error', err.message, 'error');
  2316. }
  2317. }
  2318. async function toggleNATRuleState(id, disabled) {
  2319. try {
  2320. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  2321. method: 'POST',
  2322. headers: { 'Content-Type': 'application/json' },
  2323. body: JSON.stringify({ disabled })
  2324. });
  2325. if (res.ok) loadFirewall(false);
  2326. } catch (err) {
  2327. showToast('Error', err.message, 'error');
  2328. }
  2329. }
  2330. async function deleteNATRule(id) {
  2331. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  2332. try {
  2333. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2334. if (res.ok) {
  2335. showToast('Deleted', 'NAT rule removed', 'success');
  2336. loadFirewall(false);
  2337. }
  2338. } catch (err) {
  2339. showToast('Error', err.message, 'error');
  2340. }
  2341. }
  2342. // ----------------- Mangle Rules -----------------
  2343. function renderMangleRules() {
  2344. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  2345. const tbody = document.getElementById('mangle-table-body');
  2346. const empty = document.getElementById('mangle-empty');
  2347. if (!tbody) return;
  2348. tbody.innerHTML = '';
  2349. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2350. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  2351. if (rules.length === 0) {
  2352. empty?.classList.remove('hidden');
  2353. return;
  2354. }
  2355. empty?.classList.add('hidden');
  2356. rules.forEach((r, idx) => {
  2357. const tr = document.createElement('tr');
  2358. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2359. const markVal = r.new_connection_mark || r.new_routing_mark || r.new_packet_mark || r.new_mss || (r.new_dscp ? 'DSCP:' + r.new_dscp : '');
  2360. tr.innerHTML = `
  2361. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2362. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2363. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  2364. <td class="py-2.5 px-3 text-slate-300">${r.src_address || '<span class="text-slate-600">0.0.0.0/0</span>'}</td>
  2365. <td class="py-2.5 px-3 text-slate-300">${r.dst_address || '<span class="text-slate-600">0.0.0.0/0</span>'}</td>
  2366. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2367. <td class="py-2.5 px-3 font-mono font-bold text-cyan-300">${markVal || '-'}</td>
  2368. <td class="py-2.5 px-3 text-center">${r.passthrough ? '<span class="text-emerald-400">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  2369. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2370. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2371. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2372. </td>
  2373. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2374. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2375. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2376. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2377. <button onclick="toggleMangleRuleState('${r.id}', ${!r.disabled})" class="text-xs ${r.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${r.disabled ? 'Enable' : 'Disable'}</button>
  2378. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2379. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2380. </td>
  2381. `;
  2382. tbody.appendChild(tr);
  2383. });
  2384. }
  2385. function openAddMangleModal() {
  2386. document.getElementById('mangle-modal-title').innerText = 'Add Mangle Rule';
  2387. document.getElementById('mangle-modal-id').value = '';
  2388. document.getElementById('mangle-modal-chain').value = 'prerouting';
  2389. document.getElementById('mangle-modal-action').value = 'mark-connection';
  2390. document.getElementById('mangle-modal-newmark').value = '';
  2391. document.getElementById('mangle-modal-passthrough').checked = true;
  2392. document.getElementById('mangle-modal-src').value = '';
  2393. document.getElementById('mangle-modal-dst').value = '';
  2394. document.getElementById('mangle-modal-connmark').value = '';
  2395. document.getElementById('mangle-modal-comment').value = '';
  2396. document.getElementById('mangle-modal-disabled').checked = false;
  2397. populateInterfaceSelect('mangle-modal-iniface');
  2398. document.getElementById('mangle-modal').classList.remove('hidden');
  2399. }
  2400. function openEditMangleModal(id) {
  2401. const r = (state.mangleRules || []).find(rule => rule.id === id);
  2402. if (!r) return;
  2403. document.getElementById('mangle-modal-title').innerText = `Edit Mangle Rule (#${r.order})`;
  2404. document.getElementById('mangle-modal-id').value = r.id;
  2405. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  2406. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  2407. document.getElementById('mangle-modal-newmark').value = r.new_connection_mark || r.new_routing_mark || r.new_packet_mark || r.new_mss || '';
  2408. document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  2409. document.getElementById('mangle-modal-src').value = r.src_address || '';
  2410. document.getElementById('mangle-modal-dst').value = r.dst_address || '';
  2411. document.getElementById('mangle-modal-connmark').value = r.connection_mark || '';
  2412. document.getElementById('mangle-modal-comment').value = r.comment || '';
  2413. document.getElementById('mangle-modal-disabled').checked = !!r.disabled;
  2414. populateInterfaceSelect('mangle-modal-iniface', r.in_interface);
  2415. document.getElementById('mangle-modal').classList.remove('hidden');
  2416. }
  2417. function closeMangleModal() {
  2418. document.getElementById('mangle-modal').classList.add('hidden');
  2419. }
  2420. function toggleMangleActionFields() {
  2421. // Handled smoothly by single dynamic input
  2422. }
  2423. async function submitSaveMangleRule(e) {
  2424. e.preventDefault();
  2425. const id = document.getElementById('mangle-modal-id').value;
  2426. const chain = document.getElementById('mangle-modal-chain').value;
  2427. const action = document.getElementById('mangle-modal-action').value;
  2428. const newmark = document.getElementById('mangle-modal-newmark').value.trim();
  2429. const passthrough = document.getElementById('mangle-modal-passthrough').checked;
  2430. const src = document.getElementById('mangle-modal-src').value.trim();
  2431. const dst = document.getElementById('mangle-modal-dst').value.trim();
  2432. const inIface = document.getElementById('mangle-modal-iniface').value;
  2433. const connmark = document.getElementById('mangle-modal-connmark').value.trim();
  2434. const comment = document.getElementById('mangle-modal-comment').value.trim();
  2435. const disabled = document.getElementById('mangle-modal-disabled').checked;
  2436. const payload = {
  2437. id,
  2438. chain,
  2439. action,
  2440. passthrough,
  2441. src_address: src,
  2442. dst_address: dst,
  2443. in_interface: inIface,
  2444. connection_mark: connmark,
  2445. comment,
  2446. disabled
  2447. };
  2448. if (action === 'mark-connection') payload.new_connection_mark = newmark;
  2449. else if (action === 'mark-routing') payload.new_routing_mark = newmark;
  2450. else if (action === 'mark-packet') payload.new_packet_mark = newmark;
  2451. else if (action === 'change-mss') payload.new_mss = newmark || 'clamp-to-pmtu';
  2452. try {
  2453. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  2454. method: 'POST',
  2455. headers: { 'Content-Type': 'application/json' },
  2456. body: JSON.stringify(payload)
  2457. });
  2458. if (res.ok) {
  2459. showToast('Mangle Rule Saved', 'Marking rule applied', 'success');
  2460. closeMangleModal();
  2461. loadFirewall(false);
  2462. }
  2463. } catch (err) {
  2464. showToast('Error', err.message, 'error');
  2465. }
  2466. }
  2467. async function moveMangleRule(id, dir) {
  2468. try {
  2469. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  2470. method: 'POST',
  2471. headers: { 'Content-Type': 'application/json' },
  2472. body: JSON.stringify({ direction: dir })
  2473. });
  2474. if (res.ok) loadFirewall(false);
  2475. } catch (err) {
  2476. showToast('Error', err.message, 'error');
  2477. }
  2478. }
  2479. async function toggleMangleRuleState(id, disabled) {
  2480. try {
  2481. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  2482. method: 'POST',
  2483. headers: { 'Content-Type': 'application/json' },
  2484. body: JSON.stringify({ disabled })
  2485. });
  2486. if (res.ok) loadFirewall(false);
  2487. } catch (err) {
  2488. showToast('Error', err.message, 'error');
  2489. }
  2490. }
  2491. async function deleteMangleRule(id) {
  2492. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  2493. try {
  2494. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2495. if (res.ok) {
  2496. showToast('Deleted', 'Mangle rule removed', 'success');
  2497. loadFirewall(false);
  2498. }
  2499. } catch (err) {
  2500. showToast('Error', err.message, 'error');
  2501. }
  2502. }
  2503. // ----------------- Address Lists -----------------
  2504. function renderAddressLists() {
  2505. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  2506. const tbody = document.getElementById('addrlist-table-body');
  2507. const empty = document.getElementById('addrlist-empty');
  2508. if (!tbody) return;
  2509. tbody.innerHTML = '';
  2510. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  2511. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  2512. // Update filter select
  2513. const sel = document.getElementById('addrlist-filter-name');
  2514. if (sel) {
  2515. const cur = sel.value;
  2516. sel.innerHTML = '<option value="">All Lists</option>';
  2517. const set = new Set((state.addressLists || []).map(a => a.name));
  2518. set.forEach(n => {
  2519. const opt = document.createElement('option');
  2520. opt.value = n;
  2521. opt.innerText = n;
  2522. if (n === cur) opt.selected = true;
  2523. sel.appendChild(opt);
  2524. });
  2525. }
  2526. if (entries.length === 0) {
  2527. empty?.classList.remove('hidden');
  2528. return;
  2529. }
  2530. empty?.classList.add('hidden');
  2531. entries.forEach((e, idx) => {
  2532. const tr = document.createElement('tr');
  2533. tr.className = `hover:bg-slate-800/40 transition text-xs ${e.disabled ? 'opacity-50' : ''}`;
  2534. tr.innerHTML = `
  2535. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  2536. <td class="py-2.5 px-3 text-center">${e.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-slate-600">-</span>'}</td>
  2537. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  2538. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  2539. <td class="py-2.5 px-3 text-slate-400 italic">${e.comment || '-'}</td>
  2540. <td class="py-2.5 px-3 text-right font-sans">
  2541. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2542. </td>
  2543. `;
  2544. tbody.appendChild(tr);
  2545. });
  2546. }
  2547. function openAddAddrListModal() {
  2548. document.getElementById('addrlist-modal-name').value = '';
  2549. document.getElementById('addrlist-modal-addr').value = '';
  2550. document.getElementById('addrlist-modal-comment').value = '';
  2551. document.getElementById('addrlist-modal').classList.remove('hidden');
  2552. }
  2553. function closeAddrListModal() {
  2554. document.getElementById('addrlist-modal').classList.add('hidden');
  2555. }
  2556. async function submitSaveAddrList(e) {
  2557. e.preventDefault();
  2558. const name = document.getElementById('addrlist-modal-name').value.trim();
  2559. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  2560. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  2561. try {
  2562. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  2563. method: 'POST',
  2564. headers: { 'Content-Type': 'application/json' },
  2565. body: JSON.stringify({ name, address: addr, comment, disabled: false })
  2566. });
  2567. if (res.ok) {
  2568. showToast('Address List Item Added', `Added ${addr} to ${name}`, 'success');
  2569. closeAddrListModal();
  2570. loadFirewall(false);
  2571. }
  2572. } catch (err) {
  2573. showToast('Error', err.message, 'error');
  2574. }
  2575. }
  2576. async function deleteAddrList(id) {
  2577. try {
  2578. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2579. if (res.ok) {
  2580. showToast('Deleted', 'Address list item removed', 'info');
  2581. loadFirewall(false);
  2582. }
  2583. } catch (err) {
  2584. showToast('Error', err.message, 'error');
  2585. }
  2586. }
  2587. // ----------------- Active Connections Tracking -----------------
  2588. async function loadConnections() {
  2589. try {
  2590. const res = await fetch(`${API_BASE}/firewall/connections`);
  2591. const data = await res.json();
  2592. state.connections = Array.isArray(data) ? data : [];
  2593. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  2594. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  2595. renderConnections();
  2596. } catch (err) {
  2597. console.error('Failed to load connections:', err);
  2598. }
  2599. }
  2600. function renderConnections() {
  2601. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  2602. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  2603. const tbody = document.getElementById('conns-table-body');
  2604. const empty = document.getElementById('conns-empty');
  2605. if (!tbody) return;
  2606. tbody.innerHTML = '';
  2607. const conns = (state.connections || []).filter(c => {
  2608. if (protoFilter && c.protocol !== protoFilter) return false;
  2609. if (search) {
  2610. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  2611. if (!line.includes(search)) return false;
  2612. }
  2613. return true;
  2614. });
  2615. if (conns.length === 0) {
  2616. empty?.classList.remove('hidden');
  2617. return;
  2618. }
  2619. empty?.classList.add('hidden');
  2620. conns.slice(0, 150).forEach(c => {
  2621. const tr = document.createElement('tr');
  2622. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2623. let stateColor = 'text-slate-400';
  2624. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  2625. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  2626. tr.innerHTML = `
  2627. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  2628. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  2629. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  2630. <td class="py-2.5 px-3 font-mono text-slate-400">${c.reply_src_address ? c.reply_src_address + ':' + c.reply_src_port : '-'}</td>
  2631. <td class="py-2.5 px-3 font-mono text-slate-400">${c.reply_dst_address ? c.reply_dst_address + ':' + c.reply_dst_port : '-'}</td>
  2632. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  2633. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  2634. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  2635. <td class="py-2.5 px-3 text-right font-sans">
  2636. <button onclick="killConnection('${c.protocol}', '${c.src_address}', ${c.src_port}, '${c.dst_address}', ${c.dst_port})" class="text-xs text-rose-400 hover:text-rose-300">Kill</button>
  2637. </td>
  2638. `;
  2639. tbody.appendChild(tr);
  2640. });
  2641. }
  2642. async function killConnection(protocol, src, sport, dst, dport) {
  2643. try {
  2644. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  2645. method: 'POST',
  2646. headers: { 'Content-Type': 'application/json' },
  2647. body: JSON.stringify({ protocol, src, sport, dst, dport })
  2648. });
  2649. if (res.ok) {
  2650. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  2651. loadConnections();
  2652. }
  2653. } catch (err) {
  2654. showToast('Error', err.message, 'error');
  2655. }
  2656. }
  2657. async function resetFirewallCounters() {
  2658. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  2659. try {
  2660. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  2661. if (res.ok) {
  2662. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  2663. loadFirewall(false);
  2664. }
  2665. } catch (err) {
  2666. showToast('Error', err.message, 'error');
  2667. }
  2668. }
  2669. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  2670. function switchRoutesSubTab(tab) {
  2671. state.routesSubTab = tab;
  2672. const tabs = ['routes', 'rules', 'tables'];
  2673. tabs.forEach(t => {
  2674. const panel = document.getElementById(`routes-subtab-${t}`);
  2675. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  2676. if (panel) {
  2677. if (t === tab) panel.classList.remove('hidden');
  2678. else panel.classList.add('hidden');
  2679. }
  2680. if (btn) {
  2681. if (t === tab) {
  2682. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-cyan-500 text-white transition flex items-center gap-2';
  2683. } else {
  2684. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  2685. }
  2686. }
  2687. });
  2688. }
  2689. async function loadRoutes() {
  2690. try {
  2691. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  2692. fetch(`${API_BASE}/routes`),
  2693. fetch(`${API_BASE}/routing/rules`),
  2694. fetch(`${API_BASE}/routing/tables`)
  2695. ]);
  2696. if (routesRes.ok) state.routes = await routesRes.json();
  2697. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  2698. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  2699. document.getElementById('routes-badge-routes').innerText = (state.routes || []).length;
  2700. document.getElementById('routes-badge-rules').innerText = (state.policyRules || []).length;
  2701. document.getElementById('routes-badge-tables').innerText = (state.routingTables || []).length;
  2702. document.getElementById('badge-routes-count').innerText = (state.routes || []).length;
  2703. renderRoutesList();
  2704. renderPolicyRules();
  2705. renderRoutingTables();
  2706. } catch (err) {
  2707. console.error('Failed to load routing:', err);
  2708. }
  2709. }
  2710. function renderRoutesList() {
  2711. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  2712. const tbody = document.getElementById('routes-table-body');
  2713. const empty = document.getElementById('routes-empty');
  2714. if (!tbody) return;
  2715. tbody.innerHTML = '';
  2716. // Update table filter select
  2717. const sel = document.getElementById('routes-filter-table');
  2718. if (sel) {
  2719. const cur = sel.value;
  2720. sel.innerHTML = '<option value="">All Tables</option>';
  2721. (state.routingTables || []).forEach(t => {
  2722. const opt = document.createElement('option');
  2723. opt.value = t.name;
  2724. opt.innerText = t.name;
  2725. if (t.name === cur) opt.selected = true;
  2726. sel.appendChild(opt);
  2727. });
  2728. }
  2729. const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
  2730. document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
  2731. if (routes.length === 0) {
  2732. empty?.classList.remove('hidden');
  2733. return;
  2734. }
  2735. empty?.classList.add('hidden');
  2736. routes.forEach(r => {
  2737. const tr = document.createElement('tr');
  2738. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2739. // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
  2740. let flags = '';
  2741. if (r.dynamic) flags += 'D';
  2742. if (r.active) flags += 'A';
  2743. if (r.connect) flags += 'C';
  2744. if (r.static) flags += 'S';
  2745. if (r.disabled) flags += 'X';
  2746. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  2747. tr.innerHTML = `
  2748. <td class="py-2.5 px-3 text-center">
  2749. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${r.active ? 'text-cyan-400 border border-cyan-800/40' : 'text-slate-500'}">
  2750. ${flags || '-'}
  2751. </span>
  2752. </td>
  2753. <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
  2754. <td class="py-2.5 px-3 text-slate-300 font-mono">${r.gateway || '<span class="text-slate-600 font-sans">Direct link</span>'}</td>
  2755. <td class="py-2.5 px-3 text-slate-400 font-mono">${r.distance || 1}</td>
  2756. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  2757. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  2758. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  2759. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  2760. ${r.static ? `
  2761. <button onclick="toggleRouteState('${r.id}', ${!r.disabled})" class="text-xs ${r.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${r.disabled ? 'Enable' : 'Disable'}</button>
  2762. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2763. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2764. ` : `<span class="text-slate-600 text-[10px]">Kernel</span>`}
  2765. </td>
  2766. `;
  2767. tbody.appendChild(tr);
  2768. });
  2769. }
  2770. function openAddRouteModal() {
  2771. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  2772. document.getElementById('route-modal-id').value = '';
  2773. document.getElementById('route-modal-dst').value = '0.0.0.0/0';
  2774. document.getElementById('route-modal-gw').value = '';
  2775. document.getElementById('route-modal-distance').value = '1';
  2776. document.getElementById('route-modal-comment').value = '';
  2777. document.getElementById('route-modal-disabled').checked = false;
  2778. populateInterfaceSelect('route-modal-iface');
  2779. // Populate tables
  2780. const sel = document.getElementById('route-modal-table');
  2781. sel.innerHTML = '';
  2782. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  2783. const opt = document.createElement('option');
  2784. opt.value = t.name;
  2785. opt.innerText = t.name;
  2786. if (t.name === 'main') opt.selected = true;
  2787. sel.appendChild(opt);
  2788. });
  2789. document.getElementById('route-modal').classList.remove('hidden');
  2790. }
  2791. function openEditRouteModal(id) {
  2792. const r = (state.routes || []).find(route => route.id === id);
  2793. if (!r) return;
  2794. document.getElementById('route-modal-title').innerText = `Edit Route: ${r.dst_address}`;
  2795. document.getElementById('route-modal-id').value = r.id;
  2796. document.getElementById('route-modal-dst').value = r.dst_address;
  2797. document.getElementById('route-modal-gw').value = r.gateway || '';
  2798. document.getElementById('route-modal-distance').value = r.distance || 1;
  2799. document.getElementById('route-modal-comment').value = r.comment || '';
  2800. document.getElementById('route-modal-disabled').checked = !!r.disabled;
  2801. populateInterfaceSelect('route-modal-iface', r.interface);
  2802. const sel = document.getElementById('route-modal-table');
  2803. sel.innerHTML = '';
  2804. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  2805. const opt = document.createElement('option');
  2806. opt.value = t.name;
  2807. opt.innerText = t.name;
  2808. if (t.name === r.routing_table) opt.selected = true;
  2809. sel.appendChild(opt);
  2810. });
  2811. document.getElementById('route-modal').classList.remove('hidden');
  2812. }
  2813. function closeRouteModal() {
  2814. document.getElementById('route-modal').classList.add('hidden');
  2815. }
  2816. async function submitSaveRoute(e) {
  2817. e.preventDefault();
  2818. const id = document.getElementById('route-modal-id').value;
  2819. const dst = document.getElementById('route-modal-dst').value.trim();
  2820. const gw = document.getElementById('route-modal-gw').value.trim();
  2821. const table = document.getElementById('route-modal-table').value;
  2822. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 1;
  2823. const iface = document.getElementById('route-modal-iface').value;
  2824. const comment = document.getElementById('route-modal-comment').value.trim();
  2825. const disabled = document.getElementById('route-modal-disabled').checked;
  2826. try {
  2827. const res = await fetch(`${API_BASE}/routes`, {
  2828. method: 'POST',
  2829. headers: { 'Content-Type': 'application/json' },
  2830. body: JSON.stringify({
  2831. id,
  2832. dst_address: dst,
  2833. gateway: gw,
  2834. routing_table: table,
  2835. distance,
  2836. interface: iface,
  2837. comment,
  2838. disabled
  2839. })
  2840. });
  2841. if (res.ok) {
  2842. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  2843. closeRouteModal();
  2844. loadRoutes();
  2845. } else {
  2846. const err = await res.json();
  2847. showToast('Error', err.message, 'error');
  2848. }
  2849. } catch (err) {
  2850. showToast('Error', err.message, 'error');
  2851. }
  2852. }
  2853. async function toggleRouteState(id, disabled) {
  2854. try {
  2855. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  2856. method: 'POST',
  2857. headers: { 'Content-Type': 'application/json' },
  2858. body: JSON.stringify({ disabled })
  2859. });
  2860. if (res.ok) loadRoutes();
  2861. } catch (err) {
  2862. showToast('Error', err.message, 'error');
  2863. }
  2864. }
  2865. async function deleteRoute(id) {
  2866. if (!confirm('Are you sure you want to delete this route?')) return;
  2867. try {
  2868. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2869. if (res.ok) {
  2870. showToast('Deleted', 'Route removed', 'success');
  2871. loadRoutes();
  2872. }
  2873. } catch (err) {
  2874. showToast('Error', err.message, 'error');
  2875. }
  2876. }
  2877. // ----------------- Policy Rules (/ip route rule) -----------------
  2878. function renderPolicyRules() {
  2879. const tbody = document.getElementById('rules-table-body');
  2880. const empty = document.getElementById('rules-empty');
  2881. if (!tbody) return;
  2882. tbody.innerHTML = '';
  2883. const rules = state.policyRules || [];
  2884. document.getElementById('rules-count-badge').innerText = `${rules.length} Rules`;
  2885. if (rules.length === 0) {
  2886. empty?.classList.remove('hidden');
  2887. return;
  2888. }
  2889. empty?.classList.add('hidden');
  2890. rules.forEach(pr => {
  2891. const tr = document.createElement('tr');
  2892. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2893. tr.innerHTML = `
  2894. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  2895. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  2896. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  2897. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  2898. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  2899. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  2900. <td class="py-2.5 px-3 text-right font-sans">
  2901. ${pr.priority < 32766 && pr.priority > 0 ? `
  2902. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2903. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  2904. </td>
  2905. `;
  2906. tbody.appendChild(tr);
  2907. });
  2908. }
  2909. function openAddPolicyRuleModal() {
  2910. document.getElementById('prule-modal-pref').value = (state.policyRules || []).length * 10 + 1000;
  2911. document.getElementById('prule-modal-mark').value = '';
  2912. document.getElementById('prule-modal-src').value = '';
  2913. document.getElementById('prule-modal-dst').value = '';
  2914. const sel = document.getElementById('prule-modal-table');
  2915. sel.innerHTML = '';
  2916. (state.routingTables || []).forEach(t => {
  2917. const opt = document.createElement('option');
  2918. opt.value = t.name;
  2919. opt.innerText = t.name;
  2920. sel.appendChild(opt);
  2921. });
  2922. document.getElementById('prule-modal').classList.remove('hidden');
  2923. }
  2924. function closePolicyRuleModal() {
  2925. document.getElementById('prule-modal').classList.add('hidden');
  2926. }
  2927. async function submitSavePolicyRule(e) {
  2928. e.preventDefault();
  2929. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  2930. const mark = document.getElementById('prule-modal-mark').value.trim();
  2931. const src = document.getElementById('prule-modal-src').value.trim();
  2932. const dst = document.getElementById('prule-modal-dst').value.trim();
  2933. const table = document.getElementById('prule-modal-table').value;
  2934. const action = document.getElementById('prule-modal-action').value;
  2935. try {
  2936. const res = await fetch(`${API_BASE}/routing/rules`, {
  2937. method: 'POST',
  2938. headers: { 'Content-Type': 'application/json' },
  2939. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  2940. });
  2941. if (res.ok) {
  2942. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  2943. closePolicyRuleModal();
  2944. loadRoutes();
  2945. } else {
  2946. const err = await res.json();
  2947. showToast('Error', err.message, 'error');
  2948. }
  2949. } catch (err) {
  2950. showToast('Error', err.message, 'error');
  2951. }
  2952. }
  2953. async function deletePolicyRule(id) {
  2954. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  2955. try {
  2956. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2957. if (res.ok) {
  2958. showToast('Rule Removed', 'Policy rule deleted', 'success');
  2959. loadRoutes();
  2960. }
  2961. } catch (err) {
  2962. showToast('Error', err.message, 'error');
  2963. }
  2964. }
  2965. // ----------------- Routing Tables -----------------
  2966. function renderRoutingTables() {
  2967. const tbody = document.getElementById('tables-table-body');
  2968. if (!tbody) return;
  2969. tbody.innerHTML = '';
  2970. (state.routingTables || []).forEach(t => {
  2971. const tr = document.createElement('tr');
  2972. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  2973. tr.innerHTML = `
  2974. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  2975. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  2976. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  2977. `;
  2978. tbody.appendChild(tr);
  2979. });
  2980. }
  2981. function openAddTableModal() {
  2982. document.getElementById('table-modal-name').value = '';
  2983. document.getElementById('table-modal-id').value = '';
  2984. document.getElementById('table-modal-comment').value = '';
  2985. document.getElementById('table-modal').classList.remove('hidden');
  2986. }
  2987. function closeTableModal() {
  2988. document.getElementById('table-modal').classList.add('hidden');
  2989. }
  2990. async function submitSaveTable(e) {
  2991. e.preventDefault();
  2992. const name = document.getElementById('table-modal-name').value.trim();
  2993. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  2994. const comment = document.getElementById('table-modal-comment').value.trim();
  2995. try {
  2996. const res = await fetch(`${API_BASE}/routing/tables`, {
  2997. method: 'POST',
  2998. headers: { 'Content-Type': 'application/json' },
  2999. body: JSON.stringify({ name, table_id: id, comment })
  3000. });
  3001. if (res.ok) {
  3002. showToast('Table Created', `Routing table ${name} registered`, 'success');
  3003. closeTableModal();
  3004. loadRoutes();
  3005. } else {
  3006. const err = await res.json();
  3007. showToast('Error', err.message, 'error');
  3008. }
  3009. } catch (err) {
  3010. showToast('Error', err.message, 'error');
  3011. }
  3012. }
  3013. async function loadDebianConfig() {
  3014. const view = document.getElementById('debian-config-view');
  3015. view.innerText = 'Generating live configuration...';
  3016. try {
  3017. const res = await fetch(`${API_BASE}/debian/config`);
  3018. const data = await res.json();
  3019. view.innerText = data.content || '# Empty config';
  3020. } catch (err) {
  3021. view.innerText = 'Failed to generate Debian network config.';
  3022. }
  3023. }
  3024. async function saveDebianConfig() {
  3025. try {
  3026. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  3027. const data = await res.json();
  3028. if (res.ok) {
  3029. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  3030. loadDebianConfig();
  3031. }
  3032. } catch (err) {
  3033. showToast('Error', err.message, 'error');
  3034. }
  3035. }
  3036. function showToast(title, message, type = 'info') {
  3037. const container = document.getElementById('toast-container');
  3038. const toast = document.createElement('div');
  3039. const borderColors = {
  3040. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  3041. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  3042. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  3043. };
  3044. toast.className = `pointer-events-auto border rounded-xl p-4 shadow-2xl backdrop-blur-md flex items-start space-x-3 w-80 transform transition-all duration-300 translate-y-2 opacity-0 ${borderColors[type] || borderColors.info}`;
  3045. toast.innerHTML = `
  3046. <div class="flex-1">
  3047. <div class="font-bold text-xs text-white">${title}</div>
  3048. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  3049. </div>
  3050. `;
  3051. container.appendChild(toast);
  3052. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  3053. setTimeout(() => {
  3054. toast.classList.add('opacity-0', 'translate-y-2');
  3055. setTimeout(() => toast.remove(), 300);
  3056. }, 4000);
  3057. }
  3058. function formatTraffic(bytesPerSec) {
  3059. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  3060. const kb = bytesPerSec / 1024;
  3061. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  3062. const mb = kb / 1024;
  3063. return `${mb.toFixed(2)} MB/s`;
  3064. }
  3065. function toggleSidebar() {
  3066. const sb = document.getElementById('sidebar');
  3067. sb.classList.toggle('-translate-x-full');
  3068. }