app.js 216 KB

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