app.js 212 KB

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