app.js 177 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281
  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. fwSubTab: 'filter',
  10. routesSubTab: 'routes',
  11. pppSubTab: 'secrets',
  12. eoipTunnels: [],
  13. pppSecrets: [],
  14. pppProfiles: [],
  15. pppActiveSessions: [],
  16. pppoeServer: null,
  17. pptpServer: null,
  18. l2tpServer: null,
  19. ipsecServer: null,
  20. ifaceFilter: 'all',
  21. currentModalIface: null,
  22. isPolling: true,
  23. expandedParents: new Set(['eth0']),
  24. pppoeData: null,
  25. wgData: null,
  26. ipsecData: null,
  27. l2tpData: null,
  28. pptpData: null,
  29. fwSummary: null,
  30. filterRules: [],
  31. natRules: [],
  32. mangleRules: [],
  33. addressLists: [],
  34. connections: [],
  35. policyRules: [],
  36. routingTables: []
  37. };
  38. const API_BASE = '/api';
  39. // Initialize on page load
  40. document.addEventListener('DOMContentLoaded', () => {
  41. const hash = window.location.hash.replace('#', '') || 'dashboard';
  42. navigate(hash);
  43. fetchData();
  44. // Live polling every 2.5 seconds
  45. setInterval(() => {
  46. if (state.isPolling) {
  47. fetchData(false);
  48. }
  49. }, 2500);
  50. });
  51. // Navigation Handler
  52. function navigate(tabName) {
  53. state.activeTab = tabName;
  54. window.location.hash = tabName;
  55. // Update nav links styling
  56. document.querySelectorAll('.nav-link').forEach(link => {
  57. 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';
  58. });
  59. const activeNav = document.getElementById(`nav-${tabName}`);
  60. if (activeNav) {
  61. 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';
  62. }
  63. // Update page headers
  64. const titles = {
  65. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  66. interfaces: { title: 'Network Interfaces', sub: 'Hierarchical view of physical interfaces and nested 802.1Q VLANs' },
  67. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  68. firewall: { title: 'MikroTik Firewall', sub: 'Filter rules, NAT, Mangle, Address Lists & Active Connections tracking' },
  69. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  70. ppp: { title: 'PPP Servers & Secrets', sub: 'MikroTik RouterOS user accounts, IP pools and VPN server concentrators' },
  71. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP Layer 2 tunneling (MikroTik RouterOS style)' },
  72. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  73. wireguard: { title: 'WireGuard Kernel VPN', sub: 'Modern ultra-fast cryptographic VPN tunnel manager' },
  74. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  75. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  76. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  77. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' }
  78. };
  79. const header = titles[tabName] || titles.dashboard;
  80. const pTitle = document.getElementById('page-title');
  81. if (pTitle) pTitle.innerText = header.title;
  82. const pSub = document.getElementById('page-subtitle');
  83. if (pSub) pSub.innerText = header.sub;
  84. // Toggle sections dynamically for all section elements
  85. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  86. if (el.id === `section-${tabName}`) {
  87. el.classList.remove('hidden');
  88. } else {
  89. el.classList.add('hidden');
  90. }
  91. });
  92. if (tabName === 'firewall') loadFirewall();
  93. if (tabName === 'routes') loadRoutes();
  94. if (tabName === 'ppp') loadPPP();
  95. if (tabName === 'eoip') loadEoIP();
  96. if (tabName === 'persistence') loadDebianConfig();
  97. if (tabName === 'pppoe') loadPPPoE();
  98. if (tabName === 'wireguard') loadWireGuard();
  99. if (tabName === 'ipsec') loadIPSec();
  100. if (tabName === 'l2tp') loadL2TP();
  101. if (tabName === 'pptp') loadPPTP();
  102. }
  103. // Fetch all core system, network and VPN telemetry
  104. async function fetchData(isManual = false) {
  105. const spinner = document.getElementById('refresh-spinner');
  106. if (isManual && spinner) spinner.classList.add('animate-spin');
  107. try {
  108. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes] = await Promise.all([
  109. fetch(`${API_BASE}/system/status`),
  110. fetch(`${API_BASE}/interfaces`),
  111. fetch(`${API_BASE}/vlans`),
  112. fetch(`${API_BASE}/vpn/status`),
  113. fetch(`${API_BASE}/firewall/summary`)
  114. ]);
  115. if (statusRes.ok) state.systemStatus = await statusRes.json();
  116. if (ifacesRes.ok) {
  117. const ifacesData = await ifacesRes.json();
  118. state.interfaces = Array.isArray(ifacesData) ? ifacesData : [];
  119. }
  120. if (vlansRes.ok) {
  121. const vlansData = await vlansRes.json();
  122. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  123. }
  124. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  125. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  126. updateSystemMetrics();
  127. updateBadges();
  128. if (state.activeTab === 'dashboard') renderDashboard();
  129. if (state.activeTab === 'interfaces') renderInterfacesList();
  130. if (state.activeTab === 'vlans') renderVlansList();
  131. if (state.activeTab === 'firewall') loadFirewall(false);
  132. if (state.activeTab === 'routes') loadRoutes(false);
  133. if (state.activeTab === 'ppp') loadPPP(false);
  134. if (state.activeTab === 'eoip') loadEoIP(false);
  135. if (state.activeTab === 'pppoe') loadPPPoE(false);
  136. if (state.activeTab === 'wireguard') loadWireGuard(false);
  137. if (state.activeTab === 'ipsec') loadIPSec(false);
  138. if (state.activeTab === 'l2tp') loadL2TP(false);
  139. if (state.activeTab === 'pptp') loadPPTP(false);
  140. } catch (err) {
  141. console.error('Failed to fetch router state:', err);
  142. } finally {
  143. if (isManual && spinner) {
  144. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  145. }
  146. }
  147. }
  148. // Update Top KPI and Sidebar Telemetry
  149. function updateSystemMetrics() {
  150. const s = state.systemStatus;
  151. const v = state.vpnStatus;
  152. if (!s) return;
  153. // Sidebar
  154. document.getElementById('side-hostname').innerText = s.hostname || 'debian-lxc';
  155. document.getElementById('side-uptime').innerText = s.uptime_human || '0m';
  156. document.getElementById('side-gateway-ip').innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  157. if (s.cpu_load && s.cpu_load.length > 0) {
  158. document.getElementById('side-cpu-val').innerText = s.cpu_load[0];
  159. const cpuPct = Math.min(100, Math.round(parseFloat(s.cpu_load[0]) * 50));
  160. document.getElementById('side-cpu-bar').style.width = `${Math.max(5, cpuPct)}%`;
  161. }
  162. document.getElementById('side-ram-val').innerText = `${Math.round(s.mem_usage_pct || 0)}%`;
  163. document.getElementById('side-ram-bar').style.width = `${Math.max(5, Math.round(s.mem_usage_pct || 0))}%`;
  164. // Dashboard Stats
  165. document.getElementById('stat-ifaces-up').innerText = s.up_ifaces || 0;
  166. document.getElementById('stat-ifaces-total').innerText = `${s.total_ifaces || 0} Total`;
  167. document.getElementById('stat-ifaces-down').innerText = `${s.down_ifaces || 0} DOWN`;
  168. document.getElementById('stat-vlans-count').innerText = s.vlan_ifaces || 0;
  169. // VPN Status Indicators
  170. if (v) {
  171. const totalActive = v.total_active_tunnels || 0;
  172. const statVpnActive = document.getElementById('stat-vpn-active');
  173. if (statVpnActive) statVpnActive.innerText = totalActive;
  174. const tunnelsDot = document.getElementById('tunnels-dot');
  175. const tunnelsLabel = document.getElementById('tunnels-label');
  176. if (tunnelsDot && tunnelsLabel) {
  177. if (totalActive > 0) {
  178. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  179. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  180. } else {
  181. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  182. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  183. }
  184. }
  185. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  186. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  187. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  188. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  189. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  190. }
  191. // Total Live Bandwidth Rate
  192. let totalRx = 0;
  193. let totalTx = 0;
  194. (state.interfaces || []).forEach(i => {
  195. if (i.rate) {
  196. totalRx += i.rate.rx_bytes_sec || 0;
  197. totalTx += i.rate.tx_bytes_sec || 0;
  198. }
  199. });
  200. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  201. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  202. }
  203. function setDotBadge(id, active) {
  204. const el = document.getElementById(id);
  205. if (!el) return;
  206. if (active) {
  207. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  208. } else {
  209. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  210. }
  211. }
  212. function updateBadges() {
  213. const bIfaces = document.getElementById('badge-ifaces-count');
  214. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  215. const bVlans = document.getElementById('badge-vlans-count');
  216. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  217. if (state.fwSummary) {
  218. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  219. const badgeFw = document.getElementById('badge-firewall-count');
  220. if (badgeFw) badgeFw.innerText = totalFwRules;
  221. }
  222. if (state.vpnStatus) {
  223. const v = state.vpnStatus;
  224. const bEoIP = document.getElementById('badge-eoip-count');
  225. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  226. const bPPPSess = document.getElementById('badge-ppp-sessions');
  227. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  228. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  229. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  230. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  231. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  232. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  233. }
  234. }
  235. // Render Dashboard View
  236. function renderDashboard() {
  237. const matrix = document.getElementById('port-matrix');
  238. matrix.innerHTML = '';
  239. (state.interfaces || []).forEach(iface => {
  240. const isUp = iface.state === 'UP';
  241. const isVlan = iface.is_vlan;
  242. const portCard = document.createElement('div');
  243. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  244. isUp
  245. ? (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')
  246. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  247. }`;
  248. portCard.onclick = () => openIfaceModal(iface.name);
  249. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  250. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  251. portCard.innerHTML = `
  252. <div class="flex items-center justify-between mb-2">
  253. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  254. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  255. </div>
  256. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  257. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  258. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  259. <span>${iface.rate?.rx_human || '0 B/s'}</span>
  260. </div>
  261. `;
  262. matrix.appendChild(portCard);
  263. });
  264. const ifaceTbody = document.getElementById('quick-interfaces-table');
  265. ifaceTbody.innerHTML = '';
  266. (state.interfaces || []).slice(0, 6).forEach(i => {
  267. const isUp = i.state === 'UP';
  268. const tr = document.createElement('tr');
  269. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  270. tr.onclick = () => openIfaceModal(i.name);
  271. tr.innerHTML = `
  272. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  273. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  274. <span>${i.name}</span>
  275. </td>
  276. <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>
  277. <td class="py-2.5 text-slate-300">${i.ipv4 && i.ipv4.length > 0 ? i.ipv4[0] : '<span class="text-slate-600">-</span>'}</td>
  278. <td class="py-2.5 text-right font-sans font-semibold ${isUp ? 'text-emerald-400' : 'text-rose-400'}">${i.state}</td>
  279. `;
  280. ifaceTbody.appendChild(tr);
  281. });
  282. const vlanTbody = document.getElementById('quick-vlans-table');
  283. vlanTbody.innerHTML = '';
  284. const vlans = state.vlans || [];
  285. if (vlans.length === 0) {
  286. 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>`;
  287. } else {
  288. vlans.slice(0, 6).forEach(v => {
  289. const tr = document.createElement('tr');
  290. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  291. tr.onclick = () => openIfaceModal(v.name);
  292. tr.innerHTML = `
  293. <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>
  294. <td class="py-2.5 text-white font-bold">${v.name}</td>
  295. <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>
  296. <td class="py-2.5 text-right text-slate-400">${v.parent_name || 'eth0'}</td>
  297. `;
  298. vlanTbody.appendChild(tr);
  299. });
  300. }
  301. }
  302. // Expand / Collapse Handlers
  303. function toggleExpand(parentName) {
  304. if (state.expandedParents.has(parentName)) {
  305. state.expandedParents.delete(parentName);
  306. } else {
  307. state.expandedParents.add(parentName);
  308. }
  309. renderInterfacesList();
  310. }
  311. function expandAllIfaces(expand) {
  312. if (expand) {
  313. (state.interfaces || []).forEach(i => {
  314. if (!i.is_vlan) state.expandedParents.add(i.name);
  315. });
  316. } else {
  317. state.expandedParents.clear();
  318. }
  319. renderInterfacesList();
  320. }
  321. // Filter and Render Hierarchical Interfaces List
  322. function filterIfaces(filter) {
  323. state.ifaceFilter = filter;
  324. document.querySelectorAll('.filter-btn').forEach(btn => {
  325. 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';
  326. });
  327. const activeBtn = document.getElementById(`filter-${filter}`);
  328. if (activeBtn) {
  329. activeBtn.className = 'filter-btn px-3 py-1.5 rounded-lg text-xs font-medium bg-slate-800 text-white border border-slate-700';
  330. }
  331. renderInterfacesList();
  332. }
  333. function renderInterfacesList() {
  334. const tbody = document.getElementById('interfaces-tree-tbody');
  335. const emptyState = document.getElementById('interfaces-empty-state');
  336. const summary = document.getElementById('ifaces-list-summary');
  337. const query = (document.getElementById('iface-search')?.value || '').toLowerCase();
  338. tbody.innerHTML = '';
  339. const allIfaces = state.interfaces || [];
  340. const allVlans = state.vlans || [];
  341. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  342. const filteredParents = parentIfaces.filter(parent => {
  343. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  344. if (query) {
  345. const matchParent = parent.name.toLowerCase().includes(query) || (parent.role || '').toLowerCase().includes(query);
  346. const matchVlan = childVlans.some(v => v.name.toLowerCase().includes(query) || String(v.vlan_id).includes(query) || (v.description || '').toLowerCase().includes(query));
  347. if (!matchParent && !matchVlan) return false;
  348. }
  349. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  350. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  351. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  352. return true;
  353. });
  354. if (summary) {
  355. summary.innerText = `${parentIfaces.length} Physical/Parent Links • ${allVlans.length} Active VLANs`;
  356. }
  357. if (filteredParents.length === 0) {
  358. emptyState?.classList.remove('hidden');
  359. return;
  360. }
  361. emptyState?.classList.add('hidden');
  362. filteredParents.forEach(parent => {
  363. const isUp = parent.state === 'UP';
  364. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  365. const isExpanded = state.expandedParents.has(parent.name);
  366. const parentRow = document.createElement('tr');
  367. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  368. parentRow.innerHTML = `
  369. <td class="py-3 px-3 text-center">
  370. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  371. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  372. <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">
  373. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  374. </svg>
  375. </button>
  376. </td>
  377. <td class="py-3 px-4">
  378. <div class="flex items-center space-x-2.5">
  379. <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">
  380. ${parent.type === 'loopback' ? 'LO' : 'NIC'}
  381. </div>
  382. <div>
  383. <div class="flex items-center gap-2">
  384. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400" onclick="toggleExpand('${parent.name}')">${parent.name}</span>
  385. ${childVlans.length > 0
  386. ? `<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>`
  387. : `<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>`
  388. }
  389. </div>
  390. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  391. </div>
  392. </div>
  393. </td>
  394. <td class="py-3 px-4 font-sans">
  395. <div class="flex items-center gap-1.5">
  396. <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>
  397. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  398. </div>
  399. </td>
  400. <td class="py-3 px-4">
  401. ${parent.ipv4 && parent.ipv4.length > 0
  402. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  403. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  404. }
  405. </td>
  406. <td class="py-3 px-4 text-slate-400 text-[11px]">
  407. <div>${parent.mac || 'N/A'}</div>
  408. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  409. </td>
  410. <td class="py-3 px-4 text-[11px]">
  411. <div class="flex items-center space-x-2">
  412. <span class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  413. <span class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  414. </div>
  415. </td>
  416. <td class="py-3 px-4 font-sans">
  417. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  418. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  419. 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'
  420. }" title="Click to toggle link status">
  421. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  422. <span>${parent.state}</span>
  423. </button>
  424. </td>
  425. <td class="py-3 px-4 text-right space-x-2 font-sans">
  426. <button onclick="openVlanModal('${parent.name}')"
  427. 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">
  428. + Add VLAN
  429. </button>
  430. <button onclick="openIfaceModal('${parent.name}')"
  431. 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">
  432. Configure
  433. </button>
  434. </td>
  435. `;
  436. tbody.appendChild(parentRow);
  437. if (isExpanded) {
  438. const drawerRow = document.createElement('tr');
  439. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  440. const drawerCell = document.createElement('td');
  441. drawerCell.colSpan = 8;
  442. drawerCell.className = 'p-0';
  443. drawerCell.innerHTML = `
  444. <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">
  445. <div class="flex items-center justify-between mb-3">
  446. <div class="flex items-center space-x-3">
  447. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  448. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  449. </span>
  450. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  451. ${childVlans.length} Attached
  452. </span>
  453. </div>
  454. <button onclick="openVlanModal('${parent.name}')"
  455. 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">
  456. <span>+ Create VLAN on ${parent.name}</span>
  457. </button>
  458. </div>
  459. ${childVlans.length === 0 ? `
  460. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  461. <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>
  462. <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">
  463. <span>+ Create Your First VLAN on ${parent.name}</span>
  464. </button>
  465. </div>
  466. ` : `
  467. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  468. <table class="w-full text-left text-xs font-mono">
  469. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  470. <tr>
  471. <th class="py-2.5 px-4">VLAN ID</th>
  472. <th class="py-2.5 px-4">Interface Device</th>
  473. <th class="py-2.5 px-4">Subnet Gateway</th>
  474. <th class="py-2.5 px-4">Role / Alias</th>
  475. <th class="py-2.5 px-4">MTU</th>
  476. <th class="py-2.5 px-4">Throughput</th>
  477. <th class="py-2.5 px-4">Status</th>
  478. <th class="py-2.5 px-4 text-right">Actions</th>
  479. </tr>
  480. </thead>
  481. <tbody class="divide-y divide-slate-800/70">
  482. ${childVlans.map(v => {
  483. const isVlanUp = v.state === 'UP';
  484. return `
  485. <tr class="hover:bg-slate-800/40 transition">
  486. <td class="py-2.5 px-4">
  487. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  488. VLAN ${v.vlan_id}
  489. </span>
  490. </td>
  491. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  492. <span class="text-cyan-500">└─</span>
  493. <span>${v.name}</span>
  494. </td>
  495. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  496. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  497. </td>
  498. <td class="py-2.5 px-4 font-sans text-slate-300">
  499. <span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 mr-1.5">${v.role || 'VLAN'}</span>
  500. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  501. </td>
  502. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  503. <td class="py-2.5 px-4 text-[11px]">
  504. <span class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  505. <span class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  506. </td>
  507. <td class="py-2.5 px-4 font-sans">
  508. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  509. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  510. 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'
  511. }">
  512. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  513. <span>${v.state}</span>
  514. </button>
  515. </td>
  516. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  517. <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>
  518. <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>
  519. </td>
  520. </tr>
  521. `;
  522. }).join('')}
  523. </tbody>
  524. </table>
  525. </div>
  526. `}
  527. </div>
  528. `;
  529. drawerRow.appendChild(drawerCell);
  530. tbody.appendChild(drawerRow);
  531. }
  532. });
  533. }
  534. // Render VLANs Dedicated View
  535. function renderVlansList() {
  536. const tbody = document.getElementById('vlans-table-body');
  537. const emptyState = document.getElementById('vlans-empty-state');
  538. const countBadge = document.getElementById('vlans-table-count');
  539. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  540. tbody.innerHTML = '';
  541. const allVlans = state.vlans || [];
  542. countBadge.innerText = allVlans.length;
  543. const filtered = allVlans.filter(v => {
  544. if (!query) return true;
  545. return v.name.toLowerCase().includes(query) ||
  546. String(v.vlan_id).includes(query) ||
  547. (v.description || '').toLowerCase().includes(query) ||
  548. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  549. });
  550. if (allVlans.length === 0) {
  551. emptyState.classList.remove('hidden');
  552. return;
  553. }
  554. emptyState.classList.add('hidden');
  555. filtered.forEach(v => {
  556. const isUp = v.state === 'UP';
  557. const tr = document.createElement('tr');
  558. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  559. tr.innerHTML = `
  560. <td class="py-3 px-4">
  561. <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">
  562. VLAN ${v.vlan_id}
  563. </span>
  564. </td>
  565. <td class="py-3 px-4 font-bold text-white">${v.name}</td>
  566. <td class="py-3 px-4 text-slate-300">
  567. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  568. </td>
  569. <td class="py-3 px-4 text-emerald-400 font-medium">
  570. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  571. </td>
  572. <td class="py-3 px-4 text-slate-300 font-sans">
  573. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  574. </td>
  575. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  576. <td class="py-3 px-4 font-sans">
  577. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  578. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  579. 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'
  580. }">
  581. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  582. <span>${v.state}</span>
  583. </button>
  584. </td>
  585. <td class="py-3 px-4 text-right space-x-2 font-sans">
  586. <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>
  587. <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>
  588. </td>
  589. `;
  590. tbody.appendChild(tr);
  591. });
  592. }
  593. // Toggle interface UP / DOWN
  594. async function toggleInterfaceState(name, newState) {
  595. try {
  596. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  597. method: 'POST',
  598. headers: { 'Content-Type': 'application/json' },
  599. body: JSON.stringify({ state: newState })
  600. });
  601. const data = await res.json();
  602. if (res.ok) {
  603. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  604. fetchData(false);
  605. } else {
  606. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  607. }
  608. } catch (err) {
  609. showToast('Error', err.message, 'error');
  610. }
  611. }
  612. // ---------------- MikroTik Flag & Utilities ----------------
  613. function renderMikroTikFlag(running, disabled) {
  614. if (running) {
  615. 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>`;
  616. }
  617. if (disabled) {
  618. 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>`;
  619. }
  620. 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>`;
  621. }
  622. function copyToClipboard(text, label = 'Text') {
  623. navigator.clipboard.writeText(text).then(() => {
  624. showToast('Copied', `${label} copied to clipboard`, 'success');
  625. }).catch(() => {
  626. prompt('Copy value:', text);
  627. });
  628. }
  629. // ======================== PPPoE Multi-Instance ========================
  630. async function loadPPPoE(populateInputs = true) {
  631. try {
  632. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  633. const list = await res.json();
  634. state.pppoeList = Array.isArray(list) ? list : [];
  635. const badge = document.getElementById('pppoe-count-badge');
  636. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  637. const tbody = document.getElementById('pppoe-table-body');
  638. const empty = document.getElementById('pppoe-empty');
  639. if (!tbody) return;
  640. tbody.innerHTML = '';
  641. if (state.pppoeList.length === 0) {
  642. if (empty) empty.classList.remove('hidden');
  643. } else {
  644. if (empty) empty.classList.add('hidden');
  645. state.pppoeList.forEach(inst => {
  646. const tr = document.createElement('tr');
  647. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  648. tr.innerHTML = `
  649. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  650. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  651. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.interface}</td>
  652. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  653. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  654. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  655. <td class="py-2.5 px-3 text-center">
  656. <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'}">
  657. ${inst.default_route ? 'Yes' : 'No'}
  658. </span>
  659. </td>
  660. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  661. ${inst.running ? `
  662. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  663. ` : `
  664. <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>
  665. `}
  666. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  667. ${inst.disabled ? 'Enable' : 'Disable'}
  668. </button>
  669. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  670. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  671. </td>
  672. `;
  673. tbody.appendChild(tr);
  674. });
  675. }
  676. } catch (err) {
  677. console.error('Failed to load PPPoE:', err);
  678. }
  679. }
  680. function openAddPPPoEModal() {
  681. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  682. document.getElementById('pppoe-modal-edit-orig').value = '';
  683. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  684. document.getElementById('pppoe-modal-name').readOnly = false;
  685. document.getElementById('pppoe-modal-user').value = '';
  686. document.getElementById('pppoe-modal-pass').value = '';
  687. document.getElementById('pppoe-modal-service').value = '';
  688. document.getElementById('pppoe-modal-mtu').value = '1492';
  689. document.getElementById('pppoe-modal-defroute').checked = true;
  690. document.getElementById('pppoe-modal-reconnect').checked = true;
  691. document.getElementById('pppoe-modal-disabled').checked = false;
  692. // Populate interfaces
  693. const sel = document.getElementById('pppoe-modal-iface');
  694. sel.innerHTML = '';
  695. (state.interfaces || []).forEach(i => {
  696. if (i.name === 'lo') return;
  697. const opt = document.createElement('option');
  698. opt.value = i.name;
  699. opt.innerText = `${i.name} (${i.role || i.type})`;
  700. sel.appendChild(opt);
  701. });
  702. document.getElementById('pppoe-modal').classList.remove('hidden');
  703. }
  704. function openEditPPPoEModal(name) {
  705. const inst = (state.pppoeList || []).find(i => i.name === name);
  706. if (!inst) return;
  707. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  708. document.getElementById('pppoe-modal-edit-orig').value = name;
  709. document.getElementById('pppoe-modal-name').value = inst.name;
  710. document.getElementById('pppoe-modal-name').readOnly = true;
  711. document.getElementById('pppoe-modal-user').value = inst.username || '';
  712. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  713. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  714. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  715. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  716. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  717. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  718. const sel = document.getElementById('pppoe-modal-iface');
  719. sel.innerHTML = '';
  720. (state.interfaces || []).forEach(i => {
  721. if (i.name === 'lo') return;
  722. const opt = document.createElement('option');
  723. opt.value = i.name;
  724. opt.innerText = `${i.name} (${i.role || i.type})`;
  725. if (i.name === inst.interface) opt.selected = true;
  726. sel.appendChild(opt);
  727. });
  728. document.getElementById('pppoe-modal').classList.remove('hidden');
  729. }
  730. function closePPPoEModal() {
  731. document.getElementById('pppoe-modal').classList.add('hidden');
  732. }
  733. async function submitSavePPPoE(e) {
  734. e.preventDefault();
  735. const name = document.getElementById('pppoe-modal-name').value.trim();
  736. const iface = document.getElementById('pppoe-modal-iface').value;
  737. const user = document.getElementById('pppoe-modal-user').value.trim();
  738. const pass = document.getElementById('pppoe-modal-pass').value;
  739. const service = document.getElementById('pppoe-modal-service').value.trim();
  740. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  741. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  742. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  743. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  744. try {
  745. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  746. method: 'POST',
  747. headers: { 'Content-Type': 'application/json' },
  748. body: JSON.stringify({
  749. name,
  750. interface: iface,
  751. username: user,
  752. password: pass,
  753. service_name: service,
  754. mtu,
  755. default_route: defRoute,
  756. auto_reconnect: reconnect,
  757. disabled
  758. })
  759. });
  760. if (res.ok) {
  761. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  762. closePPPoEModal();
  763. loadPPPoE(false);
  764. fetchData(false);
  765. } else {
  766. const err = await res.json();
  767. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  768. }
  769. } catch (err) {
  770. showToast('Error', err.message, 'error');
  771. }
  772. }
  773. async function connectPPPoEInstance(name) {
  774. try {
  775. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  776. if (res.ok) {
  777. showToast('Connecting', `Dialing ${name}...`, 'info');
  778. setTimeout(() => loadPPPoE(false), 2000);
  779. }
  780. } catch (err) {
  781. showToast('Error', err.message, 'error');
  782. }
  783. }
  784. async function disconnectPPPoEInstance(name) {
  785. try {
  786. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  787. if (res.ok) {
  788. showToast('Disconnected', `${name} session terminated`, 'info');
  789. setTimeout(() => loadPPPoE(false), 1000);
  790. }
  791. } catch (err) {
  792. showToast('Error', err.message, 'error');
  793. }
  794. }
  795. async function togglePPPoEState(name, enable) {
  796. try {
  797. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  798. method: 'POST',
  799. headers: { 'Content-Type': 'application/json' },
  800. body: JSON.stringify({ enabled: enable })
  801. });
  802. if (res.ok) {
  803. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  804. loadPPPoE(false);
  805. }
  806. } catch (err) {
  807. showToast('Error', err.message, 'error');
  808. }
  809. }
  810. async function deletePPPoEInstance(name) {
  811. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  812. try {
  813. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  814. if (res.ok) {
  815. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  816. loadPPPoE(false);
  817. fetchData(false);
  818. }
  819. } catch (err) {
  820. showToast('Error', err.message, 'error');
  821. }
  822. }
  823. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  824. state.wgSubTab = 'ifaces';
  825. function switchWGSubTab(tab) {
  826. state.wgSubTab = tab;
  827. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  828. const peersPanel = document.getElementById('wg-subtab-peers');
  829. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  830. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  831. if (tab === 'ifaces') {
  832. ifacesPanel?.classList.remove('hidden');
  833. peersPanel?.classList.add('hidden');
  834. 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';
  835. 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';
  836. } else {
  837. ifacesPanel?.classList.add('hidden');
  838. peersPanel?.classList.remove('hidden');
  839. 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';
  840. 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';
  841. renderWGPeers();
  842. }
  843. }
  844. async function loadWireGuard(populateInputs = true) {
  845. try {
  846. const [ifacesRes, peersRes] = await Promise.all([
  847. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  848. fetch(`${API_BASE}/vpn/wireguard/peers`)
  849. ]);
  850. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  851. const peers = peersRes.ok ? await peersRes.json() : [];
  852. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  853. state.wgPeers = Array.isArray(peers) ? peers : [];
  854. // Badges
  855. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  856. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  857. const peersCountBadge = document.getElementById('wg-peers-count');
  858. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  859. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  860. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  861. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  862. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  863. // Render Interfaces
  864. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  865. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  866. if (ifacesTbody) {
  867. ifacesTbody.innerHTML = '';
  868. if (state.wgInterfaces.length === 0) {
  869. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  870. } else {
  871. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  872. state.wgInterfaces.forEach(iface => {
  873. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  874. const tr = document.createElement('tr');
  875. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  876. tr.innerHTML = `
  877. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  878. <td class="py-2.5 px-3 font-bold text-white">${iface.name}</td>
  879. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  880. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '-'}</td>
  881. <td class="py-2.5 px-3 text-slate-300 font-mono">
  882. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  883. ${(iface.public_key || '').substring(0, 10)}... 📋
  884. </span>
  885. </td>
  886. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  887. <td class="py-2.5 px-3 text-center">
  888. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  889. </td>
  890. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  891. ${iface.running ? `
  892. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300">Stop</button>
  893. ` : `
  894. <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>
  895. `}
  896. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  897. ${iface.disabled ? 'Enable' : 'Disable'}
  898. </button>
  899. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  900. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  901. </td>
  902. `;
  903. ifacesTbody.appendChild(tr);
  904. });
  905. }
  906. }
  907. // Populate filter dropdown in peers tab
  908. const filterSel = document.getElementById('wg-peers-filter-iface');
  909. if (filterSel) {
  910. const currentVal = filterSel.value;
  911. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  912. state.wgInterfaces.forEach(i => {
  913. const opt = document.createElement('option');
  914. opt.value = i.name;
  915. opt.innerText = i.name;
  916. if (i.name === currentVal) opt.selected = true;
  917. filterSel.appendChild(opt);
  918. });
  919. }
  920. renderWGPeers();
  921. } catch (err) {
  922. console.error('Failed to load WireGuard:', err);
  923. }
  924. }
  925. function renderWGPeers() {
  926. const filterSel = document.getElementById('wg-peers-filter-iface');
  927. const selectedIface = filterSel ? filterSel.value : '';
  928. const tbody = document.getElementById('wg-peers-table-body');
  929. const empty = document.getElementById('wg-peers-empty');
  930. if (!tbody) return;
  931. tbody.innerHTML = '';
  932. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  933. if (filtered.length === 0) {
  934. if (empty) empty.classList.remove('hidden');
  935. } else {
  936. if (empty) empty.classList.add('hidden');
  937. filtered.forEach(p => {
  938. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  939. const tr = document.createElement('tr');
  940. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  941. tr.innerHTML = `
  942. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  943. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${p.interface}</td>
  944. <td class="py-2.5 px-3 font-bold text-white font-sans">${p.name || 'Unnamed'}</td>
  945. <td class="py-2.5 px-3 text-slate-300 font-mono">
  946. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  947. ${p.public_key.substring(0, 10)}... 📋
  948. </span>
  949. </td>
  950. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  951. <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>
  952. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  953. <td class="py-2.5 px-3 font-mono text-[11px]">
  954. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  955. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  956. </td>
  957. <td class="py-2.5 px-3 text-right font-sans space-x-2">
  958. <button onclick="openWGClientConfModal('${p.interface}', '${(p.allowed_ips || [])[0] || '10.10.0.2/32'}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold" title="Generate WireGuard Client Profile (.conf)">Config (.conf)</button>
  959. <button onclick="deleteWGPeer('${p.interface}', '${p.public_key}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  960. </td>
  961. `;
  962. tbody.appendChild(tr);
  963. });
  964. }
  965. }
  966. function openAddWGInterfaceModal() {
  967. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  968. document.getElementById('wg-iface-modal-edit-orig').value = '';
  969. document.getElementById('wg-iface-modal-name').value = `wg${(state.wgInterfaces || []).length}`;
  970. document.getElementById('wg-iface-modal-name').readOnly = false;
  971. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  972. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  973. document.getElementById('wg-iface-modal-mtu').value = '1420';
  974. document.getElementById('wg-iface-modal-pubkey').value = '';
  975. document.getElementById('wg-iface-modal-privkey').value = '';
  976. document.getElementById('wg-iface-modal-disabled').checked = false;
  977. generateWGInterfaceKeys();
  978. document.getElementById('wg-iface-modal').classList.remove('hidden');
  979. }
  980. function openEditWGInterfaceModal(name) {
  981. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  982. if (!iface) return;
  983. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  984. document.getElementById('wg-iface-modal-edit-orig').value = name;
  985. document.getElementById('wg-iface-modal-name').value = iface.name;
  986. document.getElementById('wg-iface-modal-name').readOnly = true;
  987. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  988. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  989. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  990. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  991. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  992. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  993. document.getElementById('wg-iface-modal').classList.remove('hidden');
  994. }
  995. function closeAddWGInterfaceModal() {
  996. document.getElementById('wg-iface-modal').classList.add('hidden');
  997. }
  998. async function generateWGInterfaceKeys() {
  999. try {
  1000. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1001. const keys = await res.json();
  1002. if (res.ok) {
  1003. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1004. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1005. }
  1006. } catch (err) {
  1007. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1008. }
  1009. }
  1010. async function submitSaveWGInterface(e) {
  1011. e.preventDefault();
  1012. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1013. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1014. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1015. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1016. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1017. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1018. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1019. try {
  1020. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1021. method: 'POST',
  1022. headers: { 'Content-Type': 'application/json' },
  1023. body: JSON.stringify({
  1024. name,
  1025. listen_port: port,
  1026. address: addr,
  1027. mtu,
  1028. public_key: pub,
  1029. private_key: priv,
  1030. disabled
  1031. })
  1032. });
  1033. if (res.ok) {
  1034. showToast('WireGuard Saved', `Interface ${name} configured`, 'success');
  1035. closeAddWGInterfaceModal();
  1036. loadWireGuard(false);
  1037. fetchData(false);
  1038. }
  1039. } catch (err) {
  1040. showToast('Error', err.message, 'error');
  1041. }
  1042. }
  1043. async function startWGInterface(name) {
  1044. try {
  1045. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1046. if (res.ok) {
  1047. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1048. loadWireGuard(false);
  1049. fetchData(false);
  1050. }
  1051. } catch (err) {
  1052. showToast('Error', err.message, 'error');
  1053. }
  1054. }
  1055. async function stopWGInterface(name) {
  1056. try {
  1057. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1058. if (res.ok) {
  1059. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1060. loadWireGuard(false);
  1061. fetchData(false);
  1062. }
  1063. } catch (err) {
  1064. showToast('Error', err.message, 'error');
  1065. }
  1066. }
  1067. async function toggleWGInterfaceState(name, enable) {
  1068. try {
  1069. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1070. method: 'POST',
  1071. headers: { 'Content-Type': 'application/json' },
  1072. body: JSON.stringify({ enabled: enable })
  1073. });
  1074. if (res.ok) {
  1075. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1076. loadWireGuard(false);
  1077. }
  1078. } catch (err) {
  1079. showToast('Error', err.message, 'error');
  1080. }
  1081. }
  1082. async function deleteWGInterface(name) {
  1083. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}?`)) return;
  1084. try {
  1085. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1086. if (res.ok) {
  1087. showToast('Deleted', `Interface ${name} removed`, 'success');
  1088. loadWireGuard(false);
  1089. fetchData(false);
  1090. }
  1091. } catch (err) {
  1092. showToast('Error', err.message, 'error');
  1093. }
  1094. }
  1095. function openAddWGPeerModal() {
  1096. const sel = document.getElementById('wg-peer-modal-iface');
  1097. sel.innerHTML = '';
  1098. (state.wgInterfaces || []).forEach(i => {
  1099. const opt = document.createElement('option');
  1100. opt.value = i.name;
  1101. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1102. sel.appendChild(opt);
  1103. });
  1104. if ((state.wgInterfaces || []).length === 0) {
  1105. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1106. openAddWGInterfaceModal();
  1107. return;
  1108. }
  1109. document.getElementById('wg-peer-modal-name').value = '';
  1110. document.getElementById('wg-peer-modal-pubkey').value = '';
  1111. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1112. document.getElementById('wg-peer-modal-endpoint').value = '';
  1113. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1114. document.getElementById('wg-peer-modal-preshared').value = '';
  1115. document.getElementById('wg-peer-modal-disabled').checked = false;
  1116. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1117. }
  1118. function closeAddWGPeerModal() {
  1119. document.getElementById('wg-peer-modal').classList.add('hidden');
  1120. }
  1121. async function submitSaveWGPeer(e) {
  1122. e.preventDefault();
  1123. const iface = document.getElementById('wg-peer-modal-iface').value;
  1124. const name = document.getElementById('wg-peer-modal-name').value.trim();
  1125. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1126. const allowed = document.getElementById('wg-peer-modal-allowedips').value.split(',').map(s => s.trim());
  1127. const ep = document.getElementById('wg-peer-modal-endpoint').value.trim();
  1128. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 25;
  1129. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  1130. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  1131. let epAddr = ep;
  1132. let epPort = 0;
  1133. if (ep.includes(':')) {
  1134. const parts = ep.split(':');
  1135. epAddr = parts[0];
  1136. epPort = parseInt(parts[1], 10) || 0;
  1137. }
  1138. try {
  1139. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  1140. method: 'POST',
  1141. headers: { 'Content-Type': 'application/json' },
  1142. body: JSON.stringify({
  1143. interface: iface,
  1144. name,
  1145. public_key: pub,
  1146. allowed_ips: allowed,
  1147. endpoint_address: epAddr,
  1148. endpoint_port: epPort,
  1149. persistent_keepalive: keepalive,
  1150. preshared_key: psk,
  1151. disabled
  1152. })
  1153. });
  1154. if (res.ok) {
  1155. showToast('Peer Saved', `Peer ${name} added to ${iface}`, 'success');
  1156. closeAddWGPeerModal();
  1157. loadWireGuard(false);
  1158. }
  1159. } catch (err) {
  1160. showToast('Error', err.message, 'error');
  1161. }
  1162. }
  1163. async function deleteWGPeer(iface, pubkey) {
  1164. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  1165. try {
  1166. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/${encodeURIComponent(iface)}/${encodeURIComponent(pubkey)}`, {
  1167. method: 'DELETE'
  1168. });
  1169. if (res.ok) {
  1170. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  1171. loadWireGuard(false);
  1172. }
  1173. } catch (err) {
  1174. showToast('Error', err.message, 'error');
  1175. }
  1176. }
  1177. // ======================== IPSec Multi-Tunnel ========================
  1178. async function loadIPSec(populateInputs = true) {
  1179. try {
  1180. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1181. const list = await res.json();
  1182. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1183. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1184. const badge = document.getElementById('ipsec-sas-badge');
  1185. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1186. const tbody = document.getElementById('ipsec-table-body');
  1187. const empty = document.getElementById('ipsec-empty');
  1188. if (!tbody) return;
  1189. tbody.innerHTML = '';
  1190. if (state.ipsecTunnels.length === 0) {
  1191. if (empty) empty.classList.remove('hidden');
  1192. } else {
  1193. if (empty) empty.classList.add('hidden');
  1194. state.ipsecTunnels.forEach(c => {
  1195. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1196. const tr = document.createElement('tr');
  1197. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1198. tr.innerHTML = `
  1199. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isEstablished, c.disabled)}</td>
  1200. <td class="py-2.5 px-4 font-bold text-white">${c.name}</td>
  1201. <td class="py-2.5 px-4 text-emerald-400 font-mono">${c.local_subnet || '-'}</td>
  1202. <td class="py-2.5 px-4 text-slate-300 font-mono">${c.remote_addrs || '-'}</td>
  1203. <td class="py-2.5 px-4 text-cyan-400 font-mono">${c.remote_subnet || '-'}</td>
  1204. <td class="py-2.5 px-4 font-sans">
  1205. <span class="px-2 py-0.5 rounded-full text-[10px] font-semibold ${
  1206. isEstablished ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-slate-800 text-slate-400'
  1207. }">${c.status || (isEstablished ? 'ESTABLISHED' : 'DISCONNECTED')}</span>
  1208. </td>
  1209. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  1210. ${isEstablished ? `
  1211. <button onclick="stopIPSecTunnel('${c.name}')" class="text-xs text-rose-400 hover:text-rose-300">Terminate</button>
  1212. ` : `
  1213. <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>
  1214. `}
  1215. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1216. ${c.disabled ? 'Enable' : 'Disable'}
  1217. </button>
  1218. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1219. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1220. </td>
  1221. `;
  1222. tbody.appendChild(tr);
  1223. });
  1224. }
  1225. } catch (err) {
  1226. console.error('Failed to load IPSec:', err);
  1227. }
  1228. }
  1229. function openAddIPSecModal() {
  1230. document.getElementById('ipsec-modal-title').innerText = 'Configure IPSec IKEv2 Tunnel';
  1231. document.getElementById('ipsec-modal-name').value = `ipsec-${(state.ipsecTunnels || []).length + 1}`;
  1232. document.getElementById('ipsec-modal-name').readOnly = false;
  1233. document.getElementById('ipsec-modal-localts').value = '192.168.10.0/24';
  1234. document.getElementById('ipsec-modal-remotets').value = '192.168.20.0/24';
  1235. document.getElementById('ipsec-modal-remotegw').value = '';
  1236. document.getElementById('ipsec-modal-psk').value = '';
  1237. document.getElementById('ipsec-modal-ikeprop').value = 'aes256-sha256-modp2048,default';
  1238. document.getElementById('ipsec-modal-espprop').value = 'aes256-sha256-modp2048,default';
  1239. document.getElementById('ipsec-modal-autostart').checked = true;
  1240. document.getElementById('ipsec-modal-disabled').checked = false;
  1241. document.getElementById('ipsec-modal').classList.remove('hidden');
  1242. }
  1243. function openEditIPSecModal(name) {
  1244. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  1245. if (!conn) return;
  1246. document.getElementById('ipsec-modal-title').innerText = `Edit IPSec Tunnel: ${name}`;
  1247. document.getElementById('ipsec-modal-name').value = conn.name;
  1248. document.getElementById('ipsec-modal-name').readOnly = true;
  1249. document.getElementById('ipsec-modal-localts').value = conn.local_subnet || '';
  1250. document.getElementById('ipsec-modal-remotets').value = conn.remote_subnet || '';
  1251. document.getElementById('ipsec-modal-remotegw').value = conn.remote_addrs || '';
  1252. document.getElementById('ipsec-modal-psk').value = conn.preshared_key || '';
  1253. document.getElementById('ipsec-modal-ikeprop').value = conn.ike_proposals || 'aes256-sha256-modp2048,default';
  1254. document.getElementById('ipsec-modal-espprop').value = conn.esp_proposals || 'aes256-sha256-modp2048,default';
  1255. document.getElementById('ipsec-modal-autostart').checked = conn.auto_start ?? true;
  1256. document.getElementById('ipsec-modal-disabled').checked = !!conn.disabled;
  1257. document.getElementById('ipsec-modal').classList.remove('hidden');
  1258. }
  1259. function closeAddIPSecModal() {
  1260. document.getElementById('ipsec-modal').classList.add('hidden');
  1261. }
  1262. async function submitSaveIPSec(e) {
  1263. e.preventDefault();
  1264. const name = document.getElementById('ipsec-modal-name').value.trim();
  1265. const localts = document.getElementById('ipsec-modal-localts').value.trim();
  1266. const remotets = document.getElementById('ipsec-modal-remotets').value.trim();
  1267. const remotegw = document.getElementById('ipsec-modal-remotegw').value.trim();
  1268. const psk = document.getElementById('ipsec-modal-psk').value;
  1269. const ike = document.getElementById('ipsec-modal-ikeprop').value.trim();
  1270. const esp = document.getElementById('ipsec-modal-espprop').value.trim();
  1271. const autostart = document.getElementById('ipsec-modal-autostart').checked;
  1272. const disabled = document.getElementById('ipsec-modal-disabled').checked;
  1273. try {
  1274. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  1275. method: 'POST',
  1276. headers: { 'Content-Type': 'application/json' },
  1277. body: JSON.stringify({
  1278. name,
  1279. local_addrs: '%any',
  1280. remote_addrs: remotegw,
  1281. local_subnet: localts,
  1282. remote_subnet: remotets,
  1283. preshared_key: psk,
  1284. ike_proposals: ike,
  1285. esp_proposals: esp,
  1286. auto_start: autostart,
  1287. disabled
  1288. })
  1289. });
  1290. if (res.ok) {
  1291. showToast('IPSec Saved', `Tunnel ${name} configured`, 'success');
  1292. closeAddIPSecModal();
  1293. loadIPSec(false);
  1294. fetchData(false);
  1295. }
  1296. } catch (err) {
  1297. showToast('Error', err.message, 'error');
  1298. }
  1299. }
  1300. async function startIPSecTunnel(name) {
  1301. try {
  1302. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1303. if (res.ok) {
  1304. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  1305. setTimeout(() => loadIPSec(false), 2000);
  1306. }
  1307. } catch (err) {
  1308. showToast('Error', err.message, 'error');
  1309. }
  1310. }
  1311. async function stopIPSecTunnel(name) {
  1312. try {
  1313. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1314. if (res.ok) {
  1315. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  1316. loadIPSec(false);
  1317. }
  1318. } catch (err) {
  1319. showToast('Error', err.message, 'error');
  1320. }
  1321. }
  1322. async function toggleIPSecState(name, enable) {
  1323. try {
  1324. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  1325. method: 'POST',
  1326. headers: { 'Content-Type': 'application/json' },
  1327. body: JSON.stringify({ enabled: enable })
  1328. });
  1329. if (res.ok) {
  1330. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  1331. loadIPSec(false);
  1332. }
  1333. } catch (err) {
  1334. showToast('Error', err.message, 'error');
  1335. }
  1336. }
  1337. async function deleteIPSecConn(name) {
  1338. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  1339. try {
  1340. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1341. if (res.ok) {
  1342. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  1343. loadIPSec(false);
  1344. fetchData(false);
  1345. }
  1346. } catch (err) {
  1347. showToast('Error', err.message, 'error');
  1348. }
  1349. }
  1350. // ======================== L2TP Multi-Instance ========================
  1351. async function loadL2TP(populateInputs = true) {
  1352. try {
  1353. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  1354. const list = await res.json();
  1355. state.l2tpList = Array.isArray(list) ? list : [];
  1356. const badge = document.getElementById('l2tp-count-badge');
  1357. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  1358. const tbody = document.getElementById('l2tp-table-body');
  1359. const empty = document.getElementById('l2tp-empty');
  1360. if (!tbody) return;
  1361. tbody.innerHTML = '';
  1362. if (state.l2tpList.length === 0) {
  1363. if (empty) empty.classList.remove('hidden');
  1364. } else {
  1365. if (empty) empty.classList.add('hidden');
  1366. state.l2tpList.forEach(inst => {
  1367. const tr = document.createElement('tr');
  1368. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1369. tr.innerHTML = `
  1370. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1371. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1372. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.connect_to}</td>
  1373. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1374. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1375. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1376. <td class="py-2.5 px-3 text-center">
  1377. <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'}">
  1378. ${inst.default_route ? 'Yes' : 'No'}
  1379. </span>
  1380. </td>
  1381. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1382. ${inst.running ? `
  1383. <button onclick="disconnectL2TPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1384. ` : `
  1385. <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>
  1386. `}
  1387. <button onclick="toggleL2TPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1388. ${inst.disabled ? 'Enable' : 'Disable'}
  1389. </button>
  1390. <button onclick="openEditL2TPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1391. <button onclick="deleteL2TPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1392. </td>
  1393. `;
  1394. tbody.appendChild(tr);
  1395. });
  1396. }
  1397. } catch (err) {
  1398. console.error('Failed to load L2TP:', err);
  1399. }
  1400. }
  1401. function openAddL2TPModal() {
  1402. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  1403. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  1404. document.getElementById('l2tp-modal-name').readOnly = false;
  1405. document.getElementById('l2tp-modal-server').value = '';
  1406. document.getElementById('l2tp-modal-user').value = '';
  1407. document.getElementById('l2tp-modal-pass').value = '';
  1408. document.getElementById('l2tp-modal-ipsec').value = '';
  1409. document.getElementById('l2tp-modal-defroute').checked = true;
  1410. document.getElementById('l2tp-modal-disabled').checked = false;
  1411. document.getElementById('l2tp-modal').classList.remove('hidden');
  1412. }
  1413. function openEditL2TPModal(name) {
  1414. const inst = (state.l2tpList || []).find(i => i.name === name);
  1415. if (!inst) return;
  1416. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  1417. document.getElementById('l2tp-modal-name').value = inst.name;
  1418. document.getElementById('l2tp-modal-name').readOnly = true;
  1419. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  1420. document.getElementById('l2tp-modal-user').value = inst.username || '';
  1421. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  1422. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  1423. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  1424. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  1425. document.getElementById('l2tp-modal').classList.remove('hidden');
  1426. }
  1427. function closeL2TPModal() {
  1428. document.getElementById('l2tp-modal').classList.add('hidden');
  1429. }
  1430. async function submitSaveL2TP(e) {
  1431. e.preventDefault();
  1432. const name = document.getElementById('l2tp-modal-name').value.trim();
  1433. const server = document.getElementById('l2tp-modal-server').value.trim();
  1434. const user = document.getElementById('l2tp-modal-user').value.trim();
  1435. const pass = document.getElementById('l2tp-modal-pass').value;
  1436. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  1437. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  1438. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  1439. try {
  1440. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  1441. method: 'POST',
  1442. headers: { 'Content-Type': 'application/json' },
  1443. body: JSON.stringify({
  1444. name,
  1445. connect_to: server,
  1446. username: user,
  1447. password: pass,
  1448. ipsec_secret: ipsec,
  1449. default_route: defRoute,
  1450. disabled
  1451. })
  1452. });
  1453. if (res.ok) {
  1454. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  1455. closeL2TPModal();
  1456. loadL2TP(false);
  1457. fetchData(false);
  1458. }
  1459. } catch (err) {
  1460. showToast('Error', err.message, 'error');
  1461. }
  1462. }
  1463. async function connectL2TPInstance(name) {
  1464. try {
  1465. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1466. if (res.ok) {
  1467. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  1468. setTimeout(() => loadL2TP(false), 2000);
  1469. }
  1470. } catch (err) {
  1471. showToast('Error', err.message, 'error');
  1472. }
  1473. }
  1474. async function disconnectL2TPInstance(name) {
  1475. try {
  1476. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1477. if (res.ok) {
  1478. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  1479. loadL2TP(false);
  1480. }
  1481. } catch (err) {
  1482. showToast('Error', err.message, 'error');
  1483. }
  1484. }
  1485. async function toggleL2TPState(name, enable) {
  1486. try {
  1487. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  1488. method: 'POST',
  1489. headers: { 'Content-Type': 'application/json' },
  1490. body: JSON.stringify({ enabled: enable })
  1491. });
  1492. if (res.ok) {
  1493. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1494. loadL2TP(false);
  1495. }
  1496. } catch (err) {
  1497. showToast('Error', err.message, 'error');
  1498. }
  1499. }
  1500. async function deleteL2TPInstance(name) {
  1501. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  1502. try {
  1503. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1504. if (res.ok) {
  1505. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  1506. loadL2TP(false);
  1507. fetchData(false);
  1508. }
  1509. } catch (err) {
  1510. showToast('Error', err.message, 'error');
  1511. }
  1512. }
  1513. // ======================== PPTP Multi-Instance ========================
  1514. async function loadPPTP(populateInputs = true) {
  1515. try {
  1516. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  1517. const list = await res.json();
  1518. state.pptpList = Array.isArray(list) ? list : [];
  1519. const badge = document.getElementById('pptp-count-badge');
  1520. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  1521. const tbody = document.getElementById('pptp-table-body');
  1522. const empty = document.getElementById('pptp-empty');
  1523. if (!tbody) return;
  1524. tbody.innerHTML = '';
  1525. if (state.pptpList.length === 0) {
  1526. if (empty) empty.classList.remove('hidden');
  1527. } else {
  1528. if (empty) empty.classList.add('hidden');
  1529. state.pptpList.forEach(inst => {
  1530. const tr = document.createElement('tr');
  1531. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1532. tr.innerHTML = `
  1533. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1534. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1535. <td class="py-2.5 px-3 text-purple-400 font-mono">${inst.connect_to}</td>
  1536. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1537. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1538. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1539. <td class="py-2.5 px-3 text-center">
  1540. <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'}">
  1541. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  1542. </span>
  1543. </td>
  1544. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1545. ${inst.running ? `
  1546. <button onclick="disconnectPPTPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1547. ` : `
  1548. <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>
  1549. `}
  1550. <button onclick="togglePPTPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1551. ${inst.disabled ? 'Enable' : 'Disable'}
  1552. </button>
  1553. <button onclick="openEditPPTPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1554. <button onclick="deletePPTPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1555. </td>
  1556. `;
  1557. tbody.appendChild(tr);
  1558. });
  1559. }
  1560. } catch (err) {
  1561. console.error('Failed to load PPTP:', err);
  1562. }
  1563. }
  1564. function openAddPPTPModal() {
  1565. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  1566. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  1567. document.getElementById('pptp-modal-name').readOnly = false;
  1568. document.getElementById('pptp-modal-server').value = '';
  1569. document.getElementById('pptp-modal-user').value = '';
  1570. document.getElementById('pptp-modal-pass').value = '';
  1571. document.getElementById('pptp-modal-mppe').checked = true;
  1572. document.getElementById('pptp-modal-defroute').checked = true;
  1573. document.getElementById('pptp-modal-disabled').checked = false;
  1574. document.getElementById('pptp-modal').classList.remove('hidden');
  1575. }
  1576. function openEditPPTPModal(name) {
  1577. const inst = (state.pptpList || []).find(i => i.name === name);
  1578. if (!inst) return;
  1579. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  1580. document.getElementById('pptp-modal-name').value = inst.name;
  1581. document.getElementById('pptp-modal-name').readOnly = true;
  1582. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  1583. document.getElementById('pptp-modal-user').value = inst.username || '';
  1584. document.getElementById('pptp-modal-pass').value = inst.password || '';
  1585. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  1586. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  1587. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  1588. document.getElementById('pptp-modal').classList.remove('hidden');
  1589. }
  1590. function closePPTPModal() {
  1591. document.getElementById('pptp-modal').classList.add('hidden');
  1592. }
  1593. async function submitSavePPTP(e) {
  1594. e.preventDefault();
  1595. const name = document.getElementById('pptp-modal-name').value.trim();
  1596. const server = document.getElementById('pptp-modal-server').value.trim();
  1597. const user = document.getElementById('pptp-modal-user').value.trim();
  1598. const pass = document.getElementById('pptp-modal-pass').value;
  1599. const mppe = document.getElementById('pptp-modal-mppe').checked;
  1600. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  1601. const disabled = document.getElementById('pptp-modal-disabled').checked;
  1602. try {
  1603. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  1604. method: 'POST',
  1605. headers: { 'Content-Type': 'application/json' },
  1606. body: JSON.stringify({
  1607. name,
  1608. connect_to: server,
  1609. username: user,
  1610. password: pass,
  1611. require_mppe: mppe,
  1612. default_route: defRoute,
  1613. auto_reconnect: true,
  1614. disabled
  1615. })
  1616. });
  1617. if (res.ok) {
  1618. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  1619. closePPTPModal();
  1620. loadPPTP(false);
  1621. fetchData(false);
  1622. }
  1623. } catch (err) {
  1624. showToast('Error', err.message, 'error');
  1625. }
  1626. }
  1627. async function connectPPTPInstance(name) {
  1628. try {
  1629. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1630. if (res.ok) {
  1631. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  1632. setTimeout(() => loadPPTP(false), 2000);
  1633. }
  1634. } catch (err) {
  1635. showToast('Error', err.message, 'error');
  1636. }
  1637. }
  1638. async function disconnectPPTPInstance(name) {
  1639. try {
  1640. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1641. if (res.ok) {
  1642. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  1643. loadPPTP(false);
  1644. }
  1645. } catch (err) {
  1646. showToast('Error', err.message, 'error');
  1647. }
  1648. }
  1649. async function togglePPTPState(name, enable) {
  1650. try {
  1651. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  1652. method: 'POST',
  1653. headers: { 'Content-Type': 'application/json' },
  1654. body: JSON.stringify({ enabled: enable })
  1655. });
  1656. if (res.ok) {
  1657. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1658. loadPPTP(false);
  1659. }
  1660. } catch (err) {
  1661. showToast('Error', err.message, 'error');
  1662. }
  1663. }
  1664. async function deletePPTPInstance(name) {
  1665. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  1666. try {
  1667. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1668. if (res.ok) {
  1669. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  1670. loadPPTP(false);
  1671. fetchData(false);
  1672. }
  1673. } catch (err) {
  1674. showToast('Error', err.message, 'error');
  1675. }
  1676. }
  1677. // ---------------- Modal & Helper Functions ----------------
  1678. function openVlanModal(defaultParent = '') {
  1679. const select = document.getElementById('vlan-parent');
  1680. select.innerHTML = '';
  1681. const allIfaces = state.interfaces || [];
  1682. const eligible = allIfaces.filter(i => !i.is_vlan && i.name !== 'lo');
  1683. if (eligible.length === 0) {
  1684. allIfaces.forEach(i => eligible.push(i));
  1685. }
  1686. eligible.forEach(i => {
  1687. const opt = document.createElement('option');
  1688. opt.value = i.name;
  1689. opt.innerText = `${i.name} (${i.role || 'Interface'} - ${i.state})`;
  1690. if (i.name === defaultParent) opt.selected = true;
  1691. select.appendChild(opt);
  1692. });
  1693. document.getElementById('vlan-id').value = '';
  1694. document.getElementById('vlan-name').value = '';
  1695. document.getElementById('vlan-ip').value = '';
  1696. document.getElementById('vlan-desc').value = '';
  1697. autoSuggestVlanName();
  1698. document.getElementById('vlan-modal').classList.remove('hidden');
  1699. }
  1700. function closeVlanModal() {
  1701. document.getElementById('vlan-modal').classList.add('hidden');
  1702. }
  1703. function autoSuggestVlanName() {
  1704. const parent = document.getElementById('vlan-parent').value;
  1705. const id = document.getElementById('vlan-id').value;
  1706. const nameInput = document.getElementById('vlan-name');
  1707. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  1708. }
  1709. function setSubnetPreset(cidr) {
  1710. const ipInput = document.getElementById('vlan-ip');
  1711. const id = document.getElementById('vlan-id').value || '10';
  1712. ipInput.value = `192.168.${id}.1${cidr}`;
  1713. }
  1714. async function submitCreateVlan(e) {
  1715. e.preventDefault();
  1716. const btn = document.getElementById('vlan-submit-btn');
  1717. btn.disabled = true;
  1718. btn.innerText = 'Creating...';
  1719. const parent = document.getElementById('vlan-parent').value;
  1720. const id = parseInt(document.getElementById('vlan-id').value, 10);
  1721. const name = document.getElementById('vlan-name').value.trim();
  1722. const ip = document.getElementById('vlan-ip').value.trim();
  1723. const role = document.getElementById('vlan-role').value;
  1724. const desc = document.getElementById('vlan-desc').value.trim();
  1725. try {
  1726. const res = await fetch(`${API_BASE}/vlans`, {
  1727. method: 'POST',
  1728. headers: { 'Content-Type': 'application/json' },
  1729. body: JSON.stringify({
  1730. parent_name: parent,
  1731. vlan_id: id,
  1732. name: name,
  1733. ip_address: ip,
  1734. role: role,
  1735. description: desc,
  1736. mtu: 1500,
  1737. auto_up: true
  1738. })
  1739. });
  1740. const data = await res.json();
  1741. if (res.ok) {
  1742. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  1743. state.expandedParents.add(parent);
  1744. closeVlanModal();
  1745. await fetchData(true);
  1746. if (state.activeTab !== 'interfaces') navigate('interfaces');
  1747. } else {
  1748. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  1749. }
  1750. } catch (err) {
  1751. showToast('Error', err.message, 'error');
  1752. } finally {
  1753. btn.disabled = false;
  1754. btn.innerText = 'Create VLAN';
  1755. }
  1756. }
  1757. async function confirmDeleteVlan(name) {
  1758. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  1759. try {
  1760. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1761. if (res.ok) {
  1762. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  1763. closeIfaceModal();
  1764. fetchData(true);
  1765. }
  1766. } catch (err) {
  1767. showToast('Error', err.message, 'error');
  1768. }
  1769. }
  1770. function openIfaceModal(name) {
  1771. const iface = (state.interfaces || []).find(i => i.name === name);
  1772. if (!iface) return;
  1773. state.currentModalIface = iface.name;
  1774. document.getElementById('modal-iface-name').innerText = iface.name;
  1775. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  1776. document.getElementById('modal-iface-mtu').value = iface.mtu;
  1777. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  1778. document.getElementById('modal-iface-desc').value = iface.description || '';
  1779. const delBtn = document.getElementById('modal-delete-vlan-btn');
  1780. if (iface.is_vlan) {
  1781. delBtn.classList.remove('hidden');
  1782. } else {
  1783. delBtn.classList.add('hidden');
  1784. }
  1785. renderModalIPs(iface);
  1786. document.getElementById('iface-modal').classList.remove('hidden');
  1787. }
  1788. function renderModalIPs(iface) {
  1789. const container = document.getElementById('modal-ip-list');
  1790. container.innerHTML = '';
  1791. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  1792. if (addrs.length === 0) {
  1793. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  1794. return;
  1795. }
  1796. addrs.forEach(addr => {
  1797. const row = document.createElement('div');
  1798. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  1799. row.innerHTML = `
  1800. <span class="text-white">${addr}</span>
  1801. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  1802. `;
  1803. container.appendChild(row);
  1804. });
  1805. }
  1806. function closeIfaceModal() {
  1807. document.getElementById('iface-modal').classList.add('hidden');
  1808. state.currentModalIface = null;
  1809. }
  1810. async function setIfaceState(name, newState) {
  1811. await toggleInterfaceState(name, newState);
  1812. const updated = (state.interfaces || []).find(i => i.name === name);
  1813. if (updated) openIfaceModal(name);
  1814. }
  1815. async function applyMTU() {
  1816. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  1817. try {
  1818. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  1819. method: 'POST',
  1820. headers: { 'Content-Type': 'application/json' },
  1821. body: JSON.stringify({ mtu })
  1822. });
  1823. if (res.ok) {
  1824. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  1825. fetchData(false);
  1826. }
  1827. } catch (err) {
  1828. showToast('Error', err.message, 'error');
  1829. }
  1830. }
  1831. async function addInterfaceIP() {
  1832. const ip = document.getElementById('modal-new-ip').value.trim();
  1833. if (!ip) return;
  1834. try {
  1835. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  1836. method: 'POST',
  1837. headers: { 'Content-Type': 'application/json' },
  1838. body: JSON.stringify({ ip })
  1839. });
  1840. if (res.ok) {
  1841. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  1842. document.getElementById('modal-new-ip').value = '';
  1843. await fetchData(false);
  1844. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  1845. if (iface) renderModalIPs(iface);
  1846. }
  1847. } catch (err) {
  1848. showToast('Error', err.message, 'error');
  1849. }
  1850. }
  1851. async function removeInterfaceIP(ip) {
  1852. if (!confirm(`Remove IP ${ip}?`)) return;
  1853. try {
  1854. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  1855. method: 'DELETE',
  1856. headers: { 'Content-Type': 'application/json' },
  1857. body: JSON.stringify({ ip })
  1858. });
  1859. if (res.ok) {
  1860. showToast('IP Removed', `Removed ${ip}`, 'success');
  1861. await fetchData(false);
  1862. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  1863. if (iface) renderModalIPs(iface);
  1864. }
  1865. } catch (err) {
  1866. showToast('Error', err.message, 'error');
  1867. }
  1868. }
  1869. async function saveInterfaceMetadata() {
  1870. const role = document.getElementById('modal-iface-role').value;
  1871. const desc = document.getElementById('modal-iface-desc').value.trim();
  1872. try {
  1873. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/metadata`, {
  1874. method: 'POST',
  1875. headers: { 'Content-Type': 'application/json' },
  1876. body: JSON.stringify({ role, description: desc })
  1877. });
  1878. if (res.ok) {
  1879. showToast('Saved', 'Metadata updated', 'success');
  1880. closeIfaceModal();
  1881. fetchData(false);
  1882. }
  1883. } catch (err) {
  1884. showToast('Error', err.message, 'error');
  1885. }
  1886. }
  1887. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  1888. state.fwSubTab = 'filter';
  1889. state.routesSubTab = 'routes';
  1890. function renderRuleFlag(disabled, hasComment) {
  1891. let flags = '';
  1892. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  1893. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  1894. return flags || '<span class="text-slate-600">-</span>';
  1895. }
  1896. function renderActionBadge(action) {
  1897. const act = (action || '').toLowerCase();
  1898. let color = 'bg-slate-800 text-slate-300';
  1899. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  1900. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  1901. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  1902. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  1903. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  1904. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  1905. }
  1906. function switchFWSubTab(tab) {
  1907. state.fwSubTab = tab;
  1908. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'connections'];
  1909. tabs.forEach(t => {
  1910. const panel = document.getElementById(`fw-subtab-${t}`);
  1911. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  1912. if (panel) {
  1913. if (t === tab) panel.classList.remove('hidden');
  1914. else panel.classList.add('hidden');
  1915. }
  1916. if (btn) {
  1917. if (t === tab) {
  1918. 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';
  1919. } else {
  1920. 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';
  1921. }
  1922. }
  1923. });
  1924. const addBtn = document.getElementById('fw-primary-add-btn');
  1925. if (addBtn) {
  1926. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  1927. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  1928. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  1929. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  1930. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  1931. }
  1932. if (tab === 'connections') loadConnections();
  1933. }
  1934. function openCurrentFWModal() {
  1935. if (state.fwSubTab === 'filter') openAddFilterModal();
  1936. else if (state.fwSubTab === 'nat') openAddNATModal();
  1937. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  1938. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  1939. else if (state.fwSubTab === 'connections') loadConnections();
  1940. }
  1941. async function loadFirewall(populateDropdowns = true) {
  1942. try {
  1943. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes] = await Promise.all([
  1944. fetch(`${API_BASE}/firewall/summary`),
  1945. fetch(`${API_BASE}/firewall/filter`),
  1946. fetch(`${API_BASE}/firewall/nat`),
  1947. fetch(`${API_BASE}/firewall/mangle`),
  1948. fetch(`${API_BASE}/firewall/address-lists`)
  1949. ]);
  1950. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  1951. if (filterRes.ok) state.filterRules = await filterRes.json();
  1952. if (natRes.ok) state.natRules = await natRes.json();
  1953. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  1954. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  1955. // Badges
  1956. const bFilter = document.getElementById('fw-badge-filter');
  1957. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  1958. const bNat = document.getElementById('fw-badge-nat');
  1959. if (bNat) bNat.innerText = (state.natRules || []).length;
  1960. const bMangle = document.getElementById('fw-badge-mangle');
  1961. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  1962. const bAddr = document.getElementById('fw-badge-addrlist');
  1963. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  1964. renderFilterRules();
  1965. renderNATRules();
  1966. renderMangleRules();
  1967. renderAddressLists();
  1968. if (state.fwSubTab === 'connections') {
  1969. loadConnections();
  1970. }
  1971. } catch (err) {
  1972. console.error('Failed to load firewall:', err);
  1973. }
  1974. }
  1975. // ----------------- Filter Rules -----------------
  1976. function renderFilterRules() {
  1977. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  1978. const tbody = document.getElementById('filter-table-body');
  1979. const empty = document.getElementById('filter-empty');
  1980. if (!tbody) return;
  1981. tbody.innerHTML = '';
  1982. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  1983. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  1984. if (rules.length === 0) {
  1985. empty?.classList.remove('hidden');
  1986. return;
  1987. }
  1988. empty?.classList.add('hidden');
  1989. rules.forEach((r, idx) => {
  1990. const tr = document.createElement('tr');
  1991. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  1992. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  1993. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  1994. tr.innerHTML = `
  1995. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  1996. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  1997. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  1998. <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>
  1999. <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>
  2000. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2001. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2002. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2003. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2004. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2005. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2006. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2007. </td>
  2008. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2009. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2010. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2011. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2012. <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>
  2013. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2014. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2015. </td>
  2016. `;
  2017. tbody.appendChild(tr);
  2018. });
  2019. }
  2020. function populateInterfaceSelect(selectId, currentVal = '') {
  2021. const sel = document.getElementById(selectId);
  2022. if (!sel) return;
  2023. sel.innerHTML = '<option value="">(Any Interface)</option>';
  2024. (state.interfaces || []).forEach(i => {
  2025. const opt = document.createElement('option');
  2026. opt.value = i.name;
  2027. opt.innerText = `${i.name} (${i.role || i.type})`;
  2028. if (i.name === currentVal) opt.selected = true;
  2029. sel.appendChild(opt);
  2030. });
  2031. }
  2032. function populateAddressListSelect(selectId, currentVal = '') {
  2033. const sel = document.getElementById(selectId);
  2034. if (!sel) return;
  2035. sel.innerHTML = '<option value="">(None)</option>';
  2036. const set = new Set((state.addressLists || []).map(a => a.name));
  2037. set.forEach(name => {
  2038. const opt = document.createElement('option');
  2039. opt.value = name;
  2040. opt.innerText = name;
  2041. if (name === currentVal) opt.selected = true;
  2042. sel.appendChild(opt);
  2043. });
  2044. }
  2045. function openAddFilterModal() {
  2046. document.getElementById('filter-modal-title').innerText = 'Add Firewall Filter Rule';
  2047. document.getElementById('filter-modal-id').value = '';
  2048. document.getElementById('filter-modal-chain').value = 'forward';
  2049. document.getElementById('filter-modal-action').value = 'accept';
  2050. document.getElementById('filter-modal-proto').value = 'all';
  2051. document.getElementById('filter-modal-src').value = '';
  2052. document.getElementById('filter-modal-dst').value = '';
  2053. document.getElementById('filter-modal-sport').value = '';
  2054. document.getElementById('filter-modal-dport').value = '';
  2055. document.getElementById('filter-modal-connmark').value = '';
  2056. document.getElementById('filter-modal-comment').value = '';
  2057. document.getElementById('filter-modal-disabled').checked = false;
  2058. document.getElementById('filter-modal-cs-established').checked = false;
  2059. document.getElementById('filter-modal-cs-related').checked = false;
  2060. document.getElementById('filter-modal-cs-new').checked = false;
  2061. document.getElementById('filter-modal-cs-invalid').checked = false;
  2062. populateInterfaceSelect('filter-modal-iniface');
  2063. populateInterfaceSelect('filter-modal-outiface');
  2064. populateAddressListSelect('filter-modal-srclist');
  2065. populateAddressListSelect('filter-modal-dstlist');
  2066. toggleFilterActionFields();
  2067. document.getElementById('filter-modal').classList.remove('hidden');
  2068. }
  2069. function openEditFilterModal(id) {
  2070. const r = (state.filterRules || []).find(rule => rule.id === id);
  2071. if (!r) return;
  2072. document.getElementById('filter-modal-title').innerText = `Edit Filter Rule (#${r.order})`;
  2073. document.getElementById('filter-modal-id').value = r.id;
  2074. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  2075. document.getElementById('filter-modal-action').value = r.action || 'accept';
  2076. document.getElementById('filter-modal-proto').value = r.protocol || 'all';
  2077. document.getElementById('filter-modal-src').value = r.src_address || '';
  2078. document.getElementById('filter-modal-dst').value = r.dst_address || '';
  2079. document.getElementById('filter-modal-sport').value = r.src_port || '';
  2080. document.getElementById('filter-modal-dport').value = r.dst_port || '';
  2081. document.getElementById('filter-modal-connmark').value = r.connection_mark || '';
  2082. document.getElementById('filter-modal-comment').value = r.comment || '';
  2083. document.getElementById('filter-modal-disabled').checked = !!r.disabled;
  2084. const states = r.connection_state || [];
  2085. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  2086. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  2087. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  2088. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  2089. populateInterfaceSelect('filter-modal-iniface', r.in_interface);
  2090. populateInterfaceSelect('filter-modal-outiface', r.out_interface);
  2091. populateAddressListSelect('filter-modal-srclist', r.src_address_list);
  2092. populateAddressListSelect('filter-modal-dstlist', r.dst_address_list);
  2093. toggleFilterActionFields();
  2094. document.getElementById('filter-modal').classList.remove('hidden');
  2095. }
  2096. function closeFilterModal() {
  2097. document.getElementById('filter-modal').classList.add('hidden');
  2098. }
  2099. function toggleFilterActionFields() {
  2100. const act = document.getElementById('filter-modal-action').value;
  2101. const rejectBox = document.getElementById('filter-action-reject-box');
  2102. if (rejectBox) {
  2103. if (act === 'reject') rejectBox.classList.remove('hidden');
  2104. else rejectBox.classList.add('hidden');
  2105. }
  2106. }
  2107. async function submitSaveFilterRule(e) {
  2108. e.preventDefault();
  2109. const id = document.getElementById('filter-modal-id').value;
  2110. const chain = document.getElementById('filter-modal-chain').value;
  2111. const action = document.getElementById('filter-modal-action').value;
  2112. const proto = document.getElementById('filter-modal-proto').value;
  2113. const src = document.getElementById('filter-modal-src').value.trim();
  2114. const dst = document.getElementById('filter-modal-dst').value.trim();
  2115. const sport = document.getElementById('filter-modal-sport').value.trim();
  2116. const dport = document.getElementById('filter-modal-dport').value.trim();
  2117. const inIface = document.getElementById('filter-modal-iniface').value;
  2118. const outIface = document.getElementById('filter-modal-outiface').value;
  2119. const connmark = document.getElementById('filter-modal-connmark').value.trim();
  2120. const srclist = document.getElementById('filter-modal-srclist').value;
  2121. const dstlist = document.getElementById('filter-modal-dstlist').value;
  2122. const comment = document.getElementById('filter-modal-comment').value.trim();
  2123. const disabled = document.getElementById('filter-modal-disabled').checked;
  2124. const rejectWith = document.getElementById('filter-modal-rejectwith')?.value || '';
  2125. const states = [];
  2126. if (document.getElementById('filter-modal-cs-established').checked) states.push('established');
  2127. if (document.getElementById('filter-modal-cs-related').checked) states.push('related');
  2128. if (document.getElementById('filter-modal-cs-new').checked) states.push('new');
  2129. if (document.getElementById('filter-modal-cs-invalid').checked) states.push('invalid');
  2130. try {
  2131. const res = await fetch(`${API_BASE}/firewall/filter`, {
  2132. method: 'POST',
  2133. headers: { 'Content-Type': 'application/json' },
  2134. body: JSON.stringify({
  2135. id,
  2136. chain,
  2137. action,
  2138. reject_with: rejectWith,
  2139. protocol: proto,
  2140. src_address: src,
  2141. dst_address: dst,
  2142. src_port: sport,
  2143. dst_port: dport,
  2144. in_interface: inIface,
  2145. out_interface: outIface,
  2146. connection_state: states,
  2147. connection_mark: connmark,
  2148. src_address_list: srclist,
  2149. dst_address_list: dstlist,
  2150. comment,
  2151. disabled
  2152. })
  2153. });
  2154. if (res.ok) {
  2155. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  2156. closeFilterModal();
  2157. loadFirewall(false);
  2158. } else {
  2159. const err = await res.json();
  2160. showToast('Error', err.message, 'error');
  2161. }
  2162. } catch (err) {
  2163. showToast('Error', err.message, 'error');
  2164. }
  2165. }
  2166. async function moveFilterRule(id, dir) {
  2167. try {
  2168. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  2169. method: 'POST',
  2170. headers: { 'Content-Type': 'application/json' },
  2171. body: JSON.stringify({ direction: dir })
  2172. });
  2173. if (res.ok) loadFirewall(false);
  2174. } catch (err) {
  2175. showToast('Error', err.message, 'error');
  2176. }
  2177. }
  2178. async function toggleFilterRuleState(id, disabled) {
  2179. try {
  2180. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  2181. method: 'POST',
  2182. headers: { 'Content-Type': 'application/json' },
  2183. body: JSON.stringify({ disabled })
  2184. });
  2185. if (res.ok) loadFirewall(false);
  2186. } catch (err) {
  2187. showToast('Error', err.message, 'error');
  2188. }
  2189. }
  2190. async function deleteFilterRule(id) {
  2191. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  2192. try {
  2193. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2194. if (res.ok) {
  2195. showToast('Deleted', 'Filter rule removed', 'success');
  2196. loadFirewall(false);
  2197. }
  2198. } catch (err) {
  2199. showToast('Error', err.message, 'error');
  2200. }
  2201. }
  2202. // ----------------- NAT Rules -----------------
  2203. function renderNATRules() {
  2204. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  2205. const tbody = document.getElementById('nat-table-body');
  2206. const empty = document.getElementById('nat-empty');
  2207. if (!tbody) return;
  2208. tbody.innerHTML = '';
  2209. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2210. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  2211. if (rules.length === 0) {
  2212. empty?.classList.remove('hidden');
  2213. return;
  2214. }
  2215. empty?.classList.add('hidden');
  2216. rules.forEach((r, idx) => {
  2217. const tr = document.createElement('tr');
  2218. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2219. const toTarget = [r.to_addresses, r.to_ports].filter(Boolean).join(':');
  2220. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  2221. tr.innerHTML = `
  2222. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2223. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2224. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  2225. <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>
  2226. <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>
  2227. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  2228. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2229. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2230. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${toTarget || '-'}</td>
  2231. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2232. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2233. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2234. </td>
  2235. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2236. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2237. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2238. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2239. <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>
  2240. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2241. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2242. </td>
  2243. `;
  2244. tbody.appendChild(tr);
  2245. });
  2246. }
  2247. function openAddNATModal() {
  2248. document.getElementById('nat-modal-title').innerText = 'Add NAT Rule';
  2249. document.getElementById('nat-modal-id').value = '';
  2250. document.getElementById('nat-modal-chain').value = 'srcnat';
  2251. document.getElementById('nat-modal-action').value = 'masquerade';
  2252. document.getElementById('nat-modal-toaddr').value = '';
  2253. document.getElementById('nat-modal-toport').value = '';
  2254. document.getElementById('nat-modal-proto').value = 'all';
  2255. document.getElementById('nat-modal-src').value = '';
  2256. document.getElementById('nat-modal-dst').value = '';
  2257. document.getElementById('nat-modal-dport').value = '';
  2258. document.getElementById('nat-modal-comment').value = '';
  2259. document.getElementById('nat-modal-disabled').checked = false;
  2260. populateInterfaceSelect('nat-modal-iniface');
  2261. populateInterfaceSelect('nat-modal-outiface');
  2262. toggleNATActionFields();
  2263. document.getElementById('nat-modal').classList.remove('hidden');
  2264. }
  2265. function openEditNATModal(id) {
  2266. const r = (state.natRules || []).find(rule => rule.id === id);
  2267. if (!r) return;
  2268. document.getElementById('nat-modal-title').innerText = `Edit NAT Rule (#${r.order})`;
  2269. document.getElementById('nat-modal-id').value = r.id;
  2270. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  2271. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  2272. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  2273. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  2274. document.getElementById('nat-modal-proto').value = r.protocol || 'all';
  2275. document.getElementById('nat-modal-src').value = r.src_address || '';
  2276. document.getElementById('nat-modal-dst').value = r.dst_address || '';
  2277. document.getElementById('nat-modal-dport').value = r.dst_port || '';
  2278. document.getElementById('nat-modal-comment').value = r.comment || '';
  2279. document.getElementById('nat-modal-disabled').checked = !!r.disabled;
  2280. populateInterfaceSelect('nat-modal-iniface', r.in_interface);
  2281. populateInterfaceSelect('nat-modal-outiface', r.out_interface);
  2282. toggleNATActionFields();
  2283. document.getElementById('nat-modal').classList.remove('hidden');
  2284. }
  2285. function closeNATModal() {
  2286. document.getElementById('nat-modal').classList.add('hidden');
  2287. }
  2288. function toggleNATChainFields() {
  2289. const ch = document.getElementById('nat-modal-chain').value;
  2290. const actSel = document.getElementById('nat-modal-action');
  2291. if (ch === 'srcnat' && actSel.value === 'dst-nat') {
  2292. actSel.value = 'masquerade';
  2293. } else if (ch === 'dstnat' && actSel.value === 'masquerade') {
  2294. actSel.value = 'dst-nat';
  2295. }
  2296. toggleNATActionFields();
  2297. }
  2298. function toggleNATActionFields() {
  2299. const act = document.getElementById('nat-modal-action').value;
  2300. const toBox = document.getElementById('nat-action-to-box');
  2301. if (toBox) {
  2302. if (act === 'masquerade' || act === 'accept') toBox.classList.add('hidden');
  2303. else toBox.classList.remove('hidden');
  2304. }
  2305. }
  2306. async function submitSaveNATRule(e) {
  2307. e.preventDefault();
  2308. const id = document.getElementById('nat-modal-id').value;
  2309. const chain = document.getElementById('nat-modal-chain').value;
  2310. const action = document.getElementById('nat-modal-action').value;
  2311. const toaddr = document.getElementById('nat-modal-toaddr').value.trim();
  2312. const toport = document.getElementById('nat-modal-toport').value.trim();
  2313. const proto = document.getElementById('nat-modal-proto').value;
  2314. const src = document.getElementById('nat-modal-src').value.trim();
  2315. const dst = document.getElementById('nat-modal-dst').value.trim();
  2316. const dport = document.getElementById('nat-modal-dport').value.trim();
  2317. const inIface = document.getElementById('nat-modal-iniface').value;
  2318. const outIface = document.getElementById('nat-modal-outiface').value;
  2319. const comment = document.getElementById('nat-modal-comment').value.trim();
  2320. const disabled = document.getElementById('nat-modal-disabled').checked;
  2321. try {
  2322. const res = await fetch(`${API_BASE}/firewall/nat`, {
  2323. method: 'POST',
  2324. headers: { 'Content-Type': 'application/json' },
  2325. body: JSON.stringify({
  2326. id,
  2327. chain,
  2328. action,
  2329. to_addresses: toaddr,
  2330. to_ports: toport,
  2331. protocol: proto,
  2332. src_address: src,
  2333. dst_address: dst,
  2334. dst_port: dport,
  2335. in_interface: inIface,
  2336. out_interface: outIface,
  2337. comment,
  2338. disabled
  2339. })
  2340. });
  2341. if (res.ok) {
  2342. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  2343. closeNATModal();
  2344. loadFirewall(false);
  2345. }
  2346. } catch (err) {
  2347. showToast('Error', err.message, 'error');
  2348. }
  2349. }
  2350. async function moveNATRule(id, dir) {
  2351. try {
  2352. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  2353. method: 'POST',
  2354. headers: { 'Content-Type': 'application/json' },
  2355. body: JSON.stringify({ direction: dir })
  2356. });
  2357. if (res.ok) loadFirewall(false);
  2358. } catch (err) {
  2359. showToast('Error', err.message, 'error');
  2360. }
  2361. }
  2362. async function toggleNATRuleState(id, disabled) {
  2363. try {
  2364. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  2365. method: 'POST',
  2366. headers: { 'Content-Type': 'application/json' },
  2367. body: JSON.stringify({ disabled })
  2368. });
  2369. if (res.ok) loadFirewall(false);
  2370. } catch (err) {
  2371. showToast('Error', err.message, 'error');
  2372. }
  2373. }
  2374. async function deleteNATRule(id) {
  2375. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  2376. try {
  2377. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2378. if (res.ok) {
  2379. showToast('Deleted', 'NAT rule removed', 'success');
  2380. loadFirewall(false);
  2381. }
  2382. } catch (err) {
  2383. showToast('Error', err.message, 'error');
  2384. }
  2385. }
  2386. // ----------------- Mangle Rules -----------------
  2387. function renderMangleRules() {
  2388. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  2389. const tbody = document.getElementById('mangle-table-body');
  2390. const empty = document.getElementById('mangle-empty');
  2391. if (!tbody) return;
  2392. tbody.innerHTML = '';
  2393. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2394. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  2395. if (rules.length === 0) {
  2396. empty?.classList.remove('hidden');
  2397. return;
  2398. }
  2399. empty?.classList.add('hidden');
  2400. rules.forEach((r, idx) => {
  2401. const tr = document.createElement('tr');
  2402. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2403. const markVal = r.new_connection_mark || r.new_routing_mark || r.new_packet_mark || r.new_mss || (r.new_dscp ? 'DSCP:' + r.new_dscp : '');
  2404. tr.innerHTML = `
  2405. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2406. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2407. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  2408. <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>
  2409. <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>
  2410. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2411. <td class="py-2.5 px-3 font-mono font-bold text-cyan-300">${markVal || '-'}</td>
  2412. <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>
  2413. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2414. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2415. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2416. </td>
  2417. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2418. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2419. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2420. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2421. <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>
  2422. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2423. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2424. </td>
  2425. `;
  2426. tbody.appendChild(tr);
  2427. });
  2428. }
  2429. function openAddMangleModal() {
  2430. document.getElementById('mangle-modal-title').innerText = 'Add Mangle Rule';
  2431. document.getElementById('mangle-modal-id').value = '';
  2432. document.getElementById('mangle-modal-chain').value = 'prerouting';
  2433. document.getElementById('mangle-modal-action').value = 'mark-connection';
  2434. document.getElementById('mangle-modal-newmark').value = '';
  2435. document.getElementById('mangle-modal-passthrough').checked = true;
  2436. document.getElementById('mangle-modal-src').value = '';
  2437. document.getElementById('mangle-modal-dst').value = '';
  2438. document.getElementById('mangle-modal-connmark').value = '';
  2439. document.getElementById('mangle-modal-comment').value = '';
  2440. document.getElementById('mangle-modal-disabled').checked = false;
  2441. populateInterfaceSelect('mangle-modal-iniface');
  2442. document.getElementById('mangle-modal').classList.remove('hidden');
  2443. }
  2444. function openEditMangleModal(id) {
  2445. const r = (state.mangleRules || []).find(rule => rule.id === id);
  2446. if (!r) return;
  2447. document.getElementById('mangle-modal-title').innerText = `Edit Mangle Rule (#${r.order})`;
  2448. document.getElementById('mangle-modal-id').value = r.id;
  2449. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  2450. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  2451. document.getElementById('mangle-modal-newmark').value = r.new_connection_mark || r.new_routing_mark || r.new_packet_mark || r.new_mss || '';
  2452. document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  2453. document.getElementById('mangle-modal-src').value = r.src_address || '';
  2454. document.getElementById('mangle-modal-dst').value = r.dst_address || '';
  2455. document.getElementById('mangle-modal-connmark').value = r.connection_mark || '';
  2456. document.getElementById('mangle-modal-comment').value = r.comment || '';
  2457. document.getElementById('mangle-modal-disabled').checked = !!r.disabled;
  2458. populateInterfaceSelect('mangle-modal-iniface', r.in_interface);
  2459. document.getElementById('mangle-modal').classList.remove('hidden');
  2460. }
  2461. function closeMangleModal() {
  2462. document.getElementById('mangle-modal').classList.add('hidden');
  2463. }
  2464. function toggleMangleActionFields() {
  2465. // Handled smoothly by single dynamic input
  2466. }
  2467. async function submitSaveMangleRule(e) {
  2468. e.preventDefault();
  2469. const id = document.getElementById('mangle-modal-id').value;
  2470. const chain = document.getElementById('mangle-modal-chain').value;
  2471. const action = document.getElementById('mangle-modal-action').value;
  2472. const newmark = document.getElementById('mangle-modal-newmark').value.trim();
  2473. const passthrough = document.getElementById('mangle-modal-passthrough').checked;
  2474. const src = document.getElementById('mangle-modal-src').value.trim();
  2475. const dst = document.getElementById('mangle-modal-dst').value.trim();
  2476. const inIface = document.getElementById('mangle-modal-iniface').value;
  2477. const connmark = document.getElementById('mangle-modal-connmark').value.trim();
  2478. const comment = document.getElementById('mangle-modal-comment').value.trim();
  2479. const disabled = document.getElementById('mangle-modal-disabled').checked;
  2480. const payload = {
  2481. id,
  2482. chain,
  2483. action,
  2484. passthrough,
  2485. src_address: src,
  2486. dst_address: dst,
  2487. in_interface: inIface,
  2488. connection_mark: connmark,
  2489. comment,
  2490. disabled
  2491. };
  2492. if (action === 'mark-connection') payload.new_connection_mark = newmark;
  2493. else if (action === 'mark-routing') payload.new_routing_mark = newmark;
  2494. else if (action === 'mark-packet') payload.new_packet_mark = newmark;
  2495. else if (action === 'change-mss') payload.new_mss = newmark || 'clamp-to-pmtu';
  2496. try {
  2497. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  2498. method: 'POST',
  2499. headers: { 'Content-Type': 'application/json' },
  2500. body: JSON.stringify(payload)
  2501. });
  2502. if (res.ok) {
  2503. showToast('Mangle Rule Saved', 'Marking rule applied', 'success');
  2504. closeMangleModal();
  2505. loadFirewall(false);
  2506. }
  2507. } catch (err) {
  2508. showToast('Error', err.message, 'error');
  2509. }
  2510. }
  2511. async function moveMangleRule(id, dir) {
  2512. try {
  2513. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  2514. method: 'POST',
  2515. headers: { 'Content-Type': 'application/json' },
  2516. body: JSON.stringify({ direction: dir })
  2517. });
  2518. if (res.ok) loadFirewall(false);
  2519. } catch (err) {
  2520. showToast('Error', err.message, 'error');
  2521. }
  2522. }
  2523. async function toggleMangleRuleState(id, disabled) {
  2524. try {
  2525. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  2526. method: 'POST',
  2527. headers: { 'Content-Type': 'application/json' },
  2528. body: JSON.stringify({ disabled })
  2529. });
  2530. if (res.ok) loadFirewall(false);
  2531. } catch (err) {
  2532. showToast('Error', err.message, 'error');
  2533. }
  2534. }
  2535. async function deleteMangleRule(id) {
  2536. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  2537. try {
  2538. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2539. if (res.ok) {
  2540. showToast('Deleted', 'Mangle rule removed', 'success');
  2541. loadFirewall(false);
  2542. }
  2543. } catch (err) {
  2544. showToast('Error', err.message, 'error');
  2545. }
  2546. }
  2547. // ----------------- Address Lists -----------------
  2548. function renderAddressLists() {
  2549. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  2550. const tbody = document.getElementById('addrlist-table-body');
  2551. const empty = document.getElementById('addrlist-empty');
  2552. if (!tbody) return;
  2553. tbody.innerHTML = '';
  2554. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  2555. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  2556. // Update filter select
  2557. const sel = document.getElementById('addrlist-filter-name');
  2558. if (sel) {
  2559. const cur = sel.value;
  2560. sel.innerHTML = '<option value="">All Lists</option>';
  2561. const set = new Set((state.addressLists || []).map(a => a.name));
  2562. set.forEach(n => {
  2563. const opt = document.createElement('option');
  2564. opt.value = n;
  2565. opt.innerText = n;
  2566. if (n === cur) opt.selected = true;
  2567. sel.appendChild(opt);
  2568. });
  2569. }
  2570. if (entries.length === 0) {
  2571. empty?.classList.remove('hidden');
  2572. return;
  2573. }
  2574. empty?.classList.add('hidden');
  2575. entries.forEach((e, idx) => {
  2576. const tr = document.createElement('tr');
  2577. tr.className = `hover:bg-slate-800/40 transition text-xs ${e.disabled ? 'opacity-50' : ''}`;
  2578. tr.innerHTML = `
  2579. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  2580. <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>
  2581. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  2582. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  2583. <td class="py-2.5 px-3 text-slate-400 italic">${e.comment || '-'}</td>
  2584. <td class="py-2.5 px-3 text-right font-sans">
  2585. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2586. </td>
  2587. `;
  2588. tbody.appendChild(tr);
  2589. });
  2590. }
  2591. function openAddAddrListModal() {
  2592. document.getElementById('addrlist-modal-name').value = '';
  2593. document.getElementById('addrlist-modal-addr').value = '';
  2594. document.getElementById('addrlist-modal-comment').value = '';
  2595. document.getElementById('addrlist-modal').classList.remove('hidden');
  2596. }
  2597. function closeAddrListModal() {
  2598. document.getElementById('addrlist-modal').classList.add('hidden');
  2599. }
  2600. async function submitSaveAddrList(e) {
  2601. e.preventDefault();
  2602. const name = document.getElementById('addrlist-modal-name').value.trim();
  2603. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  2604. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  2605. try {
  2606. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  2607. method: 'POST',
  2608. headers: { 'Content-Type': 'application/json' },
  2609. body: JSON.stringify({ name, address: addr, comment, disabled: false })
  2610. });
  2611. if (res.ok) {
  2612. showToast('Address List Item Added', `Added ${addr} to ${name}`, 'success');
  2613. closeAddrListModal();
  2614. loadFirewall(false);
  2615. }
  2616. } catch (err) {
  2617. showToast('Error', err.message, 'error');
  2618. }
  2619. }
  2620. async function deleteAddrList(id) {
  2621. try {
  2622. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2623. if (res.ok) {
  2624. showToast('Deleted', 'Address list item removed', 'info');
  2625. loadFirewall(false);
  2626. }
  2627. } catch (err) {
  2628. showToast('Error', err.message, 'error');
  2629. }
  2630. }
  2631. // ----------------- Active Connections Tracking -----------------
  2632. async function loadConnections() {
  2633. try {
  2634. const res = await fetch(`${API_BASE}/firewall/connections`);
  2635. const data = await res.json();
  2636. state.connections = Array.isArray(data) ? data : [];
  2637. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  2638. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  2639. renderConnections();
  2640. } catch (err) {
  2641. console.error('Failed to load connections:', err);
  2642. }
  2643. }
  2644. function renderConnections() {
  2645. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  2646. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  2647. const tbody = document.getElementById('conns-table-body');
  2648. const empty = document.getElementById('conns-empty');
  2649. if (!tbody) return;
  2650. tbody.innerHTML = '';
  2651. const conns = (state.connections || []).filter(c => {
  2652. if (protoFilter && c.protocol !== protoFilter) return false;
  2653. if (search) {
  2654. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  2655. if (!line.includes(search)) return false;
  2656. }
  2657. return true;
  2658. });
  2659. if (conns.length === 0) {
  2660. empty?.classList.remove('hidden');
  2661. return;
  2662. }
  2663. empty?.classList.add('hidden');
  2664. conns.slice(0, 150).forEach(c => {
  2665. const tr = document.createElement('tr');
  2666. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2667. let stateColor = 'text-slate-400';
  2668. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  2669. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  2670. tr.innerHTML = `
  2671. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  2672. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  2673. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  2674. <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>
  2675. <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>
  2676. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  2677. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  2678. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  2679. <td class="py-2.5 px-3 text-right font-sans">
  2680. <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>
  2681. </td>
  2682. `;
  2683. tbody.appendChild(tr);
  2684. });
  2685. }
  2686. async function killConnection(protocol, src, sport, dst, dport) {
  2687. try {
  2688. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  2689. method: 'POST',
  2690. headers: { 'Content-Type': 'application/json' },
  2691. body: JSON.stringify({ protocol, src, sport, dst, dport })
  2692. });
  2693. if (res.ok) {
  2694. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  2695. loadConnections();
  2696. }
  2697. } catch (err) {
  2698. showToast('Error', err.message, 'error');
  2699. }
  2700. }
  2701. async function resetFirewallCounters() {
  2702. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  2703. try {
  2704. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  2705. if (res.ok) {
  2706. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  2707. loadFirewall(false);
  2708. }
  2709. } catch (err) {
  2710. showToast('Error', err.message, 'error');
  2711. }
  2712. }
  2713. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  2714. function switchRoutesSubTab(tab) {
  2715. state.routesSubTab = tab;
  2716. const tabs = ['routes', 'rules', 'tables'];
  2717. tabs.forEach(t => {
  2718. const panel = document.getElementById(`routes-subtab-${t}`);
  2719. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  2720. if (panel) {
  2721. if (t === tab) panel.classList.remove('hidden');
  2722. else panel.classList.add('hidden');
  2723. }
  2724. if (btn) {
  2725. if (t === tab) {
  2726. 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';
  2727. } else {
  2728. 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';
  2729. }
  2730. }
  2731. });
  2732. }
  2733. async function loadRoutes() {
  2734. try {
  2735. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  2736. fetch(`${API_BASE}/routes`),
  2737. fetch(`${API_BASE}/routing/rules`),
  2738. fetch(`${API_BASE}/routing/tables`)
  2739. ]);
  2740. if (routesRes.ok) state.routes = await routesRes.json();
  2741. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  2742. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  2743. const bRoutes = document.getElementById('routes-badge-routes');
  2744. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  2745. const bRules = document.getElementById('routes-badge-rules');
  2746. if (bRules) bRules.innerText = (state.policyRules || []).length;
  2747. const bTables = document.getElementById('routes-badge-tables');
  2748. if (bTables) bTables.innerText = (state.routingTables || []).length;
  2749. const bRoutesCount = document.getElementById('badge-routes-count');
  2750. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  2751. renderRoutesList();
  2752. renderPolicyRules();
  2753. renderRoutingTables();
  2754. } catch (err) {
  2755. console.error('Failed to load routing:', err);
  2756. }
  2757. }
  2758. function renderRoutesList() {
  2759. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  2760. const tbody = document.getElementById('routes-table-body');
  2761. const empty = document.getElementById('routes-empty');
  2762. if (!tbody) return;
  2763. tbody.innerHTML = '';
  2764. // Update table filter select
  2765. const sel = document.getElementById('routes-filter-table');
  2766. if (sel) {
  2767. const cur = sel.value;
  2768. sel.innerHTML = '<option value="">All Tables</option>';
  2769. (state.routingTables || []).forEach(t => {
  2770. const opt = document.createElement('option');
  2771. opt.value = t.name;
  2772. opt.innerText = t.name;
  2773. if (t.name === cur) opt.selected = true;
  2774. sel.appendChild(opt);
  2775. });
  2776. }
  2777. const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
  2778. document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
  2779. if (routes.length === 0) {
  2780. empty?.classList.remove('hidden');
  2781. return;
  2782. }
  2783. empty?.classList.add('hidden');
  2784. routes.forEach(r => {
  2785. const tr = document.createElement('tr');
  2786. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2787. // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
  2788. let flags = '';
  2789. if (r.dynamic) flags += 'D';
  2790. if (r.active) flags += 'A';
  2791. if (r.connect) flags += 'C';
  2792. if (r.static) flags += 'S';
  2793. if (r.disabled) flags += 'X';
  2794. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  2795. tr.innerHTML = `
  2796. <td class="py-2.5 px-3 text-center">
  2797. <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'}">
  2798. ${flags || '-'}
  2799. </span>
  2800. </td>
  2801. <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
  2802. <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>
  2803. <td class="py-2.5 px-3 text-slate-400 font-mono">${r.distance || 1}</td>
  2804. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  2805. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  2806. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  2807. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  2808. ${r.static ? `
  2809. <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>
  2810. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2811. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2812. ` : `<span class="text-slate-600 text-[10px]">Kernel</span>`}
  2813. </td>
  2814. `;
  2815. tbody.appendChild(tr);
  2816. });
  2817. }
  2818. function openAddRouteModal() {
  2819. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  2820. document.getElementById('route-modal-id').value = '';
  2821. document.getElementById('route-modal-dst').value = '0.0.0.0/0';
  2822. document.getElementById('route-modal-gw').value = '';
  2823. document.getElementById('route-modal-distance').value = '1';
  2824. document.getElementById('route-modal-comment').value = '';
  2825. document.getElementById('route-modal-disabled').checked = false;
  2826. populateInterfaceSelect('route-modal-iface');
  2827. // Populate tables
  2828. const sel = document.getElementById('route-modal-table');
  2829. sel.innerHTML = '';
  2830. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  2831. const opt = document.createElement('option');
  2832. opt.value = t.name;
  2833. opt.innerText = t.name;
  2834. if (t.name === 'main') opt.selected = true;
  2835. sel.appendChild(opt);
  2836. });
  2837. document.getElementById('route-modal').classList.remove('hidden');
  2838. }
  2839. function openEditRouteModal(id) {
  2840. const r = (state.routes || []).find(route => route.id === id);
  2841. if (!r) return;
  2842. document.getElementById('route-modal-title').innerText = `Edit Route: ${r.dst_address}`;
  2843. document.getElementById('route-modal-id').value = r.id;
  2844. document.getElementById('route-modal-dst').value = r.dst_address;
  2845. document.getElementById('route-modal-gw').value = r.gateway || '';
  2846. document.getElementById('route-modal-distance').value = r.distance || 1;
  2847. document.getElementById('route-modal-comment').value = r.comment || '';
  2848. document.getElementById('route-modal-disabled').checked = !!r.disabled;
  2849. populateInterfaceSelect('route-modal-iface', r.interface);
  2850. const sel = document.getElementById('route-modal-table');
  2851. sel.innerHTML = '';
  2852. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  2853. const opt = document.createElement('option');
  2854. opt.value = t.name;
  2855. opt.innerText = t.name;
  2856. if (t.name === r.routing_table) opt.selected = true;
  2857. sel.appendChild(opt);
  2858. });
  2859. document.getElementById('route-modal').classList.remove('hidden');
  2860. }
  2861. function closeRouteModal() {
  2862. document.getElementById('route-modal').classList.add('hidden');
  2863. }
  2864. async function submitSaveRoute(e) {
  2865. e.preventDefault();
  2866. const id = document.getElementById('route-modal-id').value;
  2867. const dst = document.getElementById('route-modal-dst').value.trim();
  2868. const gw = document.getElementById('route-modal-gw').value.trim();
  2869. const table = document.getElementById('route-modal-table').value;
  2870. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 1;
  2871. const iface = document.getElementById('route-modal-iface').value;
  2872. const comment = document.getElementById('route-modal-comment').value.trim();
  2873. const disabled = document.getElementById('route-modal-disabled').checked;
  2874. try {
  2875. const res = await fetch(`${API_BASE}/routes`, {
  2876. method: 'POST',
  2877. headers: { 'Content-Type': 'application/json' },
  2878. body: JSON.stringify({
  2879. id,
  2880. dst_address: dst,
  2881. gateway: gw,
  2882. routing_table: table,
  2883. distance,
  2884. interface: iface,
  2885. comment,
  2886. disabled
  2887. })
  2888. });
  2889. if (res.ok) {
  2890. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  2891. closeRouteModal();
  2892. loadRoutes();
  2893. } else {
  2894. const err = await res.json();
  2895. showToast('Error', err.message, 'error');
  2896. }
  2897. } catch (err) {
  2898. showToast('Error', err.message, 'error');
  2899. }
  2900. }
  2901. async function toggleRouteState(id, disabled) {
  2902. try {
  2903. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  2904. method: 'POST',
  2905. headers: { 'Content-Type': 'application/json' },
  2906. body: JSON.stringify({ disabled })
  2907. });
  2908. if (res.ok) loadRoutes();
  2909. } catch (err) {
  2910. showToast('Error', err.message, 'error');
  2911. }
  2912. }
  2913. async function deleteRoute(id) {
  2914. if (!confirm('Are you sure you want to delete this route?')) return;
  2915. try {
  2916. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2917. if (res.ok) {
  2918. showToast('Deleted', 'Route removed', 'success');
  2919. loadRoutes();
  2920. }
  2921. } catch (err) {
  2922. showToast('Error', err.message, 'error');
  2923. }
  2924. }
  2925. // ----------------- Policy Rules (/ip route rule) -----------------
  2926. function renderPolicyRules() {
  2927. const tbody = document.getElementById('rules-table-body');
  2928. const empty = document.getElementById('rules-empty');
  2929. if (!tbody) return;
  2930. tbody.innerHTML = '';
  2931. const rules = state.policyRules || [];
  2932. document.getElementById('rules-count-badge').innerText = `${rules.length} Rules`;
  2933. if (rules.length === 0) {
  2934. empty?.classList.remove('hidden');
  2935. return;
  2936. }
  2937. empty?.classList.add('hidden');
  2938. rules.forEach(pr => {
  2939. const tr = document.createElement('tr');
  2940. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2941. tr.innerHTML = `
  2942. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  2943. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  2944. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  2945. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  2946. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  2947. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  2948. <td class="py-2.5 px-3 text-right font-sans">
  2949. ${pr.priority < 32766 && pr.priority > 0 ? `
  2950. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2951. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  2952. </td>
  2953. `;
  2954. tbody.appendChild(tr);
  2955. });
  2956. }
  2957. function openAddPolicyRuleModal() {
  2958. document.getElementById('prule-modal-pref').value = (state.policyRules || []).length * 10 + 1000;
  2959. document.getElementById('prule-modal-mark').value = '';
  2960. document.getElementById('prule-modal-src').value = '';
  2961. document.getElementById('prule-modal-dst').value = '';
  2962. const sel = document.getElementById('prule-modal-table');
  2963. sel.innerHTML = '';
  2964. (state.routingTables || []).forEach(t => {
  2965. const opt = document.createElement('option');
  2966. opt.value = t.name;
  2967. opt.innerText = t.name;
  2968. sel.appendChild(opt);
  2969. });
  2970. document.getElementById('prule-modal').classList.remove('hidden');
  2971. }
  2972. function closePolicyRuleModal() {
  2973. document.getElementById('prule-modal').classList.add('hidden');
  2974. }
  2975. async function submitSavePolicyRule(e) {
  2976. e.preventDefault();
  2977. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  2978. const mark = document.getElementById('prule-modal-mark').value.trim();
  2979. const src = document.getElementById('prule-modal-src').value.trim();
  2980. const dst = document.getElementById('prule-modal-dst').value.trim();
  2981. const table = document.getElementById('prule-modal-table').value;
  2982. const action = document.getElementById('prule-modal-action').value;
  2983. try {
  2984. const res = await fetch(`${API_BASE}/routing/rules`, {
  2985. method: 'POST',
  2986. headers: { 'Content-Type': 'application/json' },
  2987. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  2988. });
  2989. if (res.ok) {
  2990. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  2991. closePolicyRuleModal();
  2992. loadRoutes();
  2993. } else {
  2994. const err = await res.json();
  2995. showToast('Error', err.message, 'error');
  2996. }
  2997. } catch (err) {
  2998. showToast('Error', err.message, 'error');
  2999. }
  3000. }
  3001. async function deletePolicyRule(id) {
  3002. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  3003. try {
  3004. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3005. if (res.ok) {
  3006. showToast('Rule Removed', 'Policy rule deleted', 'success');
  3007. loadRoutes();
  3008. }
  3009. } catch (err) {
  3010. showToast('Error', err.message, 'error');
  3011. }
  3012. }
  3013. // ----------------- Routing Tables -----------------
  3014. function renderRoutingTables() {
  3015. const tbody = document.getElementById('tables-table-body');
  3016. if (!tbody) return;
  3017. tbody.innerHTML = '';
  3018. (state.routingTables || []).forEach(t => {
  3019. const tr = document.createElement('tr');
  3020. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  3021. tr.innerHTML = `
  3022. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  3023. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  3024. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  3025. `;
  3026. tbody.appendChild(tr);
  3027. });
  3028. }
  3029. function openAddTableModal() {
  3030. document.getElementById('table-modal-name').value = '';
  3031. document.getElementById('table-modal-id').value = '';
  3032. document.getElementById('table-modal-comment').value = '';
  3033. document.getElementById('table-modal').classList.remove('hidden');
  3034. }
  3035. function closeTableModal() {
  3036. document.getElementById('table-modal').classList.add('hidden');
  3037. }
  3038. async function submitSaveTable(e) {
  3039. e.preventDefault();
  3040. const name = document.getElementById('table-modal-name').value.trim();
  3041. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  3042. const comment = document.getElementById('table-modal-comment').value.trim();
  3043. try {
  3044. const res = await fetch(`${API_BASE}/routing/tables`, {
  3045. method: 'POST',
  3046. headers: { 'Content-Type': 'application/json' },
  3047. body: JSON.stringify({ name, table_id: id, comment })
  3048. });
  3049. if (res.ok) {
  3050. showToast('Table Created', `Routing table ${name} registered`, 'success');
  3051. closeTableModal();
  3052. loadRoutes();
  3053. } else {
  3054. const err = await res.json();
  3055. showToast('Error', err.message, 'error');
  3056. }
  3057. } catch (err) {
  3058. showToast('Error', err.message, 'error');
  3059. }
  3060. }
  3061. async function loadDebianConfig() {
  3062. const view = document.getElementById('debian-config-view');
  3063. view.innerText = 'Generating live configuration...';
  3064. try {
  3065. const res = await fetch(`${API_BASE}/debian/config`);
  3066. const data = await res.json();
  3067. view.innerText = data.content || '# Empty config';
  3068. } catch (err) {
  3069. view.innerText = 'Failed to generate Debian network config.';
  3070. }
  3071. }
  3072. async function saveDebianConfig() {
  3073. try {
  3074. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  3075. const data = await res.json();
  3076. if (res.ok) {
  3077. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  3078. loadDebianConfig();
  3079. }
  3080. } catch (err) {
  3081. showToast('Error', err.message, 'error');
  3082. }
  3083. }
  3084. function showToast(title, message, type = 'info') {
  3085. const container = document.getElementById('toast-container');
  3086. const toast = document.createElement('div');
  3087. const borderColors = {
  3088. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  3089. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  3090. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  3091. };
  3092. 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}`;
  3093. toast.innerHTML = `
  3094. <div class="flex-1">
  3095. <div class="font-bold text-xs text-white">${title}</div>
  3096. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  3097. </div>
  3098. `;
  3099. container.appendChild(toast);
  3100. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  3101. setTimeout(() => {
  3102. toast.classList.add('opacity-0', 'translate-y-2');
  3103. setTimeout(() => toast.remove(), 300);
  3104. }, 4000);
  3105. }
  3106. function formatTraffic(bytesPerSec) {
  3107. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  3108. const kb = bytesPerSec / 1024;
  3109. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  3110. const mb = kb / 1024;
  3111. return `${mb.toFixed(2)} MB/s`;
  3112. }
  3113. function toggleSidebar() {
  3114. const sb = document.getElementById('sidebar');
  3115. sb.classList.toggle('-translate-x-full');
  3116. }
  3117. // ======================== EoIP (Ethernet over IP) ========================
  3118. async function loadEoIP(populate = true) {
  3119. try {
  3120. const res = await fetch(`${API_BASE}/vpn/eoip`);
  3121. const data = await res.json();
  3122. state.eoipTunnels = Array.isArray(data) ? data : [];
  3123. const badge = document.getElementById('eoip-count-badge');
  3124. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  3125. const sideBadge = document.getElementById('badge-eoip-count');
  3126. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  3127. renderEoIPTunnels();
  3128. } catch (err) {
  3129. console.error('Failed to load EoIP:', err);
  3130. }
  3131. }
  3132. function renderEoIPTunnels() {
  3133. const tbody = document.getElementById('eoip-table-body');
  3134. const empty = document.getElementById('eoip-empty');
  3135. if (!tbody) return;
  3136. tbody.innerHTML = '';
  3137. const tunnels = state.eoipTunnels || [];
  3138. if (tunnels.length === 0) {
  3139. empty?.classList.remove('hidden');
  3140. return;
  3141. }
  3142. empty?.classList.add('hidden');
  3143. tunnels.forEach(t => {
  3144. const tr = document.createElement('tr');
  3145. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  3146. tr.innerHTML = `
  3147. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  3148. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  3149. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  3150. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  3151. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  3152. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  3153. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  3154. <td class="py-2.5 px-3 font-mono text-[11px]">
  3155. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  3156. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  3157. </td>
  3158. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  3159. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3160. <button onclick="toggleEoIPState('${t.id}', ${!t.disabled})" class="text-xs ${t.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${t.disabled ? 'Enable' : 'Disable'}</button>
  3161. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3162. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  3163. </td>
  3164. `;
  3165. tbody.appendChild(tr);
  3166. });
  3167. }
  3168. function openAddEoIPModal() {
  3169. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  3170. document.getElementById('eoip-modal-id').value = '';
  3171. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  3172. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  3173. document.getElementById('eoip-modal-remote').value = '';
  3174. document.getElementById('eoip-modal-local').value = '';
  3175. document.getElementById('eoip-modal-mac').value = '';
  3176. document.getElementById('eoip-modal-mtu').value = '1500';
  3177. document.getElementById('eoip-modal-comment').value = '';
  3178. document.getElementById('eoip-modal-clampmss').checked = true;
  3179. document.getElementById('eoip-modal-disabled').checked = false;
  3180. document.getElementById('eoip-modal').classList.remove('hidden');
  3181. }
  3182. function openEditEoIPModal(id) {
  3183. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  3184. if (!t) return;
  3185. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  3186. document.getElementById('eoip-modal-id').value = t.id;
  3187. document.getElementById('eoip-modal-name').value = t.name;
  3188. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  3189. document.getElementById('eoip-modal-remote').value = t.remote_address;
  3190. document.getElementById('eoip-modal-local').value = t.local_address || '';
  3191. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  3192. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  3193. document.getElementById('eoip-modal-comment').value = t.comment || '';
  3194. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  3195. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  3196. document.getElementById('eoip-modal').classList.remove('hidden');
  3197. }
  3198. function closeEoIPModal() {
  3199. document.getElementById('eoip-modal').classList.add('hidden');
  3200. }
  3201. async function submitSaveEoIP(e) {
  3202. e.preventDefault();
  3203. const id = document.getElementById('eoip-modal-id').value;
  3204. const name = document.getElementById('eoip-modal-name').value.trim();
  3205. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  3206. const remote = document.getElementById('eoip-modal-remote').value.trim();
  3207. const local = document.getElementById('eoip-modal-local').value.trim();
  3208. const mac = document.getElementById('eoip-modal-mac').value.trim();
  3209. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  3210. const comment = document.getElementById('eoip-modal-comment').value.trim();
  3211. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  3212. const disabled = document.getElementById('eoip-modal-disabled').checked;
  3213. try {
  3214. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  3215. method: 'POST',
  3216. headers: { 'Content-Type': 'application/json' },
  3217. body: JSON.stringify({
  3218. id,
  3219. name,
  3220. tunnel_id: tunnelId,
  3221. remote_address: remote,
  3222. local_address: local,
  3223. mac_address: mac,
  3224. mtu,
  3225. clamp_mss: clampMss,
  3226. comment,
  3227. disabled
  3228. })
  3229. });
  3230. if (res.ok) {
  3231. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  3232. closeEoIPModal();
  3233. loadEoIP(false);
  3234. fetchData(false);
  3235. } else {
  3236. const err = await res.json();
  3237. showToast('Error', err.message, 'error');
  3238. }
  3239. } catch (err) {
  3240. showToast('Error', err.message, 'error');
  3241. }
  3242. }
  3243. async function toggleEoIPState(id, disabled) {
  3244. try {
  3245. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  3246. method: 'POST',
  3247. headers: { 'Content-Type': 'application/json' },
  3248. body: JSON.stringify({ disabled })
  3249. });
  3250. if (res.ok) {
  3251. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  3252. loadEoIP(false);
  3253. fetchData(false);
  3254. }
  3255. } catch (err) {
  3256. showToast('Error', err.message, 'error');
  3257. }
  3258. }
  3259. async function deleteEoIP(id) {
  3260. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  3261. try {
  3262. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3263. if (res.ok) {
  3264. showToast('Deleted', 'EoIP tunnel removed', 'success');
  3265. loadEoIP(false);
  3266. fetchData(false);
  3267. }
  3268. } catch (err) {
  3269. showToast('Error', err.message, 'error');
  3270. }
  3271. }
  3272. // ======================== PPP Central Hub & Servers ========================
  3273. function switchPPPSubTab(tab) {
  3274. state.pppSubTab = tab;
  3275. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  3276. tabs.forEach(t => {
  3277. const panel = document.getElementById(`ppp-subtab-${t}`);
  3278. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  3279. if (panel) {
  3280. if (t === tab) panel.classList.remove('hidden');
  3281. else panel.classList.add('hidden');
  3282. }
  3283. if (btn) {
  3284. if (t === tab) {
  3285. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-violet-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  3286. } else {
  3287. 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';
  3288. }
  3289. }
  3290. });
  3291. const addBtn = document.getElementById('ppp-primary-add-btn');
  3292. if (addBtn) {
  3293. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  3294. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  3295. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  3296. else addBtn.innerHTML = '<span>Save Config</span>';
  3297. }
  3298. if (tab === 'active') loadPPPSessions();
  3299. }
  3300. function openCurrentPPPModal() {
  3301. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  3302. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  3303. else if (state.pppSubTab === 'active') loadPPPSessions();
  3304. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  3305. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  3306. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  3307. }
  3308. async function loadPPP(populateDropdowns = true) {
  3309. await Promise.all([
  3310. loadPPPSecrets(),
  3311. loadPPPProfiles(),
  3312. loadPPPServers(),
  3313. loadPPPSessions()
  3314. ]);
  3315. }
  3316. async function loadPPPSecrets() {
  3317. try {
  3318. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  3319. const data = await res.json();
  3320. state.pppSecrets = Array.isArray(data) ? data : [];
  3321. const b = document.getElementById('ppp-badge-secrets');
  3322. if (b) b.innerText = state.pppSecrets.length;
  3323. const b2 = document.getElementById('secrets-count-badge');
  3324. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  3325. renderPPPSecrets();
  3326. } catch (err) {
  3327. console.error('Failed to load PPP secrets:', err);
  3328. }
  3329. }
  3330. function renderPPPSecrets() {
  3331. const tbody = document.getElementById('secrets-table-body');
  3332. const empty = document.getElementById('secrets-empty');
  3333. if (!tbody) return;
  3334. tbody.innerHTML = '';
  3335. const secrets = state.pppSecrets || [];
  3336. if (secrets.length === 0) {
  3337. empty?.classList.remove('hidden');
  3338. return;
  3339. }
  3340. empty?.classList.add('hidden');
  3341. secrets.forEach(s => {
  3342. const tr = document.createElement('tr');
  3343. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  3344. tr.innerHTML = `
  3345. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  3346. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  3347. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  3348. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  3349. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  3350. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  3351. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  3352. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3353. <button onclick="togglePPPSecretState('${s.id}', ${!s.disabled})" class="text-xs ${s.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${s.disabled ? 'Enable' : 'Disable'}</button>
  3354. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3355. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  3356. </td>
  3357. `;
  3358. tbody.appendChild(tr);
  3359. });
  3360. }
  3361. async function loadPPPProfiles() {
  3362. try {
  3363. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  3364. const data = await res.json();
  3365. state.pppProfiles = Array.isArray(data) ? data : [];
  3366. const b = document.getElementById('ppp-badge-profiles');
  3367. if (b) b.innerText = state.pppProfiles.length;
  3368. const b2 = document.getElementById('profiles-count-badge');
  3369. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  3370. // Populate profile selects across modals
  3371. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  3372. selects.forEach(sid => {
  3373. const el = document.getElementById(sid);
  3374. if (!el) return;
  3375. const cur = el.value;
  3376. el.innerHTML = '';
  3377. state.pppProfiles.forEach(p => {
  3378. const opt = document.createElement('option');
  3379. opt.value = p.name;
  3380. opt.innerText = `${p.name} (${p.remote_address})`;
  3381. if (p.name === cur) opt.selected = true;
  3382. el.appendChild(opt);
  3383. });
  3384. });
  3385. renderPPPProfiles();
  3386. } catch (err) {
  3387. console.error('Failed to load PPP profiles:', err);
  3388. }
  3389. }
  3390. function renderPPPProfiles() {
  3391. const tbody = document.getElementById('profiles-table-body');
  3392. if (!tbody) return;
  3393. tbody.innerHTML = '';
  3394. (state.pppProfiles || []).forEach(p => {
  3395. const isDefault = p.name.startsWith('default');
  3396. const tr = document.createElement('tr');
  3397. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  3398. tr.innerHTML = `
  3399. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  3400. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  3401. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  3402. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  3403. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  3404. <td class="py-2.5 px-3 text-center">${p.only_one ? '<span class="text-emerald-400">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  3405. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  3406. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  3407. ${!isDefault ? `<button onclick="deletePPPProfile('${p.name}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>` : `<span class="text-slate-600 text-[10px]">Built-in</span>`}
  3408. </td>
  3409. `;
  3410. tbody.appendChild(tr);
  3411. });
  3412. }
  3413. async function loadPPPServers() {
  3414. try {
  3415. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  3416. fetch(`${API_BASE}/vpn/servers/pppoe`),
  3417. fetch(`${API_BASE}/vpn/servers/pptp`),
  3418. fetch(`${API_BASE}/vpn/servers/l2tp`),
  3419. fetch(`${API_BASE}/vpn/servers/ipsec`)
  3420. ]);
  3421. if (pppoeRes.ok) {
  3422. state.pppoeServer = await pppoeRes.json();
  3423. const s = state.pppoeServer;
  3424. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  3425. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  3426. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  3427. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  3428. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  3429. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  3430. const pill = document.getElementById('pppoe-server-status-pill');
  3431. if (pill) {
  3432. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  3433. pill.className = s.running ? 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-blue-500/20 text-blue-300 border border-blue-500/40' : 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-slate-800 text-slate-400';
  3434. }
  3435. setDotBadge('ppp-badge-pppoe-state', s.running);
  3436. }
  3437. if (pptpRes.ok) {
  3438. state.pptpServer = await pptpRes.json();
  3439. const s = state.pptpServer;
  3440. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  3441. document.getElementById('pptp-server-port').value = s.port || 1723;
  3442. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  3443. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  3444. const pill = document.getElementById('pptp-server-status-pill');
  3445. if (pill) {
  3446. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  3447. pill.className = s.running ? 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-purple-500/20 text-purple-300 border border-purple-500/40' : 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-slate-800 text-slate-400';
  3448. }
  3449. setDotBadge('ppp-badge-pptp-state', s.running);
  3450. }
  3451. if (l2tpRes.ok) {
  3452. state.l2tpServer = await l2tpRes.json();
  3453. const s = state.l2tpServer;
  3454. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  3455. document.getElementById('l2tp-server-port').value = s.port || 1701;
  3456. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  3457. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  3458. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  3459. const pill = document.getElementById('l2tp-server-status-pill');
  3460. if (pill) {
  3461. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  3462. pill.className = s.running ? 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-cyan-500/20 text-cyan-300 border border-cyan-500/40' : 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-slate-800 text-slate-400';
  3463. }
  3464. setDotBadge('ppp-badge-l2tp-state', s.running);
  3465. }
  3466. if (ipsecRes.ok) {
  3467. state.ipsecServer = await ipsecRes.json();
  3468. const s = state.ipsecServer;
  3469. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  3470. if (modalEn) modalEn.checked = !!s.enabled;
  3471. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  3472. if (modalPsk) modalPsk.value = s.preshared_key || '';
  3473. const modalPool = document.getElementById('modal-ipsec-server-pool');
  3474. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  3475. const modalDns = document.getElementById('modal-ipsec-server-dns');
  3476. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  3477. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  3478. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  3479. const pill = document.getElementById('modal-ipsec-server-status');
  3480. if (pill) {
  3481. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  3482. pill.className = s.running ? 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-amber-500/20 text-amber-300 border border-amber-500/40' : 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-slate-800 text-slate-400';
  3483. }
  3484. }
  3485. } catch (err) {
  3486. console.error('Failed to load VPN servers:', err);
  3487. }
  3488. }
  3489. async function loadPPPSessions() {
  3490. try {
  3491. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  3492. const data = await res.json();
  3493. state.pppActiveSessions = Array.isArray(data) ? data : [];
  3494. const b = document.getElementById('ppp-badge-active');
  3495. if (b) b.innerText = state.pppActiveSessions.length;
  3496. const sideB = document.getElementById('badge-ppp-sessions');
  3497. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  3498. renderPPPSessions();
  3499. } catch (err) {
  3500. console.error('Failed to load active PPP sessions:', err);
  3501. }
  3502. }
  3503. function renderPPPSessions() {
  3504. const tbody = document.getElementById('active-ppp-table-body');
  3505. const empty = document.getElementById('active-ppp-empty');
  3506. if (!tbody) return;
  3507. tbody.innerHTML = '';
  3508. const list = state.pppActiveSessions || [];
  3509. if (list.length === 0) {
  3510. empty?.classList.remove('hidden');
  3511. return;
  3512. }
  3513. empty?.classList.add('hidden');
  3514. list.forEach(s => {
  3515. const tr = document.createElement('tr');
  3516. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  3517. tr.innerHTML = `
  3518. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  3519. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  3520. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  3521. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  3522. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  3523. <td class="py-2.5 px-3 text-[11px]">
  3524. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  3525. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  3526. </td>
  3527. <td class="py-2.5 px-3 text-right font-sans">
  3528. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  3529. </td>
  3530. `;
  3531. tbody.appendChild(tr);
  3532. });
  3533. }
  3534. async function disconnectPPPSession(iface) {
  3535. if (!confirm(`Disconnect session ${iface}?`)) return;
  3536. try {
  3537. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  3538. if (res.ok) {
  3539. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  3540. loadPPPSessions();
  3541. }
  3542. } catch (err) {
  3543. showToast('Error', err.message, 'error');
  3544. }
  3545. }
  3546. // PPP Secret Modal handlers
  3547. function openAddPPPSecretModal() {
  3548. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  3549. document.getElementById('secret-modal-id').value = '';
  3550. document.getElementById('secret-modal-name').value = '';
  3551. document.getElementById('secret-modal-password').value = '';
  3552. document.getElementById('secret-modal-service').value = 'any';
  3553. document.getElementById('secret-modal-profile').value = 'default';
  3554. document.getElementById('secret-modal-local').value = '';
  3555. document.getElementById('secret-modal-remote').value = '';
  3556. document.getElementById('secret-modal-comment').value = '';
  3557. document.getElementById('secret-modal-disabled').checked = false;
  3558. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  3559. }
  3560. function openEditPPPSecretModal(id) {
  3561. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  3562. if (!s) return;
  3563. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  3564. document.getElementById('secret-modal-id').value = s.id;
  3565. document.getElementById('secret-modal-name').value = s.name;
  3566. document.getElementById('secret-modal-password').value = s.password;
  3567. document.getElementById('secret-modal-service').value = s.service || 'any';
  3568. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  3569. document.getElementById('secret-modal-local').value = s.local_address || '';
  3570. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  3571. document.getElementById('secret-modal-comment').value = s.comment || '';
  3572. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  3573. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  3574. }
  3575. function closePPPSecretModal() {
  3576. document.getElementById('ppp-secret-modal').classList.add('hidden');
  3577. }
  3578. async function submitSavePPPSecret(e) {
  3579. e.preventDefault();
  3580. const id = document.getElementById('secret-modal-id').value;
  3581. const name = document.getElementById('secret-modal-name').value.trim();
  3582. const password = document.getElementById('secret-modal-password').value.trim();
  3583. const service = document.getElementById('secret-modal-service').value;
  3584. const profile = document.getElementById('secret-modal-profile').value;
  3585. const local = document.getElementById('secret-modal-local').value.trim();
  3586. const remote = document.getElementById('secret-modal-remote').value.trim();
  3587. const comment = document.getElementById('secret-modal-comment').value.trim();
  3588. const disabled = document.getElementById('secret-modal-disabled').checked;
  3589. try {
  3590. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  3591. method: 'POST',
  3592. headers: { 'Content-Type': 'application/json' },
  3593. body: JSON.stringify({
  3594. id,
  3595. name,
  3596. password,
  3597. service,
  3598. profile,
  3599. local_address: local,
  3600. remote_address: remote,
  3601. comment,
  3602. disabled
  3603. })
  3604. });
  3605. if (res.ok) {
  3606. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  3607. closePPPSecretModal();
  3608. loadPPPSecrets();
  3609. } else {
  3610. const err = await res.json();
  3611. showToast('Error', err.message, 'error');
  3612. }
  3613. } catch (err) {
  3614. showToast('Error', err.message, 'error');
  3615. }
  3616. }
  3617. async function togglePPPSecretState(id, disabled) {
  3618. try {
  3619. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  3620. method: 'POST',
  3621. headers: { 'Content-Type': 'application/json' },
  3622. body: JSON.stringify({ disabled })
  3623. });
  3624. if (res.ok) {
  3625. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  3626. loadPPPSecrets();
  3627. }
  3628. } catch (err) {
  3629. showToast('Error', err.message, 'error');
  3630. }
  3631. }
  3632. async function deletePPPSecret(id) {
  3633. if (!confirm('Are you sure you want to delete this secret account?')) return;
  3634. try {
  3635. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3636. if (res.ok) {
  3637. showToast('Deleted', 'Secret account removed', 'success');
  3638. loadPPPSecrets();
  3639. }
  3640. } catch (err) {
  3641. showToast('Error', err.message, 'error');
  3642. }
  3643. }
  3644. // PPP Profile Modal handlers
  3645. function openAddPPPProfileModal() {
  3646. document.getElementById('profile-modal-name').value = '';
  3647. document.getElementById('profile-modal-local').value = '10.10.10.1';
  3648. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  3649. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  3650. document.getElementById('profile-modal-encryption').value = 'required';
  3651. document.getElementById('profile-modal-onlyone').checked = true;
  3652. document.getElementById('profile-modal-comment').value = '';
  3653. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  3654. }
  3655. function closePPPProfileModal() {
  3656. document.getElementById('ppp-profile-modal').classList.add('hidden');
  3657. }
  3658. async function submitSavePPPProfile(e) {
  3659. e.preventDefault();
  3660. const name = document.getElementById('profile-modal-name').value.trim();
  3661. const local = document.getElementById('profile-modal-local').value.trim();
  3662. const remote = document.getElementById('profile-modal-remote').value.trim();
  3663. const dns = document.getElementById('profile-modal-dns').value.trim();
  3664. const enc = document.getElementById('profile-modal-encryption').value;
  3665. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  3666. const comment = document.getElementById('profile-modal-comment').value.trim();
  3667. try {
  3668. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  3669. method: 'POST',
  3670. headers: { 'Content-Type': 'application/json' },
  3671. body: JSON.stringify({
  3672. id: name,
  3673. name,
  3674. local_address: local,
  3675. remote_address: remote,
  3676. dns_servers: dns,
  3677. use_encryption: enc,
  3678. only_one: onlyone,
  3679. comment
  3680. })
  3681. });
  3682. if (res.ok) {
  3683. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  3684. closePPPProfileModal();
  3685. loadPPPProfiles();
  3686. } else {
  3687. const err = await res.json();
  3688. showToast('Error', err.message, 'error');
  3689. }
  3690. } catch (err) {
  3691. showToast('Error', err.message, 'error');
  3692. }
  3693. }
  3694. async function deletePPPProfile(name) {
  3695. if (!confirm(`Delete PPP profile ${name}?`)) return;
  3696. try {
  3697. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3698. if (res.ok) {
  3699. showToast('Deleted', 'Profile removed', 'success');
  3700. loadPPPProfiles();
  3701. } else {
  3702. const err = await res.json();
  3703. showToast('Error', err.message, 'error');
  3704. }
  3705. } catch (err) {
  3706. showToast('Error', err.message, 'error');
  3707. }
  3708. }
  3709. // Server Config submissions
  3710. async function savePPPoEServerConfig(e) {
  3711. e.preventDefault();
  3712. const enabled = document.getElementById('pppoe-server-enabled').checked;
  3713. const name = document.getElementById('pppoe-server-name').value.trim();
  3714. const iface = document.getElementById('pppoe-server-iface').value;
  3715. const profile = document.getElementById('pppoe-server-profile').value;
  3716. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  3717. const onesession = document.getElementById('pppoe-server-onesession').checked;
  3718. try {
  3719. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  3720. method: 'POST',
  3721. headers: { 'Content-Type': 'application/json' },
  3722. body: JSON.stringify({
  3723. enabled,
  3724. service_name: name,
  3725. interface: iface,
  3726. default_profile: profile,
  3727. max_mtu: mtu,
  3728. max_mru: mtu,
  3729. one_session_per_host: onesession
  3730. })
  3731. });
  3732. if (res.ok) {
  3733. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  3734. loadPPPServers();
  3735. fetchData(false);
  3736. } else {
  3737. const err = await res.json();
  3738. showToast('Error', err.message, 'error');
  3739. }
  3740. } catch (err) {
  3741. showToast('Error', err.message, 'error');
  3742. }
  3743. }
  3744. async function savePPTPServerConfig(e) {
  3745. e.preventDefault();
  3746. const enabled = document.getElementById('pptp-server-enabled').checked;
  3747. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  3748. const profile = document.getElementById('pptp-server-profile').value;
  3749. const mppe = document.getElementById('pptp-server-mppe').checked;
  3750. try {
  3751. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  3752. method: 'POST',
  3753. headers: { 'Content-Type': 'application/json' },
  3754. body: JSON.stringify({
  3755. enabled,
  3756. port,
  3757. default_profile: profile,
  3758. require_mppe: mppe
  3759. })
  3760. });
  3761. if (res.ok) {
  3762. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  3763. loadPPPServers();
  3764. fetchData(false);
  3765. } else {
  3766. const err = await res.json();
  3767. showToast('Error', err.message, 'error');
  3768. }
  3769. } catch (err) {
  3770. showToast('Error', err.message, 'error');
  3771. }
  3772. }
  3773. async function saveL2TPServerConfig(e) {
  3774. e.preventDefault();
  3775. const enabled = document.getElementById('l2tp-server-enabled').checked;
  3776. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  3777. const profile = document.getElementById('l2tp-server-profile').value;
  3778. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  3779. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  3780. try {
  3781. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  3782. method: 'POST',
  3783. headers: { 'Content-Type': 'application/json' },
  3784. body: JSON.stringify({
  3785. enabled,
  3786. port,
  3787. default_profile: profile,
  3788. use_ipsec: useipsec,
  3789. ipsec_secret: psk
  3790. })
  3791. });
  3792. if (res.ok) {
  3793. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  3794. loadPPPServers();
  3795. fetchData(false);
  3796. } else {
  3797. const err = await res.json();
  3798. showToast('Error', err.message, 'error');
  3799. }
  3800. } catch (err) {
  3801. showToast('Error', err.message, 'error');
  3802. }
  3803. }
  3804. // IPSec Server Modal
  3805. function openIPSecServerModal() {
  3806. loadPPPServers();
  3807. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  3808. }
  3809. function closeIPSecServerModal() {
  3810. document.getElementById('ipsec-server-modal').classList.add('hidden');
  3811. }
  3812. async function submitSaveIPSecServer(e) {
  3813. e.preventDefault();
  3814. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  3815. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  3816. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  3817. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  3818. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  3819. try {
  3820. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  3821. method: 'POST',
  3822. headers: { 'Content-Type': 'application/json' },
  3823. body: JSON.stringify({
  3824. enabled,
  3825. preshared_key: psk,
  3826. pool_address: pool,
  3827. dns_servers: dns,
  3828. local_subnet: subnet
  3829. })
  3830. });
  3831. if (res.ok) {
  3832. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  3833. closeIPSecServerModal();
  3834. loadPPPServers();
  3835. fetchData(false);
  3836. } else {
  3837. const err = await res.json();
  3838. showToast('Error', err.message, 'error');
  3839. }
  3840. } catch (err) {
  3841. showToast('Error', err.message, 'error');
  3842. }
  3843. }
  3844. // WireGuard Client Config Viewer
  3845. let currentWGClientConf = '';
  3846. async function openWGClientConfModal(iface, clientIP) {
  3847. try {
  3848. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  3849. method: 'POST',
  3850. headers: { 'Content-Type': 'application/json' },
  3851. body: JSON.stringify({
  3852. interface: iface,
  3853. address: clientIP || '10.10.0.2/32',
  3854. dns: '1.1.1.1, 8.8.8.8'
  3855. })
  3856. });
  3857. if (res.ok) {
  3858. const data = await res.json();
  3859. currentWGClientConf = data.config;
  3860. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  3861. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  3862. } else {
  3863. const err = await res.json();
  3864. showToast('Error', err.message, 'error');
  3865. }
  3866. } catch (err) {
  3867. showToast('Error', err.message, 'error');
  3868. }
  3869. }
  3870. function closeWGClientConfModal() {
  3871. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  3872. }
  3873. function copyWGClientConf() {
  3874. if (!currentWGClientConf) return;
  3875. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  3876. }
  3877. function downloadWGClientConf() {
  3878. if (!currentWGClientConf) return;
  3879. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  3880. const a = document.createElement('a');
  3881. a.href = URL.createObjectURL(blob);
  3882. a.download = 'wireguard-client.conf';
  3883. document.body.appendChild(a);
  3884. a.click();
  3885. document.body.removeChild(a);
  3886. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  3887. }