app.js 240 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739
  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', 'geo', '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 === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  1956. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  1957. }
  1958. if (tab === 'geo') loadGeoIP();
  1959. if (tab === 'connections') loadConnections();
  1960. }
  1961. function openCurrentFWModal() {
  1962. if (state.fwSubTab === 'filter') openAddFilterModal();
  1963. else if (state.fwSubTab === 'nat') openAddNATModal();
  1964. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  1965. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  1966. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  1967. else if (state.fwSubTab === 'connections') loadConnections();
  1968. }
  1969. async function loadFirewall(populateDropdowns = true) {
  1970. try {
  1971. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  1972. fetch(`${API_BASE}/firewall/summary`),
  1973. fetch(`${API_BASE}/firewall/filter`),
  1974. fetch(`${API_BASE}/firewall/nat`),
  1975. fetch(`${API_BASE}/firewall/mangle`),
  1976. fetch(`${API_BASE}/firewall/address-lists`),
  1977. fetch(`${API_BASE}/firewall/geoip/status`),
  1978. fetch(`${API_BASE}/firewall/geoip/countries`)
  1979. ]);
  1980. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  1981. if (filterRes.ok) state.filterRules = await filterRes.json();
  1982. if (natRes.ok) state.natRules = await natRes.json();
  1983. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  1984. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  1985. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  1986. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  1987. // Badges
  1988. const bFilter = document.getElementById('fw-badge-filter');
  1989. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  1990. const bNat = document.getElementById('fw-badge-nat');
  1991. if (bNat) bNat.innerText = (state.natRules || []).length;
  1992. const bMangle = document.getElementById('fw-badge-mangle');
  1993. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  1994. const bAddr = document.getElementById('fw-badge-addrlist');
  1995. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  1996. const bGeo = document.getElementById('fw-badge-geo');
  1997. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  1998. renderFilterRules();
  1999. renderNATRules();
  2000. renderMangleRules();
  2001. renderAddressLists();
  2002. renderGeoCountries();
  2003. if (state.fwSubTab === 'connections') {
  2004. loadConnections();
  2005. }
  2006. } catch (err) {
  2007. console.error('Failed to load firewall:', err);
  2008. }
  2009. }
  2010. // ----------------- Filter Rules -----------------
  2011. function renderFilterRules() {
  2012. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  2013. const tbody = document.getElementById('filter-table-body');
  2014. const empty = document.getElementById('filter-empty');
  2015. if (!tbody) return;
  2016. tbody.innerHTML = '';
  2017. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2018. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2019. if (rules.length === 0) {
  2020. empty?.classList.remove('hidden');
  2021. return;
  2022. }
  2023. empty?.classList.add('hidden');
  2024. rules.forEach((r, idx) => {
  2025. const tr = document.createElement('tr');
  2026. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2027. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2028. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2029. tr.innerHTML = `
  2030. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2031. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2032. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2033. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2034. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2035. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2036. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2037. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2038. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2039. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2040. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2041. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2042. </td>
  2043. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2044. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2045. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2046. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2047. <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>
  2048. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2049. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2050. </td>
  2051. `;
  2052. tbody.appendChild(tr);
  2053. });
  2054. }
  2055. function formatTarget(addr, list, geo) {
  2056. const parts = [];
  2057. if (addr) parts.push(`<span>${addr}</span>`);
  2058. if (list) {
  2059. const inv = list.startsWith('!') ? '!' : '';
  2060. const clean = list.replace(/^!/, '');
  2061. parts.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-amber-950/80 border border-amber-800/40 text-amber-300 font-mono" title="Address List: ${list}">${inv}list:${clean}</span>`);
  2062. }
  2063. if (geo) {
  2064. const inv = geo.startsWith('!') ? '!' : '';
  2065. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  2066. parts.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-emerald-950/80 border border-emerald-800/40 text-emerald-300 font-mono" title="Geo-Location: ${geo}">🌍 ${inv}${clean}</span>`);
  2067. }
  2068. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  2069. return parts.join(' ');
  2070. }
  2071. function populateInterfaceSelect(selectId, currentVal = '') {
  2072. const sel = document.getElementById(selectId);
  2073. if (!sel) return;
  2074. sel.innerHTML = '<option value="">(Any Interface)</option>';
  2075. (state.interfaces || []).forEach(i => {
  2076. const opt = document.createElement('option');
  2077. opt.value = i.name;
  2078. opt.innerText = `${i.name} (${i.role || i.type})`;
  2079. if (i.name === currentVal) opt.selected = true;
  2080. sel.appendChild(opt);
  2081. });
  2082. }
  2083. function populateAddressListSelect(selectId, currentVal = '') {
  2084. const sel = document.getElementById(selectId);
  2085. if (!sel) return;
  2086. sel.innerHTML = '<option value="">(None)</option>';
  2087. const cleanVal = (currentVal || '').replace(/^!/, '');
  2088. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  2089. customNames.forEach(name => {
  2090. const count = (state.addressLists || []).filter(a => a.name === name).length;
  2091. const opt = document.createElement('option');
  2092. opt.value = name;
  2093. opt.innerText = `${name} (${count} entries)`;
  2094. if (name === cleanVal) opt.selected = true;
  2095. sel.appendChild(opt);
  2096. });
  2097. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  2098. const opt = document.createElement('option');
  2099. opt.value = cleanVal;
  2100. opt.innerText = cleanVal;
  2101. opt.selected = true;
  2102. sel.appendChild(opt);
  2103. }
  2104. }
  2105. function populateGeoIPSelect(selectId, currentVal = '') {
  2106. const sel = document.getElementById(selectId);
  2107. if (!sel) return;
  2108. sel.innerHTML = '<option value="">(None)</option>';
  2109. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  2110. // Presets optgroup
  2111. const grpPresets = document.createElement('optgroup');
  2112. grpPresets.label = '⚡ Regional Presets';
  2113. const presets = [
  2114. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  2115. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  2116. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  2117. ];
  2118. presets.forEach(p => {
  2119. const opt = document.createElement('option');
  2120. opt.value = p.code;
  2121. opt.innerText = p.label;
  2122. if (p.code === cleanVal) opt.selected = true;
  2123. grpPresets.appendChild(opt);
  2124. });
  2125. sel.appendChild(grpPresets);
  2126. // All Countries optgroup
  2127. const grpCountries = document.createElement('optgroup');
  2128. grpCountries.label = '🌍 All Countries';
  2129. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  2130. countries.forEach(c => {
  2131. const opt = document.createElement('option');
  2132. opt.value = c.code;
  2133. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  2134. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  2135. if (c.code === cleanVal) opt.selected = true;
  2136. grpCountries.appendChild(opt);
  2137. });
  2138. sel.appendChild(grpCountries);
  2139. }
  2140. function openAddFilterModal() {
  2141. document.getElementById('filter-modal-title').innerText = 'Add Firewall Filter Rule';
  2142. document.getElementById('filter-modal-id').value = '';
  2143. document.getElementById('filter-modal-chain').value = 'forward';
  2144. document.getElementById('filter-modal-action').value = 'accept';
  2145. document.getElementById('filter-modal-proto').value = 'all';
  2146. document.getElementById('filter-modal-src').value = '';
  2147. document.getElementById('filter-modal-dst').value = '';
  2148. document.getElementById('filter-modal-sport').value = '';
  2149. document.getElementById('filter-modal-dport').value = '';
  2150. document.getElementById('filter-modal-connmark').value = '';
  2151. document.getElementById('filter-modal-comment').value = '';
  2152. document.getElementById('filter-modal-disabled').checked = false;
  2153. document.getElementById('filter-modal-cs-established').checked = false;
  2154. document.getElementById('filter-modal-cs-related').checked = false;
  2155. document.getElementById('filter-modal-cs-new').checked = false;
  2156. document.getElementById('filter-modal-cs-invalid').checked = false;
  2157. populateInterfaceSelect('filter-modal-iniface');
  2158. populateInterfaceSelect('filter-modal-outiface');
  2159. if (document.getElementById('filter-modal-srclist-inv')) document.getElementById('filter-modal-srclist-inv').checked = false;
  2160. if (document.getElementById('filter-modal-dstlist-inv')) document.getElementById('filter-modal-dstlist-inv').checked = false;
  2161. populateAddressListSelect('filter-modal-srclist');
  2162. populateAddressListSelect('filter-modal-dstlist');
  2163. if (document.getElementById('filter-modal-srcgeoip-inv')) document.getElementById('filter-modal-srcgeoip-inv').checked = false;
  2164. if (document.getElementById('filter-modal-dstgeoip-inv')) document.getElementById('filter-modal-dstgeoip-inv').checked = false;
  2165. populateGeoIPSelect('filter-modal-srcgeoip');
  2166. populateGeoIPSelect('filter-modal-dstgeoip');
  2167. toggleFilterActionFields();
  2168. document.getElementById('filter-modal').classList.remove('hidden');
  2169. }
  2170. function openEditFilterModal(id) {
  2171. const r = (state.filterRules || []).find(rule => rule.id === id);
  2172. if (!r) return;
  2173. document.getElementById('filter-modal-title').innerText = `Edit Filter Rule (#${r.order})`;
  2174. document.getElementById('filter-modal-id').value = r.id;
  2175. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  2176. document.getElementById('filter-modal-action').value = r.action || 'accept';
  2177. document.getElementById('filter-modal-proto').value = r.protocol || 'all';
  2178. document.getElementById('filter-modal-src').value = r.src_address || '';
  2179. document.getElementById('filter-modal-dst').value = r.dst_address || '';
  2180. document.getElementById('filter-modal-sport').value = r.src_port || '';
  2181. document.getElementById('filter-modal-dport').value = r.dst_port || '';
  2182. document.getElementById('filter-modal-connmark').value = r.connection_mark || '';
  2183. document.getElementById('filter-modal-comment').value = r.comment || '';
  2184. document.getElementById('filter-modal-disabled').checked = !!r.disabled;
  2185. const states = r.connection_state || [];
  2186. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  2187. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  2188. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  2189. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  2190. populateInterfaceSelect('filter-modal-iniface', r.in_interface);
  2191. populateInterfaceSelect('filter-modal-outiface', r.out_interface);
  2192. const srcInv = (r.src_address_list || '').startsWith('!');
  2193. const dstInv = (r.dst_address_list || '').startsWith('!');
  2194. if (document.getElementById('filter-modal-srclist-inv')) document.getElementById('filter-modal-srclist-inv').checked = srcInv;
  2195. if (document.getElementById('filter-modal-dstlist-inv')) document.getElementById('filter-modal-dstlist-inv').checked = dstInv;
  2196. populateAddressListSelect('filter-modal-srclist', r.src_address_list || '');
  2197. populateAddressListSelect('filter-modal-dstlist', r.dst_address_list || '');
  2198. const srcGeoInv = (r.src_geoip || '').startsWith('!');
  2199. const dstGeoInv = (r.dst_geoip || '').startsWith('!');
  2200. if (document.getElementById('filter-modal-srcgeoip-inv')) document.getElementById('filter-modal-srcgeoip-inv').checked = srcGeoInv;
  2201. if (document.getElementById('filter-modal-dstgeoip-inv')) document.getElementById('filter-modal-dstgeoip-inv').checked = dstGeoInv;
  2202. populateGeoIPSelect('filter-modal-srcgeoip', r.src_geoip || '');
  2203. populateGeoIPSelect('filter-modal-dstgeoip', r.dst_geoip || '');
  2204. toggleFilterActionFields();
  2205. document.getElementById('filter-modal').classList.remove('hidden');
  2206. }
  2207. function closeFilterModal() {
  2208. document.getElementById('filter-modal').classList.add('hidden');
  2209. }
  2210. function toggleFilterActionFields() {
  2211. const act = document.getElementById('filter-modal-action').value;
  2212. const rejectBox = document.getElementById('filter-action-reject-box');
  2213. if (rejectBox) {
  2214. if (act === 'reject') rejectBox.classList.remove('hidden');
  2215. else rejectBox.classList.add('hidden');
  2216. }
  2217. }
  2218. async function submitSaveFilterRule(e) {
  2219. e.preventDefault();
  2220. const id = document.getElementById('filter-modal-id').value;
  2221. const chain = document.getElementById('filter-modal-chain').value;
  2222. const action = document.getElementById('filter-modal-action').value;
  2223. const proto = document.getElementById('filter-modal-proto').value;
  2224. const src = document.getElementById('filter-modal-src').value.trim();
  2225. const dst = document.getElementById('filter-modal-dst').value.trim();
  2226. const sport = document.getElementById('filter-modal-sport').value.trim();
  2227. const dport = document.getElementById('filter-modal-dport').value.trim();
  2228. const inIface = document.getElementById('filter-modal-iniface').value;
  2229. const outIface = document.getElementById('filter-modal-outiface').value;
  2230. const connmark = document.getElementById('filter-modal-connmark').value.trim();
  2231. let srclist = document.getElementById('filter-modal-srclist')?.value || '';
  2232. if (srclist && document.getElementById('filter-modal-srclist-inv')?.checked) {
  2233. srclist = '!' + srclist.replace(/^!/, '');
  2234. }
  2235. let dstlist = document.getElementById('filter-modal-dstlist')?.value || '';
  2236. if (dstlist && document.getElementById('filter-modal-dstlist-inv')?.checked) {
  2237. dstlist = '!' + dstlist.replace(/^!/, '');
  2238. }
  2239. let srcgeoip = document.getElementById('filter-modal-srcgeoip')?.value || '';
  2240. if (srcgeoip && document.getElementById('filter-modal-srcgeoip-inv')?.checked) {
  2241. srcgeoip = '!' + srcgeoip.replace(/^!/, '');
  2242. }
  2243. let dstgeoip = document.getElementById('filter-modal-dstgeoip')?.value || '';
  2244. if (dstgeoip && document.getElementById('filter-modal-dstgeoip-inv')?.checked) {
  2245. dstgeoip = '!' + dstgeoip.replace(/^!/, '');
  2246. }
  2247. const comment = document.getElementById('filter-modal-comment').value.trim();
  2248. const disabled = document.getElementById('filter-modal-disabled').checked;
  2249. const rejectWith = document.getElementById('filter-modal-rejectwith')?.value || '';
  2250. const states = [];
  2251. if (document.getElementById('filter-modal-cs-established').checked) states.push('established');
  2252. if (document.getElementById('filter-modal-cs-related').checked) states.push('related');
  2253. if (document.getElementById('filter-modal-cs-new').checked) states.push('new');
  2254. if (document.getElementById('filter-modal-cs-invalid').checked) states.push('invalid');
  2255. try {
  2256. const res = await fetch(`${API_BASE}/firewall/filter`, {
  2257. method: 'POST',
  2258. headers: { 'Content-Type': 'application/json' },
  2259. body: JSON.stringify({
  2260. id,
  2261. chain,
  2262. action,
  2263. reject_with: rejectWith,
  2264. protocol: proto,
  2265. src_address: src,
  2266. dst_address: dst,
  2267. src_port: sport,
  2268. dst_port: dport,
  2269. in_interface: inIface,
  2270. out_interface: outIface,
  2271. connection_state: states,
  2272. connection_mark: connmark,
  2273. src_address_list: srclist,
  2274. dst_address_list: dstlist,
  2275. src_geoip: srcgeoip,
  2276. dst_geoip: dstgeoip,
  2277. comment,
  2278. disabled
  2279. })
  2280. });
  2281. if (res.ok) {
  2282. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  2283. closeFilterModal();
  2284. loadFirewall(false);
  2285. } else {
  2286. const err = await res.json();
  2287. showToast('Error', err.message, 'error');
  2288. }
  2289. } catch (err) {
  2290. showToast('Error', err.message, 'error');
  2291. }
  2292. }
  2293. async function moveFilterRule(id, dir) {
  2294. try {
  2295. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  2296. method: 'POST',
  2297. headers: { 'Content-Type': 'application/json' },
  2298. body: JSON.stringify({ direction: dir })
  2299. });
  2300. if (res.ok) loadFirewall(false);
  2301. } catch (err) {
  2302. showToast('Error', err.message, 'error');
  2303. }
  2304. }
  2305. async function toggleFilterRuleState(id, disabled) {
  2306. try {
  2307. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  2308. method: 'POST',
  2309. headers: { 'Content-Type': 'application/json' },
  2310. body: JSON.stringify({ disabled })
  2311. });
  2312. if (res.ok) loadFirewall(false);
  2313. } catch (err) {
  2314. showToast('Error', err.message, 'error');
  2315. }
  2316. }
  2317. async function deleteFilterRule(id) {
  2318. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  2319. try {
  2320. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2321. if (res.ok) {
  2322. showToast('Deleted', 'Filter rule removed', 'success');
  2323. loadFirewall(false);
  2324. }
  2325. } catch (err) {
  2326. showToast('Error', err.message, 'error');
  2327. }
  2328. }
  2329. // ----------------- NAT Rules -----------------
  2330. function renderNATRules() {
  2331. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  2332. const tbody = document.getElementById('nat-table-body');
  2333. const empty = document.getElementById('nat-empty');
  2334. if (!tbody) return;
  2335. tbody.innerHTML = '';
  2336. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2337. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  2338. if (rules.length === 0) {
  2339. empty?.classList.remove('hidden');
  2340. return;
  2341. }
  2342. empty?.classList.add('hidden');
  2343. rules.forEach((r, idx) => {
  2344. const tr = document.createElement('tr');
  2345. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2346. const toTarget = [r.to_addresses, r.to_ports].filter(Boolean).join(':');
  2347. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  2348. tr.innerHTML = `
  2349. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2350. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2351. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  2352. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2353. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2354. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  2355. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2356. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2357. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${toTarget || '-'}</td>
  2358. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2359. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2360. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2361. </td>
  2362. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2363. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2364. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2365. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2366. <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>
  2367. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2368. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2369. </td>
  2370. `;
  2371. tbody.appendChild(tr);
  2372. });
  2373. }
  2374. function openAddNATModal() {
  2375. document.getElementById('nat-modal-title').innerText = 'Add NAT Rule';
  2376. document.getElementById('nat-modal-id').value = '';
  2377. document.getElementById('nat-modal-chain').value = 'srcnat';
  2378. document.getElementById('nat-modal-action').value = 'masquerade';
  2379. document.getElementById('nat-modal-toaddr').value = '';
  2380. document.getElementById('nat-modal-toport').value = '';
  2381. document.getElementById('nat-modal-proto').value = 'all';
  2382. document.getElementById('nat-modal-src').value = '';
  2383. document.getElementById('nat-modal-dst').value = '';
  2384. document.getElementById('nat-modal-dport').value = '';
  2385. document.getElementById('nat-modal-comment').value = '';
  2386. document.getElementById('nat-modal-disabled').checked = false;
  2387. populateInterfaceSelect('nat-modal-iniface');
  2388. populateInterfaceSelect('nat-modal-outiface');
  2389. populateAddressListSelect('nat-modal-srclist');
  2390. populateAddressListSelect('nat-modal-dstlist');
  2391. const srcInvEl = document.getElementById('nat-modal-srclist-inv');
  2392. if (srcInvEl) srcInvEl.checked = false;
  2393. const dstInvEl = document.getElementById('nat-modal-dstlist-inv');
  2394. if (dstInvEl) dstInvEl.checked = false;
  2395. populateGeoIPSelect('nat-modal-srcgeoip');
  2396. populateGeoIPSelect('nat-modal-dstgeoip');
  2397. const srcGeoInvEl = document.getElementById('nat-modal-srcgeoip-inv');
  2398. if (srcGeoInvEl) srcGeoInvEl.checked = false;
  2399. const dstGeoInvEl = document.getElementById('nat-modal-dstgeoip-inv');
  2400. if (dstGeoInvEl) dstGeoInvEl.checked = false;
  2401. toggleNATActionFields();
  2402. document.getElementById('nat-modal').classList.remove('hidden');
  2403. }
  2404. function openEditNATModal(id) {
  2405. const r = (state.natRules || []).find(rule => rule.id === id);
  2406. if (!r) return;
  2407. document.getElementById('nat-modal-title').innerText = `Edit NAT Rule (#${r.order})`;
  2408. document.getElementById('nat-modal-id').value = r.id;
  2409. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  2410. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  2411. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  2412. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  2413. document.getElementById('nat-modal-proto').value = r.protocol || 'all';
  2414. document.getElementById('nat-modal-src').value = r.src_address || '';
  2415. document.getElementById('nat-modal-dst').value = r.dst_address || '';
  2416. document.getElementById('nat-modal-dport').value = r.dst_port || '';
  2417. document.getElementById('nat-modal-comment').value = r.comment || '';
  2418. document.getElementById('nat-modal-disabled').checked = !!r.disabled;
  2419. populateInterfaceSelect('nat-modal-iniface', r.in_interface);
  2420. populateInterfaceSelect('nat-modal-outiface', r.out_interface);
  2421. const srcInv = (r.src_address_list || '').startsWith('!');
  2422. const dstInv = (r.dst_address_list || '').startsWith('!');
  2423. const srcInvEl = document.getElementById('nat-modal-srclist-inv');
  2424. if (srcInvEl) srcInvEl.checked = srcInv;
  2425. const dstInvEl = document.getElementById('nat-modal-dstlist-inv');
  2426. if (dstInvEl) dstInvEl.checked = dstInv;
  2427. populateAddressListSelect('nat-modal-srclist', r.src_address_list || '');
  2428. populateAddressListSelect('nat-modal-dstlist', r.dst_address_list || '');
  2429. const srcGeoInv = (r.src_geoip || '').startsWith('!');
  2430. const dstGeoInv = (r.dst_geoip || '').startsWith('!');
  2431. const srcGeoInvEl = document.getElementById('nat-modal-srcgeoip-inv');
  2432. if (srcGeoInvEl) srcGeoInvEl.checked = srcGeoInv;
  2433. const dstGeoInvEl = document.getElementById('nat-modal-dstgeoip-inv');
  2434. if (dstGeoInvEl) dstGeoInvEl.checked = dstGeoInv;
  2435. populateGeoIPSelect('nat-modal-srcgeoip', r.src_geoip || '');
  2436. populateGeoIPSelect('nat-modal-dstgeoip', r.dst_geoip || '');
  2437. toggleNATActionFields();
  2438. document.getElementById('nat-modal').classList.remove('hidden');
  2439. }
  2440. function closeNATModal() {
  2441. document.getElementById('nat-modal').classList.add('hidden');
  2442. }
  2443. function toggleNATChainFields() {
  2444. const ch = document.getElementById('nat-modal-chain').value;
  2445. const actSel = document.getElementById('nat-modal-action');
  2446. if (ch === 'srcnat' && actSel.value === 'dst-nat') {
  2447. actSel.value = 'masquerade';
  2448. } else if (ch === 'dstnat' && actSel.value === 'masquerade') {
  2449. actSel.value = 'dst-nat';
  2450. }
  2451. toggleNATActionFields();
  2452. }
  2453. function toggleNATActionFields() {
  2454. const act = document.getElementById('nat-modal-action').value;
  2455. const toBox = document.getElementById('nat-action-to-box');
  2456. if (toBox) {
  2457. if (act === 'masquerade' || act === 'accept') toBox.classList.add('hidden');
  2458. else toBox.classList.remove('hidden');
  2459. }
  2460. }
  2461. async function submitSaveNATRule(e) {
  2462. e.preventDefault();
  2463. const id = document.getElementById('nat-modal-id').value;
  2464. const chain = document.getElementById('nat-modal-chain').value;
  2465. const action = document.getElementById('nat-modal-action').value;
  2466. const toaddr = document.getElementById('nat-modal-toaddr').value.trim();
  2467. const toport = document.getElementById('nat-modal-toport').value.trim();
  2468. const proto = document.getElementById('nat-modal-proto').value;
  2469. const src = document.getElementById('nat-modal-src').value.trim();
  2470. const dst = document.getElementById('nat-modal-dst').value.trim();
  2471. const dport = document.getElementById('nat-modal-dport').value.trim();
  2472. const inIface = document.getElementById('nat-modal-iniface').value;
  2473. const outIface = document.getElementById('nat-modal-outiface').value;
  2474. let srclist = document.getElementById('nat-modal-srclist')?.value || '';
  2475. if (srclist && document.getElementById('nat-modal-srclist-inv')?.checked) {
  2476. srclist = '!' + srclist.replace(/^!/, '');
  2477. }
  2478. let dstlist = document.getElementById('nat-modal-dstlist')?.value || '';
  2479. if (dstlist && document.getElementById('nat-modal-dstlist-inv')?.checked) {
  2480. dstlist = '!' + dstlist.replace(/^!/, '');
  2481. }
  2482. let srcgeoip = document.getElementById('nat-modal-srcgeoip')?.value || '';
  2483. if (srcgeoip && document.getElementById('nat-modal-srcgeoip-inv')?.checked) {
  2484. srcgeoip = '!' + srcgeoip.replace(/^!/, '');
  2485. }
  2486. let dstgeoip = document.getElementById('nat-modal-dstgeoip')?.value || '';
  2487. if (dstgeoip && document.getElementById('nat-modal-dstgeoip-inv')?.checked) {
  2488. dstgeoip = '!' + dstgeoip.replace(/^!/, '');
  2489. }
  2490. const comment = document.getElementById('nat-modal-comment').value.trim();
  2491. const disabled = document.getElementById('nat-modal-disabled').checked;
  2492. try {
  2493. const res = await fetch(`${API_BASE}/firewall/nat`, {
  2494. method: 'POST',
  2495. headers: { 'Content-Type': 'application/json' },
  2496. body: JSON.stringify({
  2497. id,
  2498. chain,
  2499. action,
  2500. to_addresses: toaddr,
  2501. to_ports: toport,
  2502. protocol: proto,
  2503. src_address: src,
  2504. dst_address: dst,
  2505. dst_port: dport,
  2506. in_interface: inIface,
  2507. out_interface: outIface,
  2508. src_address_list: srclist,
  2509. dst_address_list: dstlist,
  2510. src_geoip: srcgeoip,
  2511. dst_geoip: dstgeoip,
  2512. comment,
  2513. disabled
  2514. })
  2515. });
  2516. if (res.ok) {
  2517. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  2518. closeNATModal();
  2519. loadFirewall(false);
  2520. }
  2521. } catch (err) {
  2522. showToast('Error', err.message, 'error');
  2523. }
  2524. }
  2525. async function moveNATRule(id, dir) {
  2526. try {
  2527. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  2528. method: 'POST',
  2529. headers: { 'Content-Type': 'application/json' },
  2530. body: JSON.stringify({ direction: dir })
  2531. });
  2532. if (res.ok) loadFirewall(false);
  2533. } catch (err) {
  2534. showToast('Error', err.message, 'error');
  2535. }
  2536. }
  2537. async function toggleNATRuleState(id, disabled) {
  2538. try {
  2539. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  2540. method: 'POST',
  2541. headers: { 'Content-Type': 'application/json' },
  2542. body: JSON.stringify({ disabled })
  2543. });
  2544. if (res.ok) loadFirewall(false);
  2545. } catch (err) {
  2546. showToast('Error', err.message, 'error');
  2547. }
  2548. }
  2549. async function deleteNATRule(id) {
  2550. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  2551. try {
  2552. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2553. if (res.ok) {
  2554. showToast('Deleted', 'NAT rule removed', 'success');
  2555. loadFirewall(false);
  2556. }
  2557. } catch (err) {
  2558. showToast('Error', err.message, 'error');
  2559. }
  2560. }
  2561. // ----------------- Mangle Rules -----------------
  2562. function renderMangleRules() {
  2563. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  2564. const tbody = document.getElementById('mangle-table-body');
  2565. const empty = document.getElementById('mangle-empty');
  2566. if (!tbody) return;
  2567. tbody.innerHTML = '';
  2568. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2569. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  2570. if (rules.length === 0) {
  2571. empty?.classList.remove('hidden');
  2572. return;
  2573. }
  2574. empty?.classList.add('hidden');
  2575. rules.forEach((r, idx) => {
  2576. const tr = document.createElement('tr');
  2577. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2578. const markVal = r.new_connection_mark || r.new_routing_mark || r.new_packet_mark || r.new_mss || (r.new_dscp ? 'DSCP:' + r.new_dscp : '');
  2579. tr.innerHTML = `
  2580. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2581. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2582. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  2583. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2584. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2585. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2586. <td class="py-2.5 px-3 font-mono font-bold text-cyan-300">${markVal || '-'}</td>
  2587. <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>
  2588. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2589. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2590. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2591. </td>
  2592. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2593. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2594. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2595. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2596. <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>
  2597. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2598. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2599. </td>
  2600. `;
  2601. tbody.appendChild(tr);
  2602. });
  2603. }
  2604. function openAddMangleModal() {
  2605. document.getElementById('mangle-modal-title').innerText = 'Add Mangle Rule';
  2606. document.getElementById('mangle-modal-id').value = '';
  2607. document.getElementById('mangle-modal-chain').value = 'prerouting';
  2608. document.getElementById('mangle-modal-action').value = 'mark-connection';
  2609. document.getElementById('mangle-modal-newmark').value = '';
  2610. document.getElementById('mangle-modal-passthrough').checked = true;
  2611. document.getElementById('mangle-modal-src').value = '';
  2612. document.getElementById('mangle-modal-dst').value = '';
  2613. document.getElementById('mangle-modal-connmark').value = '';
  2614. document.getElementById('mangle-modal-comment').value = '';
  2615. document.getElementById('mangle-modal-disabled').checked = false;
  2616. populateInterfaceSelect('mangle-modal-iniface');
  2617. populateAddressListSelect('mangle-modal-srclist');
  2618. populateAddressListSelect('mangle-modal-dstlist');
  2619. const srcInvEl = document.getElementById('mangle-modal-srclist-inv');
  2620. if (srcInvEl) srcInvEl.checked = false;
  2621. const dstInvEl = document.getElementById('mangle-modal-dstlist-inv');
  2622. if (dstInvEl) dstInvEl.checked = false;
  2623. populateGeoIPSelect('mangle-modal-srcgeoip');
  2624. populateGeoIPSelect('mangle-modal-dstgeoip');
  2625. const srcGeoInvEl = document.getElementById('mangle-modal-srcgeoip-inv');
  2626. if (srcGeoInvEl) srcGeoInvEl.checked = false;
  2627. const dstGeoInvEl = document.getElementById('mangle-modal-dstgeoip-inv');
  2628. if (dstGeoInvEl) dstGeoInvEl.checked = false;
  2629. document.getElementById('mangle-modal').classList.remove('hidden');
  2630. }
  2631. function openEditMangleModal(id) {
  2632. const r = (state.mangleRules || []).find(rule => rule.id === id);
  2633. if (!r) return;
  2634. document.getElementById('mangle-modal-title').innerText = `Edit Mangle Rule (#${r.order})`;
  2635. document.getElementById('mangle-modal-id').value = r.id;
  2636. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  2637. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  2638. document.getElementById('mangle-modal-newmark').value = r.new_connection_mark || r.new_routing_mark || r.new_packet_mark || r.new_mss || '';
  2639. document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  2640. document.getElementById('mangle-modal-src').value = r.src_address || '';
  2641. document.getElementById('mangle-modal-dst').value = r.dst_address || '';
  2642. document.getElementById('mangle-modal-connmark').value = r.connection_mark || '';
  2643. document.getElementById('mangle-modal-comment').value = r.comment || '';
  2644. document.getElementById('mangle-modal-disabled').checked = !!r.disabled;
  2645. populateInterfaceSelect('mangle-modal-iniface', r.in_interface);
  2646. const srcInv = (r.src_address_list || '').startsWith('!');
  2647. const dstInv = (r.dst_address_list || '').startsWith('!');
  2648. const srcInvEl = document.getElementById('mangle-modal-srclist-inv');
  2649. if (srcInvEl) srcInvEl.checked = srcInv;
  2650. const dstInvEl = document.getElementById('mangle-modal-dstlist-inv');
  2651. if (dstInvEl) dstInvEl.checked = dstInv;
  2652. populateAddressListSelect('mangle-modal-srclist', r.src_address_list || '');
  2653. populateAddressListSelect('mangle-modal-dstlist', r.dst_address_list || '');
  2654. const srcGeoInv = (r.src_geoip || '').startsWith('!');
  2655. const dstGeoInv = (r.dst_geoip || '').startsWith('!');
  2656. const srcGeoInvEl = document.getElementById('mangle-modal-srcgeoip-inv');
  2657. if (srcGeoInvEl) srcGeoInvEl.checked = srcGeoInv;
  2658. const dstGeoInvEl = document.getElementById('mangle-modal-dstgeoip-inv');
  2659. if (dstGeoInvEl) dstGeoInvEl.checked = dstGeoInv;
  2660. populateGeoIPSelect('mangle-modal-srcgeoip', r.src_geoip || '');
  2661. populateGeoIPSelect('mangle-modal-dstgeoip', r.dst_geoip || '');
  2662. document.getElementById('mangle-modal').classList.remove('hidden');
  2663. }
  2664. function closeMangleModal() {
  2665. document.getElementById('mangle-modal').classList.add('hidden');
  2666. }
  2667. function toggleMangleActionFields() {
  2668. // Handled smoothly by single dynamic input
  2669. }
  2670. async function submitSaveMangleRule(e) {
  2671. e.preventDefault();
  2672. const id = document.getElementById('mangle-modal-id').value;
  2673. const chain = document.getElementById('mangle-modal-chain').value;
  2674. const action = document.getElementById('mangle-modal-action').value;
  2675. const newmark = document.getElementById('mangle-modal-newmark').value.trim();
  2676. const passthrough = document.getElementById('mangle-modal-passthrough').checked;
  2677. const src = document.getElementById('mangle-modal-src').value.trim();
  2678. const dst = document.getElementById('mangle-modal-dst').value.trim();
  2679. const inIface = document.getElementById('mangle-modal-iniface').value;
  2680. let srclist = document.getElementById('mangle-modal-srclist')?.value || '';
  2681. if (srclist && document.getElementById('mangle-modal-srclist-inv')?.checked) {
  2682. srclist = '!' + srclist.replace(/^!/, '');
  2683. }
  2684. let dstlist = document.getElementById('mangle-modal-dstlist')?.value || '';
  2685. if (dstlist && document.getElementById('mangle-modal-dstlist-inv')?.checked) {
  2686. dstlist = '!' + dstlist.replace(/^!/, '');
  2687. }
  2688. let srcgeoip = document.getElementById('mangle-modal-srcgeoip')?.value || '';
  2689. if (srcgeoip && document.getElementById('mangle-modal-srcgeoip-inv')?.checked) {
  2690. srcgeoip = '!' + srcgeoip.replace(/^!/, '');
  2691. }
  2692. let dstgeoip = document.getElementById('mangle-modal-dstgeoip')?.value || '';
  2693. if (dstgeoip && document.getElementById('mangle-modal-dstgeoip-inv')?.checked) {
  2694. dstgeoip = '!' + dstgeoip.replace(/^!/, '');
  2695. }
  2696. const connmark = document.getElementById('mangle-modal-connmark').value.trim();
  2697. const comment = document.getElementById('mangle-modal-comment').value.trim();
  2698. const disabled = document.getElementById('mangle-modal-disabled').checked;
  2699. const payload = {
  2700. id,
  2701. chain,
  2702. action,
  2703. passthrough,
  2704. src_address: src,
  2705. dst_address: dst,
  2706. in_interface: inIface,
  2707. src_address_list: srclist,
  2708. dst_address_list: dstlist,
  2709. src_geoip: srcgeoip,
  2710. dst_geoip: dstgeoip,
  2711. connection_mark: connmark,
  2712. comment,
  2713. disabled
  2714. };
  2715. if (action === 'mark-connection') payload.new_connection_mark = newmark;
  2716. else if (action === 'mark-routing') payload.new_routing_mark = newmark;
  2717. else if (action === 'mark-packet') payload.new_packet_mark = newmark;
  2718. else if (action === 'change-mss') payload.new_mss = newmark || 'clamp-to-pmtu';
  2719. try {
  2720. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  2721. method: 'POST',
  2722. headers: { 'Content-Type': 'application/json' },
  2723. body: JSON.stringify(payload)
  2724. });
  2725. if (res.ok) {
  2726. showToast('Mangle Rule Saved', 'Marking rule applied', 'success');
  2727. closeMangleModal();
  2728. loadFirewall(false);
  2729. }
  2730. } catch (err) {
  2731. showToast('Error', err.message, 'error');
  2732. }
  2733. }
  2734. async function moveMangleRule(id, dir) {
  2735. try {
  2736. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  2737. method: 'POST',
  2738. headers: { 'Content-Type': 'application/json' },
  2739. body: JSON.stringify({ direction: dir })
  2740. });
  2741. if (res.ok) loadFirewall(false);
  2742. } catch (err) {
  2743. showToast('Error', err.message, 'error');
  2744. }
  2745. }
  2746. async function toggleMangleRuleState(id, disabled) {
  2747. try {
  2748. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  2749. method: 'POST',
  2750. headers: { 'Content-Type': 'application/json' },
  2751. body: JSON.stringify({ disabled })
  2752. });
  2753. if (res.ok) loadFirewall(false);
  2754. } catch (err) {
  2755. showToast('Error', err.message, 'error');
  2756. }
  2757. }
  2758. async function deleteMangleRule(id) {
  2759. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  2760. try {
  2761. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2762. if (res.ok) {
  2763. showToast('Deleted', 'Mangle rule removed', 'success');
  2764. loadFirewall(false);
  2765. }
  2766. } catch (err) {
  2767. showToast('Error', err.message, 'error');
  2768. }
  2769. }
  2770. // ----------------- Address Lists -----------------
  2771. function renderAddressLists() {
  2772. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  2773. const tbody = document.getElementById('addrlist-table-body');
  2774. const empty = document.getElementById('addrlist-empty');
  2775. if (!tbody) return;
  2776. tbody.innerHTML = '';
  2777. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  2778. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  2779. // Update filter select
  2780. const sel = document.getElementById('addrlist-filter-name');
  2781. if (sel) {
  2782. const cur = sel.value;
  2783. sel.innerHTML = '<option value="">All Lists</option>';
  2784. const set = new Set((state.addressLists || []).map(a => a.name));
  2785. set.forEach(n => {
  2786. const opt = document.createElement('option');
  2787. opt.value = n;
  2788. opt.innerText = n;
  2789. if (n === cur) opt.selected = true;
  2790. sel.appendChild(opt);
  2791. });
  2792. }
  2793. if (entries.length === 0) {
  2794. empty?.classList.remove('hidden');
  2795. return;
  2796. }
  2797. empty?.classList.add('hidden');
  2798. entries.forEach((e, idx) => {
  2799. const tr = document.createElement('tr');
  2800. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  2801. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  2802. tr.innerHTML = `
  2803. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  2804. <td class="py-2.5 px-3 text-center">${e.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '<span class="text-emerald-400 font-bold">✓</span>'}</td>
  2805. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  2806. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  2807. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  2808. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  2809. <button onclick="toggleAddrListState('${e.id}', ${!e.disabled})" class="text-xs ${e.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${e.disabled ? 'Enable' : 'Disable'}</button>
  2810. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  2811. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2812. </td>
  2813. `;
  2814. tbody.appendChild(tr);
  2815. });
  2816. }
  2817. function openAddAddrListModal() {
  2818. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  2819. document.getElementById('addrlist-modal-id').value = '';
  2820. document.getElementById('addrlist-modal-name').value = '';
  2821. document.getElementById('addrlist-modal-addr').value = '';
  2822. document.getElementById('addrlist-modal-comment').value = '';
  2823. document.getElementById('addrlist-modal-disabled').checked = false;
  2824. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  2825. if (submitBtn) submitBtn.innerText = 'Add to List';
  2826. document.getElementById('addrlist-modal').classList.remove('hidden');
  2827. }
  2828. function openEditAddrListModal(id) {
  2829. const e = (state.addressLists || []).find(item => item.id === id);
  2830. if (!e) return;
  2831. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  2832. document.getElementById('addrlist-modal-id').value = e.id;
  2833. document.getElementById('addrlist-modal-name').value = e.name;
  2834. document.getElementById('addrlist-modal-addr').value = e.address;
  2835. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  2836. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  2837. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  2838. if (submitBtn) submitBtn.innerText = 'Save Changes';
  2839. document.getElementById('addrlist-modal').classList.remove('hidden');
  2840. }
  2841. function closeAddrListModal() {
  2842. document.getElementById('addrlist-modal').classList.add('hidden');
  2843. }
  2844. async function submitSaveAddrList(e) {
  2845. e.preventDefault();
  2846. const id = document.getElementById('addrlist-modal-id').value;
  2847. const name = document.getElementById('addrlist-modal-name').value.trim();
  2848. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  2849. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  2850. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  2851. try {
  2852. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  2853. method: 'POST',
  2854. headers: { 'Content-Type': 'application/json' },
  2855. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  2856. });
  2857. if (res.ok) {
  2858. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  2859. closeAddrListModal();
  2860. loadFirewall(false);
  2861. } else {
  2862. const err = await res.json();
  2863. showToast('Error', err.message || 'Failed to save address list', 'error');
  2864. }
  2865. } catch (err) {
  2866. showToast('Error', err.message, 'error');
  2867. }
  2868. }
  2869. async function toggleAddrListState(id, disabled) {
  2870. try {
  2871. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  2872. method: 'POST',
  2873. headers: { 'Content-Type': 'application/json' },
  2874. body: JSON.stringify({ disabled })
  2875. });
  2876. if (res.ok) {
  2877. loadFirewall(false);
  2878. }
  2879. } catch (err) {
  2880. showToast('Error', err.message, 'error');
  2881. }
  2882. }
  2883. async function deleteAddrList(id) {
  2884. if (!confirm('Are you sure you want to delete this address list item?')) return;
  2885. try {
  2886. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2887. if (res.ok) {
  2888. showToast('Deleted', 'Address list item removed', 'info');
  2889. loadFirewall(false);
  2890. }
  2891. } catch (err) {
  2892. showToast('Error', err.message, 'error');
  2893. }
  2894. }
  2895. // ----------------- Geo-Location IP Management -----------------
  2896. async function loadGeoIP() {
  2897. try {
  2898. const [statusRes, countriesRes] = await Promise.all([
  2899. fetch(`${API_BASE}/firewall/geoip/status`),
  2900. fetch(`${API_BASE}/firewall/geoip/countries`)
  2901. ]);
  2902. if (statusRes.ok) state.geoStatus = await statusRes.json();
  2903. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  2904. updateGeoHeader();
  2905. renderGeoCountries();
  2906. } catch (err) {
  2907. console.error('Failed to load GeoIP:', err);
  2908. }
  2909. }
  2910. function updateGeoHeader() {
  2911. const s = state.geoStatus || {};
  2912. const statusBadge = document.getElementById('geo-status-badge');
  2913. if (statusBadge) {
  2914. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  2915. statusBadge.className = s.auto_update
  2916. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  2917. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  2918. }
  2919. const intervalLabel = document.getElementById('geo-interval-label');
  2920. if (intervalLabel) {
  2921. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  2922. }
  2923. const activeCountEl = document.getElementById('geo-stat-active-countries');
  2924. if (activeCountEl) activeCountEl.innerText = (s.enabled_count || 0).toLocaleString();
  2925. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  2926. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  2927. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  2928. if (lastSyncEl) {
  2929. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  2930. const d = new Date(s.last_updated);
  2931. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  2932. } else {
  2933. lastSyncEl.innerText = 'Never (Sync Pending)';
  2934. }
  2935. }
  2936. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  2937. if (nextSyncEl) {
  2938. if (s.next_update && !s.next_update.startsWith('0001')) {
  2939. const d = new Date(s.next_update);
  2940. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  2941. } else {
  2942. nextSyncEl.innerText = '-';
  2943. }
  2944. }
  2945. const badge = document.getElementById('fw-badge-geo');
  2946. if (badge) badge.innerText = s.enabled_count || 0;
  2947. }
  2948. function renderGeoCountries() {
  2949. const tbody = document.getElementById('geo-table-body');
  2950. const empty = document.getElementById('geo-empty');
  2951. if (!tbody) return;
  2952. tbody.innerHTML = '';
  2953. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  2954. const continent = document.getElementById('geo-continent-filter')?.value || '';
  2955. const enabledOnly = document.getElementById('geo-filter-enabled-only')?.checked;
  2956. const countries = (state.geoCountries || []).filter(c => {
  2957. if (enabledOnly && !c.enabled) return false;
  2958. if (continent && c.continent !== continent) return false;
  2959. if (q) {
  2960. const matchCode = c.code.toLowerCase().includes(q);
  2961. const matchName = c.name.toLowerCase().includes(q);
  2962. if (!matchCode && !matchName) return false;
  2963. }
  2964. return true;
  2965. });
  2966. if (countries.length === 0) {
  2967. empty?.classList.remove('hidden');
  2968. return;
  2969. }
  2970. empty?.classList.add('hidden');
  2971. countries.forEach(c => {
  2972. const tr = document.createElement('tr');
  2973. tr.className = `hover:bg-slate-800/40 transition text-xs ${c.enabled ? 'bg-emerald-950/10' : ''}`;
  2974. tr.innerHTML = `
  2975. <td class="py-2.5 px-3 text-center">
  2976. <span class="px-2 py-0.5 rounded font-mono font-bold ${c.enabled ? 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/40' : 'bg-slate-800 text-cyan-300 border border-slate-700'}">
  2977. ${c.code}
  2978. </span>
  2979. </td>
  2980. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  2981. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  2982. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  2983. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  2984. </td>
  2985. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  2986. <td class="py-2.5 px-3">
  2987. ${c.enabled
  2988. ? '<span class="px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/40">ENABLED</span>'
  2989. : '<span class="px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-500">DISABLED</span>'}
  2990. </td>
  2991. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  2992. ${c.enabled
  2993. ? `<button onclick="toggleGeoCountry('${c.code}', false)" class="text-xs text-rose-400 hover:underline font-semibold">Disable</button>`
  2994. : `<button onclick="toggleGeoCountry('${c.code}', true)" class="text-xs text-emerald-400 hover:underline font-semibold">Enable</button>`}
  2995. <button onclick="updateGeoCountry('${c.code}')" class="text-xs text-cyan-400 hover:text-cyan-300" title="Re-download latest country IP blocks">Sync</button>
  2996. <button onclick="viewGeoSubnets('${c.code}', '${c.name.replace(/'/g, "\\'")}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  2997. </td>
  2998. `;
  2999. tbody.appendChild(tr);
  3000. });
  3001. }
  3002. async function toggleGeoCountry(code, enabled) {
  3003. try {
  3004. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  3005. method: 'POST',
  3006. headers: { 'Content-Type': 'application/json' },
  3007. body: JSON.stringify({ enabled })
  3008. });
  3009. if (res.ok) {
  3010. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  3011. loadGeoIP();
  3012. } else {
  3013. const err = await res.json();
  3014. showToast('Error', err.message || 'Failed to toggle country', 'error');
  3015. }
  3016. } catch (err) {
  3017. showToast('Error', err.message, 'error');
  3018. }
  3019. }
  3020. async function updateGeoCountry(code) {
  3021. try {
  3022. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  3023. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  3024. if (res.ok) {
  3025. const data = await res.json();
  3026. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  3027. loadGeoIP();
  3028. } else {
  3029. const err = await res.json();
  3030. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  3031. }
  3032. } catch (err) {
  3033. showToast('Error', err.message, 'error');
  3034. }
  3035. }
  3036. async function triggerGeoUpdateNow() {
  3037. const spinner = document.getElementById('geo-update-spinner');
  3038. if (spinner) spinner.classList.remove('hidden');
  3039. try {
  3040. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  3041. if (res.ok) {
  3042. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  3043. setTimeout(() => {
  3044. loadGeoIP();
  3045. if (spinner) spinner.classList.add('hidden');
  3046. }, 2500);
  3047. } else {
  3048. const err = await res.json();
  3049. showToast('Notice', err.message || 'Update in progress', 'info');
  3050. if (spinner) spinner.classList.add('hidden');
  3051. }
  3052. } catch (err) {
  3053. showToast('Error', err.message, 'error');
  3054. if (spinner) spinner.classList.add('hidden');
  3055. }
  3056. }
  3057. async function applyGeoPreset(preset) {
  3058. try {
  3059. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  3060. method: 'POST',
  3061. headers: { 'Content-Type': 'application/json' },
  3062. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  3063. });
  3064. if (res.ok) {
  3065. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  3066. loadGeoIP();
  3067. }
  3068. } catch (err) {
  3069. showToast('Error', err.message, 'error');
  3070. }
  3071. }
  3072. function openGeoIntervalModal() {
  3073. const s = state.geoStatus || {};
  3074. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  3075. const sel = document.getElementById('geo-cfg-interval');
  3076. const customBox = document.getElementById('geo-cfg-custom-box');
  3077. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  3078. const curHours = s.interval_hours || 24;
  3079. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  3080. if (matchOption) {
  3081. sel.value = String(curHours);
  3082. customBox.classList.add('hidden');
  3083. } else {
  3084. sel.value = 'custom';
  3085. customHoursInput.value = curHours;
  3086. customBox.classList.remove('hidden');
  3087. }
  3088. document.getElementById('geo-interval-modal').classList.remove('hidden');
  3089. }
  3090. function closeGeoIntervalModal() {
  3091. document.getElementById('geo-interval-modal').classList.add('hidden');
  3092. }
  3093. function toggleCustomGeoInterval() {
  3094. const val = document.getElementById('geo-cfg-interval').value;
  3095. const customBox = document.getElementById('geo-cfg-custom-box');
  3096. if (val === 'custom') {
  3097. customBox.classList.remove('hidden');
  3098. } else {
  3099. customBox.classList.add('hidden');
  3100. }
  3101. }
  3102. async function submitGeoIntervalSettings(e) {
  3103. e.preventDefault();
  3104. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  3105. const intervalVal = document.getElementById('geo-cfg-interval').value;
  3106. let hours = 24;
  3107. if (intervalVal === 'custom') {
  3108. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  3109. } else {
  3110. hours = parseInt(intervalVal, 10) || 24;
  3111. }
  3112. try {
  3113. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  3114. method: 'POST',
  3115. headers: { 'Content-Type': 'application/json' },
  3116. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  3117. });
  3118. if (res.ok) {
  3119. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  3120. closeGeoIntervalModal();
  3121. loadGeoIP();
  3122. } else {
  3123. const err = await res.json();
  3124. showToast('Error', err.message || 'Failed to save schedule', 'error');
  3125. }
  3126. } catch (err) {
  3127. showToast('Error', err.message, 'error');
  3128. }
  3129. }
  3130. async function viewGeoSubnets(code, name) {
  3131. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  3132. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  3133. const listEl = document.getElementById('geo-subnets-list');
  3134. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  3135. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  3136. try {
  3137. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  3138. if (res.ok) {
  3139. const data = await res.json();
  3140. const subnets = data.subnets || [];
  3141. if (subnets.length === 0) {
  3142. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  3143. } else {
  3144. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  3145. }
  3146. } else {
  3147. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  3148. }
  3149. } catch (err) {
  3150. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  3151. }
  3152. }
  3153. function closeGeoSubnetsModal() {
  3154. document.getElementById('geo-subnets-modal').classList.add('hidden');
  3155. }
  3156. // ----------------- Active Connections Tracking -----------------
  3157. async function loadConnections() {
  3158. try {
  3159. const res = await fetch(`${API_BASE}/firewall/connections`);
  3160. const data = await res.json();
  3161. state.connections = Array.isArray(data) ? data : [];
  3162. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  3163. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  3164. renderConnections();
  3165. } catch (err) {
  3166. console.error('Failed to load connections:', err);
  3167. }
  3168. }
  3169. function renderConnections() {
  3170. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  3171. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  3172. const tbody = document.getElementById('conns-table-body');
  3173. const empty = document.getElementById('conns-empty');
  3174. if (!tbody) return;
  3175. tbody.innerHTML = '';
  3176. const conns = (state.connections || []).filter(c => {
  3177. if (protoFilter && c.protocol !== protoFilter) return false;
  3178. if (search) {
  3179. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  3180. if (!line.includes(search)) return false;
  3181. }
  3182. return true;
  3183. });
  3184. if (conns.length === 0) {
  3185. empty?.classList.remove('hidden');
  3186. return;
  3187. }
  3188. empty?.classList.add('hidden');
  3189. conns.slice(0, 150).forEach(c => {
  3190. const tr = document.createElement('tr');
  3191. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  3192. let stateColor = 'text-slate-400';
  3193. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  3194. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  3195. tr.innerHTML = `
  3196. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  3197. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  3198. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  3199. <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>
  3200. <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>
  3201. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  3202. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  3203. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  3204. <td class="py-2.5 px-3 text-right font-sans">
  3205. <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>
  3206. </td>
  3207. `;
  3208. tbody.appendChild(tr);
  3209. });
  3210. }
  3211. async function killConnection(protocol, src, sport, dst, dport) {
  3212. try {
  3213. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  3214. method: 'POST',
  3215. headers: { 'Content-Type': 'application/json' },
  3216. body: JSON.stringify({ protocol, src, sport, dst, dport })
  3217. });
  3218. if (res.ok) {
  3219. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  3220. loadConnections();
  3221. }
  3222. } catch (err) {
  3223. showToast('Error', err.message, 'error');
  3224. }
  3225. }
  3226. async function resetFirewallCounters() {
  3227. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  3228. try {
  3229. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3230. if (res.ok) {
  3231. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  3232. loadFirewall(false);
  3233. }
  3234. } catch (err) {
  3235. showToast('Error', err.message, 'error');
  3236. }
  3237. }
  3238. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  3239. function switchRoutesSubTab(tab) {
  3240. state.routesSubTab = tab;
  3241. const tabs = ['routes', 'rules', 'tables'];
  3242. tabs.forEach(t => {
  3243. const panel = document.getElementById(`routes-subtab-${t}`);
  3244. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  3245. if (panel) {
  3246. if (t === tab) panel.classList.remove('hidden');
  3247. else panel.classList.add('hidden');
  3248. }
  3249. if (btn) {
  3250. if (t === tab) {
  3251. 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';
  3252. } else {
  3253. 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';
  3254. }
  3255. }
  3256. });
  3257. }
  3258. async function loadRoutes() {
  3259. try {
  3260. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  3261. fetch(`${API_BASE}/routes`),
  3262. fetch(`${API_BASE}/routing/rules`),
  3263. fetch(`${API_BASE}/routing/tables`)
  3264. ]);
  3265. if (routesRes.ok) state.routes = await routesRes.json();
  3266. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  3267. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  3268. const bRoutes = document.getElementById('routes-badge-routes');
  3269. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  3270. const bRules = document.getElementById('routes-badge-rules');
  3271. if (bRules) bRules.innerText = (state.policyRules || []).length;
  3272. const bTables = document.getElementById('routes-badge-tables');
  3273. if (bTables) bTables.innerText = (state.routingTables || []).length;
  3274. const bRoutesCount = document.getElementById('badge-routes-count');
  3275. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  3276. renderRoutesList();
  3277. renderPolicyRules();
  3278. renderRoutingTables();
  3279. } catch (err) {
  3280. console.error('Failed to load routing:', err);
  3281. }
  3282. }
  3283. function renderRoutesList() {
  3284. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  3285. const tbody = document.getElementById('routes-table-body');
  3286. const empty = document.getElementById('routes-empty');
  3287. if (!tbody) return;
  3288. tbody.innerHTML = '';
  3289. // Update table filter select
  3290. const sel = document.getElementById('routes-filter-table');
  3291. if (sel) {
  3292. const cur = sel.value;
  3293. sel.innerHTML = '<option value="">All Tables</option>';
  3294. (state.routingTables || []).forEach(t => {
  3295. const opt = document.createElement('option');
  3296. opt.value = t.name;
  3297. opt.innerText = t.name;
  3298. if (t.name === cur) opt.selected = true;
  3299. sel.appendChild(opt);
  3300. });
  3301. }
  3302. const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
  3303. document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
  3304. if (routes.length === 0) {
  3305. empty?.classList.remove('hidden');
  3306. return;
  3307. }
  3308. empty?.classList.add('hidden');
  3309. routes.forEach(r => {
  3310. const tr = document.createElement('tr');
  3311. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  3312. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  3313. // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
  3314. let flags = '';
  3315. if (r.dynamic) flags += 'D';
  3316. if (r.active) flags += 'A';
  3317. if (r.connect) flags += 'C';
  3318. if (r.static) flags += 'S';
  3319. if (r.disabled) flags += 'X';
  3320. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  3321. tr.innerHTML = `
  3322. <td class="py-2.5 px-3 text-center">
  3323. <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'}">
  3324. ${flags || '-'}
  3325. </span>
  3326. </td>
  3327. <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
  3328. <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>
  3329. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  3330. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  3331. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  3332. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  3333. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  3334. ${r.static ? `
  3335. <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>
  3336. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  3337. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3338. ` : `
  3339. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  3340. `}
  3341. </td>
  3342. `;
  3343. tbody.appendChild(tr);
  3344. });
  3345. }
  3346. function openAddRouteModal() {
  3347. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  3348. document.getElementById('route-modal-id').value = '';
  3349. document.getElementById('route-modal-old-dst').value = '';
  3350. document.getElementById('route-modal-old-gw').value = '';
  3351. document.getElementById('route-modal-old-distance').value = '';
  3352. document.getElementById('route-modal-old-table').value = '';
  3353. document.getElementById('route-modal-old-iface').value = '';
  3354. const dstInput = document.getElementById('route-modal-dst');
  3355. const gwInput = document.getElementById('route-modal-gw');
  3356. const distInput = document.getElementById('route-modal-distance');
  3357. const ifaceSelect = document.getElementById('route-modal-iface');
  3358. const tableSelect = document.getElementById('route-modal-table');
  3359. const commentInput = document.getElementById('route-modal-comment');
  3360. const disCheck = document.getElementById('route-modal-disabled');
  3361. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  3362. dstInput.disabled = false;
  3363. dstInput.value = '0.0.0.0/0';
  3364. gwInput.disabled = false;
  3365. gwInput.value = '';
  3366. distInput.disabled = false;
  3367. distInput.value = '1';
  3368. ifaceSelect.disabled = false;
  3369. tableSelect.disabled = false;
  3370. commentInput.disabled = false;
  3371. commentInput.value = '';
  3372. disCheck.disabled = false;
  3373. disCheck.checked = false;
  3374. if (saveBtn) saveBtn.classList.remove('hidden');
  3375. populateInterfaceSelect('route-modal-iface');
  3376. // Populate tables
  3377. tableSelect.innerHTML = '';
  3378. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  3379. const opt = document.createElement('option');
  3380. opt.value = t.name;
  3381. opt.innerText = t.name;
  3382. if (t.name === 'main') opt.selected = true;
  3383. tableSelect.appendChild(opt);
  3384. });
  3385. document.getElementById('route-modal').classList.remove('hidden');
  3386. }
  3387. function openEditRouteModal(id) {
  3388. const r = (state.routes || []).find(route => route.id === id);
  3389. if (!r) return;
  3390. const isStatic = !!r.static;
  3391. document.getElementById('route-modal-title').innerText = isStatic
  3392. ? `Edit Route: ${r.dst_address}`
  3393. : `Route Properties (Read Only): ${r.dst_address}`;
  3394. document.getElementById('route-modal-id').value = r.id;
  3395. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  3396. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  3397. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  3398. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  3399. document.getElementById('route-modal-old-iface').value = r.interface || '';
  3400. const dstInput = document.getElementById('route-modal-dst');
  3401. const gwInput = document.getElementById('route-modal-gw');
  3402. const distInput = document.getElementById('route-modal-distance');
  3403. const ifaceSelect = document.getElementById('route-modal-iface');
  3404. const tableSelect = document.getElementById('route-modal-table');
  3405. const commentInput = document.getElementById('route-modal-comment');
  3406. const disCheck = document.getElementById('route-modal-disabled');
  3407. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  3408. dstInput.value = r.dst_address;
  3409. gwInput.value = r.gateway || '';
  3410. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  3411. commentInput.value = r.comment || '';
  3412. disCheck.checked = !!r.disabled;
  3413. dstInput.disabled = !isStatic;
  3414. gwInput.disabled = !isStatic;
  3415. distInput.disabled = !isStatic;
  3416. ifaceSelect.disabled = !isStatic;
  3417. tableSelect.disabled = !isStatic;
  3418. commentInput.disabled = !isStatic;
  3419. disCheck.disabled = !isStatic;
  3420. if (saveBtn) {
  3421. if (isStatic) {
  3422. saveBtn.classList.remove('hidden');
  3423. } else {
  3424. saveBtn.classList.add('hidden');
  3425. }
  3426. }
  3427. populateInterfaceSelect('route-modal-iface', r.interface);
  3428. tableSelect.innerHTML = '';
  3429. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  3430. const opt = document.createElement('option');
  3431. opt.value = t.name;
  3432. opt.innerText = t.name;
  3433. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  3434. tableSelect.appendChild(opt);
  3435. });
  3436. document.getElementById('route-modal').classList.remove('hidden');
  3437. }
  3438. function closeRouteModal() {
  3439. document.getElementById('route-modal').classList.add('hidden');
  3440. }
  3441. async function submitSaveRoute(e) {
  3442. e.preventDefault();
  3443. const id = document.getElementById('route-modal-id').value;
  3444. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  3445. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  3446. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  3447. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  3448. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  3449. const dst = document.getElementById('route-modal-dst').value.trim();
  3450. const gw = document.getElementById('route-modal-gw').value.trim();
  3451. const table = document.getElementById('route-modal-table').value;
  3452. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  3453. const iface = document.getElementById('route-modal-iface').value;
  3454. const comment = document.getElementById('route-modal-comment').value.trim();
  3455. const disabled = document.getElementById('route-modal-disabled').checked;
  3456. if (!dst) {
  3457. showToast('Error', 'Destination address is required', 'error');
  3458. return;
  3459. }
  3460. if (!gw && !iface) {
  3461. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  3462. return;
  3463. }
  3464. const payload = {
  3465. id,
  3466. old_dst_address: oldDst,
  3467. old_gateway: oldGw,
  3468. old_routing_table: oldTable,
  3469. old_interface: oldIface,
  3470. dst_address: dst,
  3471. gateway: gw || iface,
  3472. routing_table: table,
  3473. distance,
  3474. interface: iface,
  3475. comment,
  3476. disabled
  3477. };
  3478. if (oldDistStr !== undefined && oldDistStr !== '') {
  3479. payload.old_distance = parseInt(oldDistStr, 10);
  3480. }
  3481. try {
  3482. const res = await fetch(`${API_BASE}/routes`, {
  3483. method: 'POST',
  3484. headers: { 'Content-Type': 'application/json' },
  3485. body: JSON.stringify(payload)
  3486. });
  3487. if (res.ok) {
  3488. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  3489. closeRouteModal();
  3490. loadRoutes();
  3491. } else {
  3492. const err = await res.json();
  3493. showToast('Error', err.message || 'Failed to save route', 'error');
  3494. }
  3495. } catch (err) {
  3496. showToast('Error', err.message, 'error');
  3497. }
  3498. }
  3499. async function toggleRouteState(id, disabled) {
  3500. try {
  3501. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  3502. method: 'POST',
  3503. headers: { 'Content-Type': 'application/json' },
  3504. body: JSON.stringify({ disabled })
  3505. });
  3506. if (res.ok) loadRoutes();
  3507. } catch (err) {
  3508. showToast('Error', err.message, 'error');
  3509. }
  3510. }
  3511. async function deleteRoute(id) {
  3512. if (!confirm('Are you sure you want to delete this route?')) return;
  3513. try {
  3514. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3515. if (res.ok) {
  3516. showToast('Deleted', 'Route removed', 'success');
  3517. loadRoutes();
  3518. }
  3519. } catch (err) {
  3520. showToast('Error', err.message, 'error');
  3521. }
  3522. }
  3523. // ----------------- Policy Rules (/ip route rule) -----------------
  3524. function renderPolicyRules() {
  3525. const tbody = document.getElementById('rules-table-body');
  3526. const empty = document.getElementById('rules-empty');
  3527. if (!tbody) return;
  3528. tbody.innerHTML = '';
  3529. const rules = state.policyRules || [];
  3530. document.getElementById('rules-count-badge').innerText = `${rules.length} Rules`;
  3531. if (rules.length === 0) {
  3532. empty?.classList.remove('hidden');
  3533. return;
  3534. }
  3535. empty?.classList.add('hidden');
  3536. rules.forEach(pr => {
  3537. const tr = document.createElement('tr');
  3538. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  3539. tr.innerHTML = `
  3540. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  3541. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  3542. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  3543. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  3544. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  3545. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  3546. <td class="py-2.5 px-3 text-right font-sans">
  3547. ${pr.priority < 32766 && pr.priority > 0 ? `
  3548. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3549. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  3550. </td>
  3551. `;
  3552. tbody.appendChild(tr);
  3553. });
  3554. }
  3555. function openAddPolicyRuleModal() {
  3556. document.getElementById('prule-modal-pref').value = (state.policyRules || []).length * 10 + 1000;
  3557. document.getElementById('prule-modal-mark').value = '';
  3558. document.getElementById('prule-modal-src').value = '';
  3559. document.getElementById('prule-modal-dst').value = '';
  3560. const sel = document.getElementById('prule-modal-table');
  3561. sel.innerHTML = '';
  3562. (state.routingTables || []).forEach(t => {
  3563. const opt = document.createElement('option');
  3564. opt.value = t.name;
  3565. opt.innerText = t.name;
  3566. sel.appendChild(opt);
  3567. });
  3568. document.getElementById('prule-modal').classList.remove('hidden');
  3569. }
  3570. function closePolicyRuleModal() {
  3571. document.getElementById('prule-modal').classList.add('hidden');
  3572. }
  3573. async function submitSavePolicyRule(e) {
  3574. e.preventDefault();
  3575. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  3576. const mark = document.getElementById('prule-modal-mark').value.trim();
  3577. const src = document.getElementById('prule-modal-src').value.trim();
  3578. const dst = document.getElementById('prule-modal-dst').value.trim();
  3579. const table = document.getElementById('prule-modal-table').value;
  3580. const action = document.getElementById('prule-modal-action').value;
  3581. try {
  3582. const res = await fetch(`${API_BASE}/routing/rules`, {
  3583. method: 'POST',
  3584. headers: { 'Content-Type': 'application/json' },
  3585. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  3586. });
  3587. if (res.ok) {
  3588. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  3589. closePolicyRuleModal();
  3590. loadRoutes();
  3591. } else {
  3592. const err = await res.json();
  3593. showToast('Error', err.message, 'error');
  3594. }
  3595. } catch (err) {
  3596. showToast('Error', err.message, 'error');
  3597. }
  3598. }
  3599. async function deletePolicyRule(id) {
  3600. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  3601. try {
  3602. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3603. if (res.ok) {
  3604. showToast('Rule Removed', 'Policy rule deleted', 'success');
  3605. loadRoutes();
  3606. }
  3607. } catch (err) {
  3608. showToast('Error', err.message, 'error');
  3609. }
  3610. }
  3611. // ----------------- Routing Tables -----------------
  3612. function renderRoutingTables() {
  3613. const tbody = document.getElementById('tables-table-body');
  3614. if (!tbody) return;
  3615. tbody.innerHTML = '';
  3616. (state.routingTables || []).forEach(t => {
  3617. const tr = document.createElement('tr');
  3618. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  3619. tr.innerHTML = `
  3620. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  3621. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  3622. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  3623. `;
  3624. tbody.appendChild(tr);
  3625. });
  3626. }
  3627. function openAddTableModal() {
  3628. document.getElementById('table-modal-name').value = '';
  3629. document.getElementById('table-modal-id').value = '';
  3630. document.getElementById('table-modal-comment').value = '';
  3631. document.getElementById('table-modal').classList.remove('hidden');
  3632. }
  3633. function closeTableModal() {
  3634. document.getElementById('table-modal').classList.add('hidden');
  3635. }
  3636. async function submitSaveTable(e) {
  3637. e.preventDefault();
  3638. const name = document.getElementById('table-modal-name').value.trim();
  3639. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  3640. const comment = document.getElementById('table-modal-comment').value.trim();
  3641. try {
  3642. const res = await fetch(`${API_BASE}/routing/tables`, {
  3643. method: 'POST',
  3644. headers: { 'Content-Type': 'application/json' },
  3645. body: JSON.stringify({ name, table_id: id, comment })
  3646. });
  3647. if (res.ok) {
  3648. showToast('Table Created', `Routing table ${name} registered`, 'success');
  3649. closeTableModal();
  3650. loadRoutes();
  3651. } else {
  3652. const err = await res.json();
  3653. showToast('Error', err.message, 'error');
  3654. }
  3655. } catch (err) {
  3656. showToast('Error', err.message, 'error');
  3657. }
  3658. }
  3659. async function loadDebianConfig() {
  3660. const view = document.getElementById('debian-config-view');
  3661. view.innerText = 'Generating live configuration...';
  3662. try {
  3663. const res = await fetch(`${API_BASE}/debian/config`);
  3664. const data = await res.json();
  3665. view.innerText = data.content || '# Empty config';
  3666. } catch (err) {
  3667. view.innerText = 'Failed to generate Debian network config.';
  3668. }
  3669. }
  3670. async function saveDebianConfig() {
  3671. try {
  3672. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  3673. const data = await res.json();
  3674. if (res.ok) {
  3675. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  3676. loadDebianConfig();
  3677. }
  3678. } catch (err) {
  3679. showToast('Error', err.message, 'error');
  3680. }
  3681. }
  3682. function showToast(title, message, type = 'info') {
  3683. const container = document.getElementById('toast-container');
  3684. const toast = document.createElement('div');
  3685. const borderColors = {
  3686. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  3687. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  3688. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  3689. };
  3690. 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}`;
  3691. toast.innerHTML = `
  3692. <div class="flex-1">
  3693. <div class="font-bold text-xs text-white">${title}</div>
  3694. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  3695. </div>
  3696. `;
  3697. container.appendChild(toast);
  3698. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  3699. setTimeout(() => {
  3700. toast.classList.add('opacity-0', 'translate-y-2');
  3701. setTimeout(() => toast.remove(), 300);
  3702. }, 4000);
  3703. }
  3704. function formatTraffic(bytesPerSec) {
  3705. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  3706. const kb = bytesPerSec / 1024;
  3707. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  3708. const mb = kb / 1024;
  3709. return `${mb.toFixed(2)} MB/s`;
  3710. }
  3711. function toggleSidebar() {
  3712. const sb = document.getElementById('sidebar');
  3713. sb.classList.toggle('-translate-x-full');
  3714. }
  3715. // ======================== EoIP (Ethernet over IP) ========================
  3716. async function loadEoIP(populate = true) {
  3717. try {
  3718. const res = await fetch(`${API_BASE}/vpn/eoip`);
  3719. const data = await res.json();
  3720. state.eoipTunnels = Array.isArray(data) ? data : [];
  3721. const badge = document.getElementById('eoip-count-badge');
  3722. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  3723. const sideBadge = document.getElementById('badge-eoip-count');
  3724. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  3725. renderEoIPTunnels();
  3726. } catch (err) {
  3727. console.error('Failed to load EoIP:', err);
  3728. }
  3729. }
  3730. function renderEoIPTunnels() {
  3731. const tbody = document.getElementById('eoip-table-body');
  3732. const empty = document.getElementById('eoip-empty');
  3733. if (!tbody) return;
  3734. tbody.innerHTML = '';
  3735. const tunnels = state.eoipTunnels || [];
  3736. if (tunnels.length === 0) {
  3737. empty?.classList.remove('hidden');
  3738. return;
  3739. }
  3740. empty?.classList.add('hidden');
  3741. tunnels.forEach(t => {
  3742. const tr = document.createElement('tr');
  3743. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  3744. tr.innerHTML = `
  3745. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  3746. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  3747. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  3748. <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>
  3749. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  3750. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  3751. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  3752. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  3753. <td class="py-2.5 px-3 font-mono text-[11px]">
  3754. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  3755. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  3756. </td>
  3757. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  3758. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3759. <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>
  3760. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3761. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  3762. </td>
  3763. `;
  3764. tbody.appendChild(tr);
  3765. });
  3766. }
  3767. function openAddEoIPModal() {
  3768. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  3769. document.getElementById('eoip-modal-id').value = '';
  3770. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  3771. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  3772. document.getElementById('eoip-modal-remote').value = '';
  3773. document.getElementById('eoip-modal-ip').value = '';
  3774. document.getElementById('eoip-modal-local').value = '';
  3775. document.getElementById('eoip-modal-mac').value = '';
  3776. document.getElementById('eoip-modal-mtu').value = '1500';
  3777. document.getElementById('eoip-modal-comment').value = '';
  3778. document.getElementById('eoip-modal-clampmss').checked = true;
  3779. document.getElementById('eoip-modal-disabled').checked = false;
  3780. document.getElementById('eoip-modal').classList.remove('hidden');
  3781. }
  3782. function openEditEoIPModal(id) {
  3783. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  3784. if (!t) return;
  3785. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  3786. document.getElementById('eoip-modal-id').value = t.id;
  3787. document.getElementById('eoip-modal-name').value = t.name;
  3788. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  3789. document.getElementById('eoip-modal-remote').value = t.remote_address;
  3790. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  3791. document.getElementById('eoip-modal-local').value = t.local_address || '';
  3792. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  3793. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  3794. document.getElementById('eoip-modal-comment').value = t.comment || '';
  3795. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  3796. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  3797. document.getElementById('eoip-modal').classList.remove('hidden');
  3798. }
  3799. function closeEoIPModal() {
  3800. document.getElementById('eoip-modal').classList.add('hidden');
  3801. }
  3802. async function submitSaveEoIP(e) {
  3803. e.preventDefault();
  3804. const id = document.getElementById('eoip-modal-id').value;
  3805. const name = document.getElementById('eoip-modal-name').value.trim();
  3806. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  3807. const remote = document.getElementById('eoip-modal-remote').value.trim();
  3808. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  3809. const local = document.getElementById('eoip-modal-local').value.trim();
  3810. const mac = document.getElementById('eoip-modal-mac').value.trim();
  3811. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  3812. const comment = document.getElementById('eoip-modal-comment').value.trim();
  3813. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  3814. const disabled = document.getElementById('eoip-modal-disabled').checked;
  3815. try {
  3816. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  3817. method: 'POST',
  3818. headers: { 'Content-Type': 'application/json' },
  3819. body: JSON.stringify({
  3820. id,
  3821. name,
  3822. tunnel_id: tunnelId,
  3823. remote_address: remote,
  3824. ip_address: ipAddress,
  3825. local_address: local,
  3826. mac_address: mac,
  3827. mtu,
  3828. clamp_mss: clampMss,
  3829. comment,
  3830. disabled
  3831. })
  3832. });
  3833. if (res.ok) {
  3834. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  3835. closeEoIPModal();
  3836. loadEoIP(false);
  3837. fetchData(false);
  3838. } else {
  3839. const err = await res.json();
  3840. showToast('Error', err.message, 'error');
  3841. }
  3842. } catch (err) {
  3843. showToast('Error', err.message, 'error');
  3844. }
  3845. }
  3846. async function toggleEoIPState(id, disabled) {
  3847. try {
  3848. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  3849. method: 'POST',
  3850. headers: { 'Content-Type': 'application/json' },
  3851. body: JSON.stringify({ disabled })
  3852. });
  3853. if (res.ok) {
  3854. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  3855. loadEoIP(false);
  3856. fetchData(false);
  3857. }
  3858. } catch (err) {
  3859. showToast('Error', err.message, 'error');
  3860. }
  3861. }
  3862. async function deleteEoIP(id) {
  3863. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  3864. try {
  3865. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3866. if (res.ok) {
  3867. showToast('Deleted', 'EoIP tunnel removed', 'success');
  3868. loadEoIP(false);
  3869. fetchData(false);
  3870. }
  3871. } catch (err) {
  3872. showToast('Error', err.message, 'error');
  3873. }
  3874. }
  3875. // ======================== PPP Central Hub & Servers ========================
  3876. function switchPPPSubTab(tab) {
  3877. state.pppSubTab = tab;
  3878. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  3879. tabs.forEach(t => {
  3880. const panel = document.getElementById(`ppp-subtab-${t}`);
  3881. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  3882. if (panel) {
  3883. if (t === tab) panel.classList.remove('hidden');
  3884. else panel.classList.add('hidden');
  3885. }
  3886. if (btn) {
  3887. if (t === tab) {
  3888. 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';
  3889. } else {
  3890. 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';
  3891. }
  3892. }
  3893. });
  3894. const addBtn = document.getElementById('ppp-primary-add-btn');
  3895. if (addBtn) {
  3896. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  3897. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  3898. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  3899. else addBtn.innerHTML = '<span>Save Config</span>';
  3900. }
  3901. if (tab === 'active') loadPPPSessions();
  3902. }
  3903. function openCurrentPPPModal() {
  3904. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  3905. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  3906. else if (state.pppSubTab === 'active') loadPPPSessions();
  3907. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  3908. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  3909. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  3910. }
  3911. async function loadPPP(populateDropdowns = true) {
  3912. await Promise.all([
  3913. loadPPPSecrets(),
  3914. loadPPPProfiles(),
  3915. loadPPPServers(),
  3916. loadPPPSessions()
  3917. ]);
  3918. }
  3919. async function loadPPPSecrets() {
  3920. try {
  3921. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  3922. const data = await res.json();
  3923. state.pppSecrets = Array.isArray(data) ? data : [];
  3924. const b = document.getElementById('ppp-badge-secrets');
  3925. if (b) b.innerText = state.pppSecrets.length;
  3926. const b2 = document.getElementById('secrets-count-badge');
  3927. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  3928. renderPPPSecrets();
  3929. } catch (err) {
  3930. console.error('Failed to load PPP secrets:', err);
  3931. }
  3932. }
  3933. function renderPPPSecrets() {
  3934. const tbody = document.getElementById('secrets-table-body');
  3935. const empty = document.getElementById('secrets-empty');
  3936. if (!tbody) return;
  3937. tbody.innerHTML = '';
  3938. const secrets = state.pppSecrets || [];
  3939. if (secrets.length === 0) {
  3940. empty?.classList.remove('hidden');
  3941. return;
  3942. }
  3943. empty?.classList.add('hidden');
  3944. secrets.forEach(s => {
  3945. const tr = document.createElement('tr');
  3946. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  3947. tr.innerHTML = `
  3948. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  3949. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  3950. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  3951. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  3952. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  3953. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  3954. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  3955. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3956. <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>
  3957. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3958. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  3959. </td>
  3960. `;
  3961. tbody.appendChild(tr);
  3962. });
  3963. }
  3964. async function loadPPPProfiles() {
  3965. try {
  3966. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  3967. const data = await res.json();
  3968. state.pppProfiles = Array.isArray(data) ? data : [];
  3969. const b = document.getElementById('ppp-badge-profiles');
  3970. if (b) b.innerText = state.pppProfiles.length;
  3971. const b2 = document.getElementById('profiles-count-badge');
  3972. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  3973. // Populate profile selects across modals
  3974. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  3975. selects.forEach(sid => {
  3976. const el = document.getElementById(sid);
  3977. if (!el) return;
  3978. const cur = el.value;
  3979. el.innerHTML = '';
  3980. state.pppProfiles.forEach(p => {
  3981. const opt = document.createElement('option');
  3982. opt.value = p.name;
  3983. opt.innerText = `${p.name} (${p.remote_address})`;
  3984. if (p.name === cur) opt.selected = true;
  3985. el.appendChild(opt);
  3986. });
  3987. });
  3988. renderPPPProfiles();
  3989. } catch (err) {
  3990. console.error('Failed to load PPP profiles:', err);
  3991. }
  3992. }
  3993. function renderPPPProfiles() {
  3994. const tbody = document.getElementById('profiles-table-body');
  3995. if (!tbody) return;
  3996. tbody.innerHTML = '';
  3997. (state.pppProfiles || []).forEach(p => {
  3998. const isDefault = p.name.startsWith('default');
  3999. const tr = document.createElement('tr');
  4000. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  4001. tr.innerHTML = `
  4002. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  4003. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  4004. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  4005. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  4006. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  4007. <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>
  4008. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  4009. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  4010. ${!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>`}
  4011. </td>
  4012. `;
  4013. tbody.appendChild(tr);
  4014. });
  4015. }
  4016. async function loadPPPServers() {
  4017. try {
  4018. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  4019. fetch(`${API_BASE}/vpn/servers/pppoe`),
  4020. fetch(`${API_BASE}/vpn/servers/pptp`),
  4021. fetch(`${API_BASE}/vpn/servers/l2tp`),
  4022. fetch(`${API_BASE}/vpn/servers/ipsec`)
  4023. ]);
  4024. if (pppoeRes.ok) {
  4025. state.pppoeServer = await pppoeRes.json();
  4026. const s = state.pppoeServer;
  4027. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  4028. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  4029. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  4030. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  4031. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  4032. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  4033. const pill = document.getElementById('pppoe-server-status-pill');
  4034. if (pill) {
  4035. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  4036. 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';
  4037. }
  4038. setDotBadge('ppp-badge-pppoe-state', s.running);
  4039. }
  4040. if (pptpRes.ok) {
  4041. state.pptpServer = await pptpRes.json();
  4042. const s = state.pptpServer;
  4043. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  4044. document.getElementById('pptp-server-port').value = s.port || 1723;
  4045. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  4046. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  4047. const pill = document.getElementById('pptp-server-status-pill');
  4048. if (pill) {
  4049. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  4050. 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';
  4051. }
  4052. setDotBadge('ppp-badge-pptp-state', s.running);
  4053. }
  4054. if (l2tpRes.ok) {
  4055. state.l2tpServer = await l2tpRes.json();
  4056. const s = state.l2tpServer;
  4057. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  4058. document.getElementById('l2tp-server-port').value = s.port || 1701;
  4059. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  4060. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  4061. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  4062. const pill = document.getElementById('l2tp-server-status-pill');
  4063. if (pill) {
  4064. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  4065. 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';
  4066. }
  4067. setDotBadge('ppp-badge-l2tp-state', s.running);
  4068. }
  4069. if (ipsecRes.ok) {
  4070. state.ipsecServer = await ipsecRes.json();
  4071. const s = state.ipsecServer;
  4072. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  4073. if (modalEn) modalEn.checked = !!s.enabled;
  4074. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  4075. if (modalPsk) modalPsk.value = s.preshared_key || '';
  4076. const modalPool = document.getElementById('modal-ipsec-server-pool');
  4077. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  4078. const modalDns = document.getElementById('modal-ipsec-server-dns');
  4079. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  4080. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  4081. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  4082. const pill = document.getElementById('modal-ipsec-server-status');
  4083. if (pill) {
  4084. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  4085. 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';
  4086. }
  4087. }
  4088. } catch (err) {
  4089. console.error('Failed to load VPN servers:', err);
  4090. }
  4091. }
  4092. async function loadPPPSessions() {
  4093. try {
  4094. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  4095. const data = await res.json();
  4096. state.pppActiveSessions = Array.isArray(data) ? data : [];
  4097. const b = document.getElementById('ppp-badge-active');
  4098. if (b) b.innerText = state.pppActiveSessions.length;
  4099. const sideB = document.getElementById('badge-ppp-sessions');
  4100. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  4101. renderPPPSessions();
  4102. } catch (err) {
  4103. console.error('Failed to load active PPP sessions:', err);
  4104. }
  4105. }
  4106. function renderPPPSessions() {
  4107. const tbody = document.getElementById('active-ppp-table-body');
  4108. const empty = document.getElementById('active-ppp-empty');
  4109. if (!tbody) return;
  4110. tbody.innerHTML = '';
  4111. const list = state.pppActiveSessions || [];
  4112. if (list.length === 0) {
  4113. empty?.classList.remove('hidden');
  4114. return;
  4115. }
  4116. empty?.classList.add('hidden');
  4117. list.forEach(s => {
  4118. const tr = document.createElement('tr');
  4119. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  4120. tr.innerHTML = `
  4121. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  4122. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  4123. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  4124. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  4125. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  4126. <td class="py-2.5 px-3 text-[11px]">
  4127. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  4128. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  4129. </td>
  4130. <td class="py-2.5 px-3 text-right font-sans">
  4131. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  4132. </td>
  4133. `;
  4134. tbody.appendChild(tr);
  4135. });
  4136. }
  4137. async function disconnectPPPSession(iface) {
  4138. if (!confirm(`Disconnect session ${iface}?`)) return;
  4139. try {
  4140. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  4141. if (res.ok) {
  4142. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  4143. loadPPPSessions();
  4144. }
  4145. } catch (err) {
  4146. showToast('Error', err.message, 'error');
  4147. }
  4148. }
  4149. // PPP Secret Modal handlers
  4150. function openAddPPPSecretModal() {
  4151. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  4152. document.getElementById('secret-modal-id').value = '';
  4153. document.getElementById('secret-modal-name').value = '';
  4154. document.getElementById('secret-modal-password').value = '';
  4155. document.getElementById('secret-modal-service').value = 'any';
  4156. document.getElementById('secret-modal-profile').value = 'default';
  4157. document.getElementById('secret-modal-local').value = '';
  4158. document.getElementById('secret-modal-remote').value = '';
  4159. document.getElementById('secret-modal-comment').value = '';
  4160. document.getElementById('secret-modal-disabled').checked = false;
  4161. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  4162. }
  4163. function openEditPPPSecretModal(id) {
  4164. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  4165. if (!s) return;
  4166. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  4167. document.getElementById('secret-modal-id').value = s.id;
  4168. document.getElementById('secret-modal-name').value = s.name;
  4169. document.getElementById('secret-modal-password').value = s.password;
  4170. document.getElementById('secret-modal-service').value = s.service || 'any';
  4171. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  4172. document.getElementById('secret-modal-local').value = s.local_address || '';
  4173. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  4174. document.getElementById('secret-modal-comment').value = s.comment || '';
  4175. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  4176. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  4177. }
  4178. function closePPPSecretModal() {
  4179. document.getElementById('ppp-secret-modal').classList.add('hidden');
  4180. }
  4181. async function submitSavePPPSecret(e) {
  4182. e.preventDefault();
  4183. const id = document.getElementById('secret-modal-id').value;
  4184. const name = document.getElementById('secret-modal-name').value.trim();
  4185. const password = document.getElementById('secret-modal-password').value.trim();
  4186. const service = document.getElementById('secret-modal-service').value;
  4187. const profile = document.getElementById('secret-modal-profile').value;
  4188. const local = document.getElementById('secret-modal-local').value.trim();
  4189. const remote = document.getElementById('secret-modal-remote').value.trim();
  4190. const comment = document.getElementById('secret-modal-comment').value.trim();
  4191. const disabled = document.getElementById('secret-modal-disabled').checked;
  4192. try {
  4193. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  4194. method: 'POST',
  4195. headers: { 'Content-Type': 'application/json' },
  4196. body: JSON.stringify({
  4197. id,
  4198. name,
  4199. password,
  4200. service,
  4201. profile,
  4202. local_address: local,
  4203. remote_address: remote,
  4204. comment,
  4205. disabled
  4206. })
  4207. });
  4208. if (res.ok) {
  4209. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  4210. closePPPSecretModal();
  4211. loadPPPSecrets();
  4212. } else {
  4213. const err = await res.json();
  4214. showToast('Error', err.message, 'error');
  4215. }
  4216. } catch (err) {
  4217. showToast('Error', err.message, 'error');
  4218. }
  4219. }
  4220. async function togglePPPSecretState(id, disabled) {
  4221. try {
  4222. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  4223. method: 'POST',
  4224. headers: { 'Content-Type': 'application/json' },
  4225. body: JSON.stringify({ disabled })
  4226. });
  4227. if (res.ok) {
  4228. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  4229. loadPPPSecrets();
  4230. }
  4231. } catch (err) {
  4232. showToast('Error', err.message, 'error');
  4233. }
  4234. }
  4235. async function deletePPPSecret(id) {
  4236. if (!confirm('Are you sure you want to delete this secret account?')) return;
  4237. try {
  4238. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4239. if (res.ok) {
  4240. showToast('Deleted', 'Secret account removed', 'success');
  4241. loadPPPSecrets();
  4242. }
  4243. } catch (err) {
  4244. showToast('Error', err.message, 'error');
  4245. }
  4246. }
  4247. // PPP Profile Modal handlers
  4248. function openAddPPPProfileModal() {
  4249. document.getElementById('profile-modal-name').value = '';
  4250. document.getElementById('profile-modal-local').value = '10.10.10.1';
  4251. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  4252. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  4253. document.getElementById('profile-modal-encryption').value = 'required';
  4254. document.getElementById('profile-modal-onlyone').checked = true;
  4255. document.getElementById('profile-modal-comment').value = '';
  4256. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  4257. }
  4258. function closePPPProfileModal() {
  4259. document.getElementById('ppp-profile-modal').classList.add('hidden');
  4260. }
  4261. async function submitSavePPPProfile(e) {
  4262. e.preventDefault();
  4263. const name = document.getElementById('profile-modal-name').value.trim();
  4264. const local = document.getElementById('profile-modal-local').value.trim();
  4265. const remote = document.getElementById('profile-modal-remote').value.trim();
  4266. const dns = document.getElementById('profile-modal-dns').value.trim();
  4267. const enc = document.getElementById('profile-modal-encryption').value;
  4268. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  4269. const comment = document.getElementById('profile-modal-comment').value.trim();
  4270. try {
  4271. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  4272. method: 'POST',
  4273. headers: { 'Content-Type': 'application/json' },
  4274. body: JSON.stringify({
  4275. id: name,
  4276. name,
  4277. local_address: local,
  4278. remote_address: remote,
  4279. dns_servers: dns,
  4280. use_encryption: enc,
  4281. only_one: onlyone,
  4282. comment
  4283. })
  4284. });
  4285. if (res.ok) {
  4286. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  4287. closePPPProfileModal();
  4288. loadPPPProfiles();
  4289. } else {
  4290. const err = await res.json();
  4291. showToast('Error', err.message, 'error');
  4292. }
  4293. } catch (err) {
  4294. showToast('Error', err.message, 'error');
  4295. }
  4296. }
  4297. async function deletePPPProfile(name) {
  4298. if (!confirm(`Delete PPP profile ${name}?`)) return;
  4299. try {
  4300. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  4301. if (res.ok) {
  4302. showToast('Deleted', 'Profile removed', 'success');
  4303. loadPPPProfiles();
  4304. } else {
  4305. const err = await res.json();
  4306. showToast('Error', err.message, 'error');
  4307. }
  4308. } catch (err) {
  4309. showToast('Error', err.message, 'error');
  4310. }
  4311. }
  4312. // Server Config submissions
  4313. async function savePPPoEServerConfig(e) {
  4314. e.preventDefault();
  4315. const enabled = document.getElementById('pppoe-server-enabled').checked;
  4316. const name = document.getElementById('pppoe-server-name').value.trim();
  4317. const iface = document.getElementById('pppoe-server-iface').value;
  4318. const profile = document.getElementById('pppoe-server-profile').value;
  4319. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  4320. const onesession = document.getElementById('pppoe-server-onesession').checked;
  4321. try {
  4322. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  4323. method: 'POST',
  4324. headers: { 'Content-Type': 'application/json' },
  4325. body: JSON.stringify({
  4326. enabled,
  4327. service_name: name,
  4328. interface: iface,
  4329. default_profile: profile,
  4330. max_mtu: mtu,
  4331. max_mru: mtu,
  4332. one_session_per_host: onesession
  4333. })
  4334. });
  4335. if (res.ok) {
  4336. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  4337. loadPPPServers();
  4338. fetchData(false);
  4339. } else {
  4340. const err = await res.json();
  4341. showToast('Error', err.message, 'error');
  4342. }
  4343. } catch (err) {
  4344. showToast('Error', err.message, 'error');
  4345. }
  4346. }
  4347. async function savePPTPServerConfig(e) {
  4348. e.preventDefault();
  4349. const enabled = document.getElementById('pptp-server-enabled').checked;
  4350. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  4351. const profile = document.getElementById('pptp-server-profile').value;
  4352. const mppe = document.getElementById('pptp-server-mppe').checked;
  4353. try {
  4354. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  4355. method: 'POST',
  4356. headers: { 'Content-Type': 'application/json' },
  4357. body: JSON.stringify({
  4358. enabled,
  4359. port,
  4360. default_profile: profile,
  4361. require_mppe: mppe
  4362. })
  4363. });
  4364. if (res.ok) {
  4365. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  4366. loadPPPServers();
  4367. fetchData(false);
  4368. } else {
  4369. const err = await res.json();
  4370. showToast('Error', err.message, 'error');
  4371. }
  4372. } catch (err) {
  4373. showToast('Error', err.message, 'error');
  4374. }
  4375. }
  4376. async function saveL2TPServerConfig(e) {
  4377. e.preventDefault();
  4378. const enabled = document.getElementById('l2tp-server-enabled').checked;
  4379. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  4380. const profile = document.getElementById('l2tp-server-profile').value;
  4381. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  4382. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  4383. try {
  4384. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  4385. method: 'POST',
  4386. headers: { 'Content-Type': 'application/json' },
  4387. body: JSON.stringify({
  4388. enabled,
  4389. port,
  4390. default_profile: profile,
  4391. use_ipsec: useipsec,
  4392. ipsec_secret: psk
  4393. })
  4394. });
  4395. if (res.ok) {
  4396. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  4397. loadPPPServers();
  4398. fetchData(false);
  4399. } else {
  4400. const err = await res.json();
  4401. showToast('Error', err.message, 'error');
  4402. }
  4403. } catch (err) {
  4404. showToast('Error', err.message, 'error');
  4405. }
  4406. }
  4407. // IPSec Server Modal
  4408. function openIPSecServerModal() {
  4409. loadPPPServers();
  4410. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  4411. }
  4412. function closeIPSecServerModal() {
  4413. document.getElementById('ipsec-server-modal').classList.add('hidden');
  4414. }
  4415. async function submitSaveIPSecServer(e) {
  4416. e.preventDefault();
  4417. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  4418. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  4419. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  4420. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  4421. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  4422. try {
  4423. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  4424. method: 'POST',
  4425. headers: { 'Content-Type': 'application/json' },
  4426. body: JSON.stringify({
  4427. enabled,
  4428. preshared_key: psk,
  4429. pool_address: pool,
  4430. dns_servers: dns,
  4431. local_subnet: subnet
  4432. })
  4433. });
  4434. if (res.ok) {
  4435. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  4436. closeIPSecServerModal();
  4437. loadPPPServers();
  4438. fetchData(false);
  4439. } else {
  4440. const err = await res.json();
  4441. showToast('Error', err.message, 'error');
  4442. }
  4443. } catch (err) {
  4444. showToast('Error', err.message, 'error');
  4445. }
  4446. }
  4447. // WireGuard Client Config Viewer
  4448. let currentWGClientConf = '';
  4449. async function openWGClientConfModal(iface, clientIP) {
  4450. try {
  4451. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  4452. method: 'POST',
  4453. headers: { 'Content-Type': 'application/json' },
  4454. body: JSON.stringify({
  4455. interface: iface,
  4456. address: clientIP || '10.10.0.2/32',
  4457. dns: '1.1.1.1, 8.8.8.8'
  4458. })
  4459. });
  4460. if (res.ok) {
  4461. const data = await res.json();
  4462. currentWGClientConf = data.config;
  4463. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  4464. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  4465. } else {
  4466. const err = await res.json();
  4467. showToast('Error', err.message, 'error');
  4468. }
  4469. } catch (err) {
  4470. showToast('Error', err.message, 'error');
  4471. }
  4472. }
  4473. function closeWGClientConfModal() {
  4474. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  4475. }
  4476. function copyWGClientConf() {
  4477. if (!currentWGClientConf) return;
  4478. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  4479. }
  4480. function downloadWGClientConf() {
  4481. if (!currentWGClientConf) return;
  4482. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  4483. const a = document.createElement('a');
  4484. a.href = URL.createObjectURL(blob);
  4485. a.download = 'wireguard-client.conf';
  4486. document.body.appendChild(a);
  4487. a.click();
  4488. document.body.removeChild(a);
  4489. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  4490. }
  4491. // =========================================================================
  4492. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  4493. // =========================================================================
  4494. state.activeDynSubTab = 'bgp-peers';
  4495. state.bgpInstance = null;
  4496. state.bgpPeers = [];
  4497. state.bgpNets = [];
  4498. state.bgpRoutes = [];
  4499. state.ospfInstance = null;
  4500. state.ospfInterfaces = [];
  4501. state.ospfAreas = [];
  4502. state.ospfNeighbors = [];
  4503. state.ospfRoutes = [];
  4504. function switchDynSubTab(subTab) {
  4505. state.activeDynSubTab = subTab;
  4506. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes', 'ospf-ifaces', 'ospf-areas', 'ospf-nbrs', 'ospf-routes'];
  4507. tabs.forEach(t => {
  4508. const el = document.getElementById(`dyn-subtab-${t}`);
  4509. const btn = document.getElementById(`dyn-subtab-btn-${t}`);
  4510. if (el) el.classList.toggle('hidden', t !== subTab);
  4511. if (btn) {
  4512. if (t === subTab) {
  4513. 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`;
  4514. } else {
  4515. 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';
  4516. }
  4517. }
  4518. });
  4519. }
  4520. async function loadDynamicRouting(showToastMsg = true) {
  4521. try {
  4522. const [sumRes, bgpInstRes, bgpPeersRes, bgpNetsRes, bgpRoutesRes, ospfInstRes, ospfIfacesRes, ospfAreasRes, ospfNbrsRes, ospfRoutesRes] = await Promise.all([
  4523. fetch(`${API_BASE}/routing/dynamic/summary`),
  4524. fetch(`${API_BASE}/routing/bgp/instance`),
  4525. fetch(`${API_BASE}/routing/bgp/peers`),
  4526. fetch(`${API_BASE}/routing/bgp/networks`),
  4527. fetch(`${API_BASE}/routing/bgp/routes`),
  4528. fetch(`${API_BASE}/routing/ospf/instance`),
  4529. fetch(`${API_BASE}/routing/ospf/interfaces`),
  4530. fetch(`${API_BASE}/routing/ospf/areas`),
  4531. fetch(`${API_BASE}/routing/ospf/neighbors`),
  4532. fetch(`${API_BASE}/routing/ospf/routes`)
  4533. ]);
  4534. if (sumRes.ok) state.dynSummary = await sumRes.json();
  4535. if (bgpInstRes.ok) state.bgpInstance = await bgpInstRes.json();
  4536. if (bgpPeersRes.ok) state.bgpPeers = await bgpPeersRes.json();
  4537. if (bgpNetsRes.ok) state.bgpNets = await bgpNetsRes.json();
  4538. if (bgpRoutesRes.ok) state.bgpRoutes = await bgpRoutesRes.json();
  4539. if (ospfInstRes.ok) state.ospfInstance = await ospfInstRes.json();
  4540. if (ospfIfacesRes.ok) state.ospfInterfaces = await ospfIfacesRes.json();
  4541. if (ospfAreasRes.ok) state.ospfAreas = await ospfAreasRes.json();
  4542. if (ospfNbrsRes.ok) state.ospfNeighbors = await ospfNbrsRes.json();
  4543. if (ospfRoutesRes.ok) state.ospfRoutes = await ospfRoutesRes.json();
  4544. renderBgpStatusPill();
  4545. renderBgpPeers();
  4546. renderBgpNetworks();
  4547. renderBgpRoutes();
  4548. renderOspfStatusPill();
  4549. renderOspfInterfaces();
  4550. renderOspfAreas();
  4551. renderOspfNeighbors();
  4552. renderOspfRoutes();
  4553. updateBadges();
  4554. } catch (err) {
  4555. console.error('Failed to load dynamic routing:', err);
  4556. if (showToastMsg) showToast('Error', 'Failed to load dynamic routing telemetry', 'error');
  4557. }
  4558. }
  4559. function renderBgpStatusPill() {
  4560. const pill = document.getElementById('bgp-live-status-pill');
  4561. if (!pill) return;
  4562. const inst = state.bgpInstance;
  4563. if (!inst || !inst.enabled) {
  4564. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  4565. pill.innerText = 'BGP DISABLED';
  4566. } else if (inst.running) {
  4567. 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';
  4568. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  4569. } else {
  4570. 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';
  4571. pill.innerText = 'BGP STARTING...';
  4572. }
  4573. }
  4574. function renderBgpPeers() {
  4575. const tbody = document.getElementById('bgp-peers-table-body');
  4576. const empty = document.getElementById('bgp-peers-empty');
  4577. const countBadge = document.getElementById('bgp-peers-count-badge');
  4578. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  4579. const peers = state.bgpPeers || [];
  4580. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  4581. if (navBadge) navBadge.innerText = peers.length;
  4582. if (peers.length === 0) {
  4583. tbody.innerHTML = '';
  4584. empty.classList.remove('hidden');
  4585. return;
  4586. }
  4587. empty.classList.add('hidden');
  4588. tbody.innerHTML = peers.map(p => {
  4589. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  4590. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  4591. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  4592. let stateBadge = '';
  4593. if (p.disabled) {
  4594. 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>';
  4595. } else if (p.state === 'Established') {
  4596. 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>';
  4597. } else if (p.state === 'Connect' || p.state === 'Active') {
  4598. 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>`;
  4599. } else {
  4600. 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>`;
  4601. }
  4602. return `
  4603. <tr class="hover:bg-slate-800/40 transition">
  4604. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  4605. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  4606. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  4607. <td class="py-2.5 px-3 font-bold text-slate-200">AS ${p.remote_as}</td>
  4608. <td class="py-2.5 px-3">${stateBadge}</td>
  4609. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  4610. <td class="py-2.5 px-3 text-slate-300">
  4611. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  4612. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  4613. </td>
  4614. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  4615. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  4616. <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'}">
  4617. ${p.disabled ? 'Enable' : 'Disable'}
  4618. </button>
  4619. <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">
  4620. Edit
  4621. </button>
  4622. <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">
  4623. Delete
  4624. </button>
  4625. </td>
  4626. </tr>
  4627. `;
  4628. }).join('');
  4629. }
  4630. function renderBgpNetworks() {
  4631. const tbody = document.getElementById('bgp-nets-table-body');
  4632. const empty = document.getElementById('bgp-nets-empty');
  4633. const countBadge = document.getElementById('bgp-nets-count-badge');
  4634. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  4635. const nets = state.bgpNets || [];
  4636. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  4637. if (navBadge) navBadge.innerText = nets.length;
  4638. if (nets.length === 0) {
  4639. tbody.innerHTML = '';
  4640. empty.classList.remove('hidden');
  4641. return;
  4642. }
  4643. empty.classList.add('hidden');
  4644. tbody.innerHTML = nets.map(n => `
  4645. <tr class="hover:bg-slate-800/40 transition">
  4646. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  4647. <td class="py-2.5 px-3">
  4648. ${n.disabled
  4649. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  4650. : '<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>'}
  4651. </td>
  4652. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  4653. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  4654. <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">
  4655. Delete
  4656. </button>
  4657. </td>
  4658. </tr>
  4659. `).join('');
  4660. }
  4661. function renderBgpRoutes() {
  4662. const tbody = document.getElementById('bgp-routes-table-body');
  4663. const empty = document.getElementById('bgp-routes-empty');
  4664. const countBadge = document.getElementById('bgp-routes-count-badge');
  4665. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  4666. const routes = state.bgpRoutes || [];
  4667. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  4668. if (navBadge) navBadge.innerText = routes.length;
  4669. if (routes.length === 0) {
  4670. tbody.innerHTML = '';
  4671. empty.classList.remove('hidden');
  4672. return;
  4673. }
  4674. empty.classList.add('hidden');
  4675. tbody.innerHTML = routes.map(r => `
  4676. <tr class="hover:bg-slate-800/40 transition">
  4677. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  4678. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  4679. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  4680. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  4681. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  4682. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  4683. </tr>
  4684. `).join('');
  4685. }
  4686. function renderOspfStatusPill() {
  4687. const pill = document.getElementById('ospf-live-status-pill');
  4688. if (!pill) return;
  4689. const inst = state.ospfInstance;
  4690. if (!inst || !inst.enabled) {
  4691. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  4692. pill.innerText = 'OSPF DISABLED';
  4693. } else if (inst.running) {
  4694. 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';
  4695. pill.innerText = `OSPF ACTIVE (ID: ${inst.router_id || 'Auto'})`;
  4696. } else {
  4697. 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';
  4698. pill.innerText = 'OSPF STARTING...';
  4699. }
  4700. }
  4701. function renderOspfInterfaces() {
  4702. const tbody = document.getElementById('ospf-ifaces-table-body');
  4703. const empty = document.getElementById('ospf-ifaces-empty');
  4704. const countBadge = document.getElementById('ospf-ifaces-count-badge');
  4705. const navBadge = document.getElementById('dyn-badge-ospf-ifaces');
  4706. const ifaces = state.ospfInterfaces || [];
  4707. if (countBadge) countBadge.innerText = `${ifaces.length} Interfaces`;
  4708. if (navBadge) navBadge.innerText = ifaces.length;
  4709. if (ifaces.length === 0) {
  4710. tbody.innerHTML = '';
  4711. empty.classList.remove('hidden');
  4712. return;
  4713. }
  4714. empty.classList.add('hidden');
  4715. tbody.innerHTML = ifaces.map(i => {
  4716. let flagA = !i.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  4717. let flagP = i.passive ? '<span class="text-amber-400 font-bold ml-1" title="Passive">P</span>' : '';
  4718. let flagX = i.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  4719. return `
  4720. <tr class="hover:bg-slate-800/40 transition">
  4721. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagP}${flagX}</td>
  4722. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(i.network)}</td>
  4723. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(i.area)}</td>
  4724. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(i.interface || 'Any')}</td>
  4725. <td class="py-2.5 px-3 text-slate-300">${i.cost}</td>
  4726. <td class="py-2.5 px-3 text-slate-300">${i.priority}</td>
  4727. <td class="py-2.5 px-3 text-slate-400">${i.hello_interval}s / ${i.dead_interval}s</td>
  4728. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(i.auth_type || 'none')}</td>
  4729. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(i.comment || '')}</td>
  4730. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  4731. <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'}">
  4732. ${i.disabled ? 'Enable' : 'Disable'}
  4733. </button>
  4734. <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">
  4735. Edit
  4736. </button>
  4737. <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">
  4738. Delete
  4739. </button>
  4740. </td>
  4741. </tr>
  4742. `;
  4743. }).join('');
  4744. }
  4745. function renderOspfAreas() {
  4746. const tbody = document.getElementById('ospf-areas-table-body');
  4747. const countBadge = document.getElementById('ospf-areas-count-badge');
  4748. const navBadge = document.getElementById('dyn-badge-ospf-areas');
  4749. const areas = state.ospfAreas || [];
  4750. if (countBadge) countBadge.innerText = `${areas.length} Areas`;
  4751. if (navBadge) navBadge.innerText = areas.length;
  4752. tbody.innerHTML = areas.map(a => `
  4753. <tr class="hover:bg-slate-800/40 transition">
  4754. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(a.name)}</td>
  4755. <td class="py-2.5 px-3 font-bold text-indigo-300">${escapeHtml(a.area_id)}</td>
  4756. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(a.area_type || 'default')}</td>
  4757. <td class="py-2.5 px-3 text-slate-400 font-sans">${escapeHtml(a.comment || '')}</td>
  4758. <td class="py-2.5 px-3 text-right font-sans">
  4759. <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">
  4760. Delete
  4761. </button>
  4762. </td>
  4763. </tr>
  4764. `).join('');
  4765. }
  4766. function renderOspfNeighbors() {
  4767. const tbody = document.getElementById('ospf-nbrs-table-body');
  4768. const empty = document.getElementById('ospf-nbrs-empty');
  4769. const countBadge = document.getElementById('ospf-nbrs-count-badge');
  4770. const navBadge = document.getElementById('dyn-badge-ospf-nbrs');
  4771. const nbrs = state.ospfNeighbors || [];
  4772. if (countBadge) countBadge.innerText = `${nbrs.length} Neighbors`;
  4773. if (navBadge) navBadge.innerText = nbrs.length;
  4774. if (nbrs.length === 0) {
  4775. tbody.innerHTML = '';
  4776. empty.classList.remove('hidden');
  4777. return;
  4778. }
  4779. empty.classList.add('hidden');
  4780. tbody.innerHTML = nbrs.map(n => {
  4781. let stateBadge = '';
  4782. if (n.state && (n.state.startsWith('Full') || n.state.includes('DR') || n.state.includes('Backup'))) {
  4783. 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>`;
  4784. } else {
  4785. 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>`;
  4786. }
  4787. return `
  4788. <tr class="hover:bg-slate-800/40 transition">
  4789. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(n.neighbor_id)}</td>
  4790. <td class="py-2.5 px-3 text-indigo-300 font-bold">${escapeHtml(n.address)}</td>
  4791. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(n.interface)}</td>
  4792. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.area || '0.0.0.0')}</td>
  4793. <td class="py-2.5 px-3">${stateBadge}</td>
  4794. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.dead_timer || '-')}</td>
  4795. </tr>
  4796. `;
  4797. }).join('');
  4798. }
  4799. function renderOspfRoutes() {
  4800. const tbody = document.getElementById('ospf-routes-table-body');
  4801. const empty = document.getElementById('ospf-routes-empty');
  4802. const countBadge = document.getElementById('ospf-routes-count-badge');
  4803. const navBadge = document.getElementById('dyn-badge-ospf-routes');
  4804. const routes = state.ospfRoutes || [];
  4805. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  4806. if (navBadge) navBadge.innerText = routes.length;
  4807. if (routes.length === 0) {
  4808. tbody.innerHTML = '';
  4809. empty.classList.remove('hidden');
  4810. return;
  4811. }
  4812. empty.classList.add('hidden');
  4813. tbody.innerHTML = routes.map(r => `
  4814. <tr class="hover:bg-slate-800/40 transition">
  4815. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(r.prefix)}</td>
  4816. <td class="py-2.5 px-3 text-slate-300">${escapeHtml(r.route_type || 'Network')}</td>
  4817. <td class="py-2.5 px-3 text-slate-300">${r.cost}</td>
  4818. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(r.area || '0.0.0.0')}</td>
  4819. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(r.next_hop || r.interface || '-')}</td>
  4820. </tr>
  4821. `).join('');
  4822. }
  4823. // BGP Modals & Actions
  4824. function openBgpInstanceModal() {
  4825. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  4826. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  4827. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  4828. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  4829. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  4830. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  4831. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  4832. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  4833. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  4834. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  4835. }
  4836. function closeBgpInstanceModal() {
  4837. document.getElementById('bgp-instance-modal').classList.add('hidden');
  4838. }
  4839. async function submitBgpInstance(e) {
  4840. e.preventDefault();
  4841. const payload = {
  4842. enabled: document.getElementById('modal-bgp-enabled').checked,
  4843. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  4844. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  4845. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  4846. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  4847. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  4848. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  4849. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  4850. };
  4851. try {
  4852. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  4853. method: 'POST',
  4854. headers: { 'Content-Type': 'application/json' },
  4855. body: JSON.stringify(payload)
  4856. });
  4857. if (res.ok) {
  4858. closeBgpInstanceModal();
  4859. showToast('Success', 'BGP instance configuration updated', 'success');
  4860. loadDynamicRouting();
  4861. } else {
  4862. const err = await res.json();
  4863. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  4864. }
  4865. } catch (err) {
  4866. showToast('Error', err.message, 'error');
  4867. }
  4868. }
  4869. function openAddBgpPeerModal() {
  4870. document.getElementById('bgp-peer-form').reset();
  4871. document.getElementById('modal-bgp-peer-id').value = '';
  4872. document.getElementById('bgp-peer-modal-title').innerText = 'Add BGP Peer Connection';
  4873. document.getElementById('modal-bgp-peer-nexthop-self').checked = true;
  4874. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  4875. }
  4876. function openEditBgpPeerModal(id) {
  4877. const p = (state.bgpPeers || []).find(item => item.id === id);
  4878. if (!p) return;
  4879. document.getElementById('modal-bgp-peer-id').value = p.id;
  4880. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  4881. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  4882. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  4883. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  4884. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  4885. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  4886. document.getElementById('modal-bgp-peer-nexthop-self').checked = !!p.nexthop_self;
  4887. document.getElementById('modal-bgp-peer-passive').checked = !!p.passive;
  4888. document.getElementById('modal-bgp-peer-disabled').checked = !!p.disabled;
  4889. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  4890. document.getElementById('bgp-peer-modal-title').innerText = 'Edit BGP Peer Connection';
  4891. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  4892. }
  4893. function closeBgpPeerModal() {
  4894. document.getElementById('bgp-peer-modal').classList.add('hidden');
  4895. }
  4896. async function submitBgpPeer(e) {
  4897. e.preventDefault();
  4898. const payload = {
  4899. id: document.getElementById('modal-bgp-peer-id').value,
  4900. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  4901. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  4902. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10),
  4903. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  4904. password: document.getElementById('modal-bgp-peer-password').value,
  4905. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  4906. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-self').checked,
  4907. passive: document.getElementById('modal-bgp-peer-passive').checked,
  4908. disabled: document.getElementById('modal-bgp-peer-disabled').checked,
  4909. comment: document.getElementById('modal-bgp-peer-comment').value.trim()
  4910. };
  4911. try {
  4912. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  4913. method: 'POST',
  4914. headers: { 'Content-Type': 'application/json' },
  4915. body: JSON.stringify(payload)
  4916. });
  4917. if (res.ok) {
  4918. closeBgpPeerModal();
  4919. showToast('Success', 'BGP Peer saved', 'success');
  4920. loadDynamicRouting();
  4921. } else {
  4922. const err = await res.json();
  4923. showToast('Error', err.error || 'Failed to save peer', 'error');
  4924. }
  4925. } catch (err) {
  4926. showToast('Error', err.message, 'error');
  4927. }
  4928. }
  4929. async function deleteBgpPeer(id) {
  4930. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  4931. try {
  4932. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4933. if (res.ok) {
  4934. showToast('Deleted', 'BGP peer removed', 'success');
  4935. loadDynamicRouting();
  4936. }
  4937. } catch (err) {
  4938. showToast('Error', err.message, 'error');
  4939. }
  4940. }
  4941. async function toggleBgpPeerState(id, disabled) {
  4942. try {
  4943. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  4944. method: 'POST',
  4945. headers: { 'Content-Type': 'application/json' },
  4946. body: JSON.stringify({ disabled })
  4947. });
  4948. if (res.ok) {
  4949. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  4950. loadDynamicRouting();
  4951. }
  4952. } catch (err) {
  4953. showToast('Error', err.message, 'error');
  4954. }
  4955. }
  4956. function openAddBgpNetworkModal() {
  4957. document.getElementById('bgp-network-form').reset();
  4958. document.getElementById('modal-bgp-net-id').value = '';
  4959. document.getElementById('bgp-network-modal').classList.remove('hidden');
  4960. }
  4961. function closeBgpNetworkModal() {
  4962. document.getElementById('bgp-network-modal').classList.add('hidden');
  4963. }
  4964. async function submitBgpNetwork(e) {
  4965. e.preventDefault();
  4966. const payload = {
  4967. id: document.getElementById('modal-bgp-net-id').value,
  4968. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  4969. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  4970. disabled: document.getElementById('modal-bgp-net-disabled').checked
  4971. };
  4972. try {
  4973. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  4974. method: 'POST',
  4975. headers: { 'Content-Type': 'application/json' },
  4976. body: JSON.stringify(payload)
  4977. });
  4978. if (res.ok) {
  4979. closeBgpNetworkModal();
  4980. showToast('Success', 'BGP network advertisement saved', 'success');
  4981. loadDynamicRouting();
  4982. } else {
  4983. const err = await res.json();
  4984. showToast('Error', err.error || 'Failed to save network', 'error');
  4985. }
  4986. } catch (err) {
  4987. showToast('Error', err.message, 'error');
  4988. }
  4989. }
  4990. async function deleteBgpNetwork(id) {
  4991. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  4992. try {
  4993. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4994. if (res.ok) {
  4995. showToast('Deleted', 'Network advertisement removed', 'success');
  4996. loadDynamicRouting();
  4997. }
  4998. } catch (err) {
  4999. showToast('Error', err.message, 'error');
  5000. }
  5001. }
  5002. // OSPF Modals & Actions
  5003. function openOspfInstanceModal() {
  5004. const inst = state.ospfInstance || { enabled: false, router_id: '192.168.131.56', default_metric: 10 };
  5005. document.getElementById('modal-ospf-enabled').checked = !!inst.enabled;
  5006. document.getElementById('modal-ospf-router-id').value = inst.router_id || '';
  5007. document.getElementById('modal-ospf-metric').value = inst.default_metric || 10;
  5008. document.getElementById('modal-ospf-redist-conn').checked = !!inst.redistribute_connected;
  5009. document.getElementById('modal-ospf-redist-static').checked = !!inst.redistribute_static;
  5010. document.getElementById('modal-ospf-redist-bgp').checked = !!inst.redistribute_bgp;
  5011. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  5012. }
  5013. function closeOspfInstanceModal() {
  5014. document.getElementById('ospf-instance-modal').classList.add('hidden');
  5015. }
  5016. async function submitOspfInstance(e) {
  5017. e.preventDefault();
  5018. const payload = {
  5019. enabled: document.getElementById('modal-ospf-enabled').checked,
  5020. router_id: document.getElementById('modal-ospf-router-id').value.trim(),
  5021. default_metric: parseInt(document.getElementById('modal-ospf-metric').value, 10),
  5022. redistribute_connected: document.getElementById('modal-ospf-redist-conn').checked,
  5023. redistribute_static: document.getElementById('modal-ospf-redist-static').checked,
  5024. redistribute_bgp: document.getElementById('modal-ospf-redist-bgp').checked
  5025. };
  5026. try {
  5027. const res = await fetch(`${API_BASE}/routing/ospf/instance`, {
  5028. method: 'POST',
  5029. headers: { 'Content-Type': 'application/json' },
  5030. body: JSON.stringify(payload)
  5031. });
  5032. if (res.ok) {
  5033. closeOspfInstanceModal();
  5034. showToast('Success', 'OSPF instance configuration updated', 'success');
  5035. loadDynamicRouting();
  5036. } else {
  5037. const err = await res.json();
  5038. showToast('Error', err.error || 'Failed to update OSPF instance', 'error');
  5039. }
  5040. } catch (err) {
  5041. showToast('Error', err.message, 'error');
  5042. }
  5043. }
  5044. function openAddOspfAreaModal() {
  5045. document.getElementById('ospf-area-form').reset();
  5046. document.getElementById('modal-ospf-area-id').value = '';
  5047. document.getElementById('modal-ospf-area-areaid').value = '0.0.0.0';
  5048. document.getElementById('ospf-area-modal').classList.remove('hidden');
  5049. }
  5050. function closeOspfAreaModal() {
  5051. document.getElementById('ospf-area-modal').classList.add('hidden');
  5052. }
  5053. async function submitOspfArea(e) {
  5054. e.preventDefault();
  5055. const payload = {
  5056. id: document.getElementById('modal-ospf-area-id').value,
  5057. name: document.getElementById('modal-ospf-area-name').value.trim(),
  5058. area_id: document.getElementById('modal-ospf-area-areaid').value.trim(),
  5059. area_type: document.getElementById('modal-ospf-area-type').value,
  5060. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  5061. };
  5062. try {
  5063. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  5064. method: 'POST',
  5065. headers: { 'Content-Type': 'application/json' },
  5066. body: JSON.stringify(payload)
  5067. });
  5068. if (res.ok) {
  5069. closeOspfAreaModal();
  5070. showToast('Success', 'OSPF area saved', 'success');
  5071. loadDynamicRouting();
  5072. } else {
  5073. const err = await res.json();
  5074. showToast('Error', err.error || 'Failed to save area', 'error');
  5075. }
  5076. } catch (err) {
  5077. showToast('Error', err.message, 'error');
  5078. }
  5079. }
  5080. async function deleteOspfArea(id) {
  5081. if (!confirm('Are you sure you want to delete this OSPF area?')) return;
  5082. try {
  5083. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5084. if (res.ok) {
  5085. showToast('Deleted', 'OSPF area removed', 'success');
  5086. loadDynamicRouting();
  5087. }
  5088. } catch (err) {
  5089. showToast('Error', err.message, 'error');
  5090. }
  5091. }
  5092. function populateOspfInterfaceDevices() {
  5093. const select = document.getElementById('modal-ospf-iface-device');
  5094. if (!select) return;
  5095. const current = select.value;
  5096. select.innerHTML = '<option value="">Any matching interface</option>';
  5097. (state.interfaces || []).forEach(iface => {
  5098. select.innerHTML += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)} (${iface.type})</option>`;
  5099. });
  5100. if (current) select.value = current;
  5101. }
  5102. function openAddOspfInterfaceModal() {
  5103. document.getElementById('ospf-interface-form').reset();
  5104. document.getElementById('modal-ospf-iface-id').value = '';
  5105. document.getElementById('modal-ospf-iface-area').value = '0.0.0.0';
  5106. document.getElementById('modal-ospf-iface-cost').value = '10';
  5107. document.getElementById('modal-ospf-iface-priority').value = '1';
  5108. document.getElementById('modal-ospf-iface-hello').value = '10';
  5109. document.getElementById('modal-ospf-iface-dead').value = '40';
  5110. document.getElementById('ospf-interface-modal-title').innerText = 'Add OSPF Interface';
  5111. populateOspfInterfaceDevices();
  5112. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  5113. }
  5114. function openEditOspfInterfaceModal(id) {
  5115. const item = (state.ospfInterfaces || []).find(i => i.id === id);
  5116. if (!item) return;
  5117. populateOspfInterfaceDevices();
  5118. document.getElementById('modal-ospf-iface-id').value = item.id;
  5119. document.getElementById('modal-ospf-iface-net').value = item.network || '';
  5120. document.getElementById('modal-ospf-iface-area').value = item.area || '0.0.0.0';
  5121. document.getElementById('modal-ospf-iface-device').value = item.interface || '';
  5122. document.getElementById('modal-ospf-iface-cost').value = item.cost || 10;
  5123. document.getElementById('modal-ospf-iface-priority').value = item.priority || 1;
  5124. document.getElementById('modal-ospf-iface-hello').value = item.hello_interval || 10;
  5125. document.getElementById('modal-ospf-iface-dead').value = item.dead_interval || 40;
  5126. document.getElementById('modal-ospf-iface-auth-type').value = item.auth_type || 'none';
  5127. document.getElementById('modal-ospf-iface-auth-key').value = item.auth_key || '';
  5128. document.getElementById('modal-ospf-iface-passive').checked = !!item.passive;
  5129. document.getElementById('modal-ospf-iface-disabled').checked = !!item.disabled;
  5130. document.getElementById('modal-ospf-iface-comment').value = item.comment || '';
  5131. document.getElementById('ospf-interface-modal-title').innerText = 'Edit OSPF Interface';
  5132. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  5133. }
  5134. function closeOspfInterfaceModal() {
  5135. document.getElementById('ospf-interface-modal').classList.add('hidden');
  5136. }
  5137. async function submitOspfInterface(e) {
  5138. e.preventDefault();
  5139. const payload = {
  5140. id: document.getElementById('modal-ospf-iface-id').value,
  5141. network: document.getElementById('modal-ospf-iface-net').value.trim(),
  5142. area: document.getElementById('modal-ospf-iface-area').value.trim(),
  5143. interface: document.getElementById('modal-ospf-iface-device').value,
  5144. cost: parseInt(document.getElementById('modal-ospf-iface-cost').value, 10),
  5145. priority: parseInt(document.getElementById('modal-ospf-iface-priority').value, 10),
  5146. hello_interval: parseInt(document.getElementById('modal-ospf-iface-hello').value, 10),
  5147. dead_interval: parseInt(document.getElementById('modal-ospf-iface-dead').value, 10),
  5148. auth_type: document.getElementById('modal-ospf-iface-auth-type').value,
  5149. auth_key: document.getElementById('modal-ospf-iface-auth-key').value,
  5150. passive: document.getElementById('modal-ospf-iface-passive').checked,
  5151. disabled: document.getElementById('modal-ospf-iface-disabled').checked,
  5152. comment: document.getElementById('modal-ospf-iface-comment').value.trim()
  5153. };
  5154. try {
  5155. const res = await fetch(`${API_BASE}/routing/ospf/interfaces`, {
  5156. method: 'POST',
  5157. headers: { 'Content-Type': 'application/json' },
  5158. body: JSON.stringify(payload)
  5159. });
  5160. if (res.ok) {
  5161. closeOspfInterfaceModal();
  5162. showToast('Success', 'OSPF interface template saved', 'success');
  5163. loadDynamicRouting();
  5164. } else {
  5165. const err = await res.json();
  5166. showToast('Error', err.error || 'Failed to save interface', 'error');
  5167. }
  5168. } catch (err) {
  5169. showToast('Error', err.message, 'error');
  5170. }
  5171. }
  5172. async function deleteOspfInterface(id) {
  5173. if (!confirm('Are you sure you want to delete this OSPF interface?')) return;
  5174. try {
  5175. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5176. if (res.ok) {
  5177. showToast('Deleted', 'OSPF interface removed', 'success');
  5178. loadDynamicRouting();
  5179. }
  5180. } catch (err) {
  5181. showToast('Error', err.message, 'error');
  5182. }
  5183. }
  5184. async function toggleOspfInterfaceState(id, disabled) {
  5185. try {
  5186. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}/state`, {
  5187. method: 'POST',
  5188. headers: { 'Content-Type': 'application/json' },
  5189. body: JSON.stringify({ disabled })
  5190. });
  5191. if (res.ok) {
  5192. showToast('Updated', `Interface ${disabled ? 'disabled' : 'enabled'}`, 'success');
  5193. loadDynamicRouting();
  5194. }
  5195. } catch (err) {
  5196. showToast('Error', err.message, 'error');
  5197. }
  5198. }