app.js 281 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708
  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. bridgeSubTab: 'bridges',
  11. bridges: [],
  12. bridgePorts: [],
  13. bridgeVLANs: [],
  14. bridgeHosts: [],
  15. bridgeSummary: null,
  16. routesSubTab: 'routes',
  17. pppSubTab: 'secrets',
  18. eoipTunnels: [],
  19. pppSecrets: [],
  20. pppProfiles: [],
  21. pppActiveSessions: [],
  22. pppoeServer: null,
  23. pptpServer: null,
  24. l2tpServer: null,
  25. ipsecServer: null,
  26. ifaceFilter: 'all',
  27. currentModalIface: null,
  28. isPolling: true,
  29. expandedParents: new Set(['eth0']),
  30. pppoeData: null,
  31. wgData: null,
  32. ipsecData: null,
  33. l2tpData: null,
  34. pptpData: null,
  35. fwSummary: null,
  36. filterRules: [],
  37. natRules: [],
  38. mangleRules: [],
  39. addressLists: [],
  40. connections: [],
  41. policyRules: [],
  42. routingTables: []
  43. };
  44. const API_BASE = '/api';
  45. // Initialize on page load
  46. document.addEventListener('DOMContentLoaded', () => {
  47. const hash = window.location.hash.replace('#', '') || 'dashboard';
  48. navigate(hash);
  49. fetchData();
  50. // Live polling every 2.5 seconds
  51. setInterval(() => {
  52. if (state.isPolling) {
  53. fetchData(false);
  54. }
  55. }, 2500);
  56. });
  57. // Navigation Handler
  58. function navigate(tabName) {
  59. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  60. navigate('bgp');
  61. return;
  62. }
  63. state.activeTab = tabName;
  64. window.location.hash = tabName;
  65. // Update nav links styling
  66. document.querySelectorAll('.nav-link').forEach(link => {
  67. 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';
  68. });
  69. const activeNav = document.getElementById(`nav-${tabName}`);
  70. if (activeNav) {
  71. 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';
  72. }
  73. // Update page headers
  74. const titles = {
  75. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  76. interfaces: { title: 'Network Interfaces', sub: 'Hierarchical view of physical interfaces and nested 802.1Q VLANs' },
  77. bridge: { title: 'Bridge Interfaces', sub: 'MikroTik-style IEEE 802.1D / 802.1Q VLAN Filtering Bridge with RSTP & FDB' },
  78. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  79. firewall: { title: 'MikroTik Firewall', sub: 'Filter rules, NAT, Mangle, Address Lists & Active Connections tracking' },
  80. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  81. bgp: { title: 'BGP Routing (/routing bgp)', sub: 'FRRouting BGP peering sessions, advertised networks, and BGP routing table (RIB)' },
  82. ospf: { title: 'OSPF Routing (/routing ospf)', sub: 'FRRouting OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  83. 'dynamic-routing': { title: 'BGP Routing (/routing bgp)', sub: 'FRRouting dynamic routing' },
  84. ppp: { title: 'PPP Servers & Secrets', sub: 'MikroTik RouterOS user accounts, IP pools and VPN server concentrators' },
  85. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP Layer 2 tunneling (MikroTik RouterOS style)' },
  86. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  87. wireguard: { title: 'WireGuard Kernel VPN', sub: 'Modern ultra-fast cryptographic VPN tunnel manager' },
  88. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  89. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  90. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  91. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' }
  92. };
  93. const header = titles[tabName] || titles.dashboard;
  94. const pTitle = document.getElementById('page-title');
  95. if (pTitle) pTitle.innerText = header.title;
  96. const pSub = document.getElementById('page-subtitle');
  97. if (pSub) pSub.innerText = header.sub;
  98. // Toggle sections dynamically for all section elements
  99. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  100. if (el.id === `section-${tabName}`) {
  101. el.classList.remove('hidden');
  102. } else {
  103. el.classList.add('hidden');
  104. }
  105. });
  106. if (tabName === 'bridge') loadBridge();
  107. if (tabName === 'firewall') loadFirewall();
  108. if (tabName === 'routes') loadRoutes();
  109. if (tabName === 'bgp') {
  110. loadDynamicRouting();
  111. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  112. }
  113. if (tabName === 'ospf') {
  114. loadDynamicRouting();
  115. switchOspfSubTab(state.activeOspfSubTab || 'ospf-ifaces');
  116. }
  117. if (tabName === 'dynamic-routing') loadDynamicRouting();
  118. if (tabName === 'ppp') loadPPP();
  119. if (tabName === 'eoip') loadEoIP();
  120. if (tabName === 'persistence') loadDebianConfig();
  121. if (tabName === 'pppoe') loadPPPoE();
  122. if (tabName === 'wireguard') loadWireGuard();
  123. if (tabName === 'ipsec') loadIPSec();
  124. if (tabName === 'l2tp') loadL2TP();
  125. if (tabName === 'pptp') loadPPTP();
  126. }
  127. // Fetch all core system, network and VPN telemetry
  128. async function fetchData(isManual = false) {
  129. const spinner = document.getElementById('refresh-spinner');
  130. if (isManual && spinner) spinner.classList.add('animate-spin');
  131. try {
  132. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes] = await Promise.all([
  133. fetch(`${API_BASE}/system/status`),
  134. fetch(`${API_BASE}/interfaces`),
  135. fetch(`${API_BASE}/vlans`),
  136. fetch(`${API_BASE}/vpn/status`),
  137. fetch(`${API_BASE}/firewall/summary`),
  138. fetch(`${API_BASE}/routing/dynamic/summary`),
  139. fetch(`${API_BASE}/bridge/summary`)
  140. ]);
  141. if (brSummaryRes.ok) {
  142. state.bridgeSummary = await brSummaryRes.json();
  143. const bBridge = document.getElementById('badge-bridge-count');
  144. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  145. const sBr = document.getElementById('bridge-stat-bridges');
  146. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  147. const sPorts = document.getElementById('bridge-stat-ports');
  148. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  149. const sHosts = document.getElementById('bridge-stat-hosts');
  150. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  151. }
  152. if (statusRes.ok) state.systemStatus = await statusRes.json();
  153. if (ifacesRes.ok) {
  154. const ifacesData = await ifacesRes.json();
  155. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  156. state.interfaces = rawIfaces.filter(i => {
  157. if (!i.name) return false;
  158. if (i.name.startsWith('ep_')) return false;
  159. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  160. });
  161. }
  162. if (vlansRes.ok) {
  163. const vlansData = await vlansRes.json();
  164. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  165. }
  166. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  167. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  168. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  169. updateSystemMetrics();
  170. updateBadges();
  171. if (state.activeTab === 'dashboard') renderDashboard();
  172. if (state.activeTab === 'interfaces') renderInterfacesList();
  173. if (state.activeTab === 'vlans') renderVlansList();
  174. if (state.activeTab === 'firewall') loadFirewall(false);
  175. if (state.activeTab === 'routes') loadRoutes(false);
  176. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  177. if (state.activeTab === 'ppp') loadPPP(false);
  178. if (state.activeTab === 'eoip') loadEoIP(false);
  179. if (state.activeTab === 'pppoe') loadPPPoE(false);
  180. if (state.activeTab === 'wireguard') loadWireGuard(false);
  181. if (state.activeTab === 'ipsec') loadIPSec(false);
  182. if (state.activeTab === 'l2tp') loadL2TP(false);
  183. if (state.activeTab === 'pptp') loadPPTP(false);
  184. } catch (err) {
  185. console.error('Failed to fetch router state:', err);
  186. } finally {
  187. if (isManual && spinner) {
  188. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  189. }
  190. }
  191. }
  192. // Update Top KPI and Sidebar Telemetry
  193. function updateSystemMetrics() {
  194. const s = state.systemStatus;
  195. const v = state.vpnStatus;
  196. if (!s) return;
  197. // Sidebar
  198. document.getElementById('side-hostname').innerText = s.hostname || 'debian-lxc';
  199. document.getElementById('side-uptime').innerText = s.uptime_human || '0m';
  200. document.getElementById('side-gateway-ip').innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  201. if (s.cpu_pct !== undefined) {
  202. const pct = s.cpu_pct;
  203. document.getElementById('side-cpu-val').innerText = `${pct.toFixed(1)}%`;
  204. document.getElementById('side-cpu-bar').style.width = `${Math.max(4, Math.min(100, pct))}%`;
  205. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  206. document.getElementById('side-cpu-bar').title = `Container: ${pct}% | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  207. } else if (s.cpu_load && s.cpu_load.length > 0) {
  208. const cores = s.cpu_cores || 4;
  209. const pct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  210. document.getElementById('side-cpu-val').innerText = `${pct}%`;
  211. document.getElementById('side-cpu-bar').style.width = `${Math.max(4, pct)}%`;
  212. }
  213. document.getElementById('side-ram-val').innerText = `${Math.round(s.mem_usage_pct || 0)}%`;
  214. document.getElementById('side-ram-bar').style.width = `${Math.max(5, Math.round(s.mem_usage_pct || 0))}%`;
  215. // Dashboard Stats
  216. document.getElementById('stat-ifaces-up').innerText = s.up_ifaces || 0;
  217. document.getElementById('stat-ifaces-total').innerText = `${s.total_ifaces || 0} Total`;
  218. document.getElementById('stat-ifaces-down').innerText = `${s.down_ifaces || 0} DOWN`;
  219. document.getElementById('stat-vlans-count').innerText = s.vlan_ifaces || 0;
  220. // VPN Status Indicators
  221. if (v) {
  222. const totalActive = v.total_active_tunnels || 0;
  223. const statVpnActive = document.getElementById('stat-vpn-active');
  224. if (statVpnActive) statVpnActive.innerText = totalActive;
  225. const tunnelsDot = document.getElementById('tunnels-dot');
  226. const tunnelsLabel = document.getElementById('tunnels-label');
  227. if (tunnelsDot && tunnelsLabel) {
  228. if (totalActive > 0) {
  229. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  230. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  231. } else {
  232. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  233. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  234. }
  235. }
  236. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  237. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  238. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  239. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  240. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  241. }
  242. // Total Live Bandwidth Rate
  243. let totalRx = 0;
  244. let totalTx = 0;
  245. (state.interfaces || []).forEach(i => {
  246. if (i.rate) {
  247. totalRx += i.rate.rx_bytes_sec || 0;
  248. totalTx += i.rate.tx_bytes_sec || 0;
  249. }
  250. });
  251. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  252. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  253. }
  254. function setDotBadge(id, active) {
  255. const el = document.getElementById(id);
  256. if (!el) return;
  257. if (active) {
  258. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  259. } else {
  260. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  261. }
  262. }
  263. function updateBadges() {
  264. const bIfaces = document.getElementById('badge-ifaces-count');
  265. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  266. const bVlans = document.getElementById('badge-vlans-count');
  267. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  268. if (state.fwSummary) {
  269. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  270. const badgeFw = document.getElementById('badge-firewall-count');
  271. if (badgeFw) badgeFw.innerText = totalFwRules;
  272. }
  273. if (state.vpnStatus) {
  274. const v = state.vpnStatus;
  275. const bEoIP = document.getElementById('badge-eoip-count');
  276. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  277. const bPPPSess = document.getElementById('badge-ppp-sessions');
  278. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  279. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  280. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  281. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  282. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  283. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  284. }
  285. if (state.dynSummary) {
  286. const d = state.dynSummary;
  287. setDotBadge('badge-bgp-dot', d.bgp_running);
  288. setDotBadge('badge-ospf-dot', d.ospf_running);
  289. const bBgp = document.getElementById('badge-bgp-count');
  290. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  291. const bOspf = document.getElementById('badge-ospf-count');
  292. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  293. }
  294. }
  295. // Render Dashboard View
  296. function renderDashboard() {
  297. const matrix = document.getElementById('port-matrix');
  298. matrix.innerHTML = '';
  299. (state.interfaces || []).forEach(iface => {
  300. const isUp = iface.state === 'UP';
  301. const isVlan = iface.is_vlan;
  302. const portCard = document.createElement('div');
  303. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  304. isUp
  305. ? (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')
  306. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  307. }`;
  308. portCard.onclick = () => openIfaceModal(iface.name);
  309. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  310. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  311. portCard.innerHTML = `
  312. <div class="flex items-center justify-between mb-2">
  313. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  314. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  315. </div>
  316. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  317. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  318. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  319. <span>${iface.rate?.rx_human || '0 B/s'}</span>
  320. </div>
  321. `;
  322. matrix.appendChild(portCard);
  323. });
  324. const ifaceTbody = document.getElementById('quick-interfaces-table');
  325. ifaceTbody.innerHTML = '';
  326. (state.interfaces || []).slice(0, 6).forEach(i => {
  327. const isUp = i.state === 'UP';
  328. const tr = document.createElement('tr');
  329. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  330. tr.onclick = () => openIfaceModal(i.name);
  331. tr.innerHTML = `
  332. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  333. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  334. <span>${i.name}</span>
  335. </td>
  336. <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>
  337. <td class="py-2.5 text-slate-300">${i.ipv4 && i.ipv4.length > 0 ? i.ipv4[0] : '<span class="text-slate-600">-</span>'}</td>
  338. <td class="py-2.5 text-right font-sans font-semibold ${isUp ? 'text-emerald-400' : 'text-rose-400'}">${i.state}</td>
  339. `;
  340. ifaceTbody.appendChild(tr);
  341. });
  342. const vlanTbody = document.getElementById('quick-vlans-table');
  343. vlanTbody.innerHTML = '';
  344. const vlans = state.vlans || [];
  345. if (vlans.length === 0) {
  346. 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>`;
  347. } else {
  348. vlans.slice(0, 6).forEach(v => {
  349. const tr = document.createElement('tr');
  350. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  351. tr.onclick = () => openIfaceModal(v.name);
  352. tr.innerHTML = `
  353. <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>
  354. <td class="py-2.5 text-white font-bold">${v.name}</td>
  355. <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>
  356. <td class="py-2.5 text-right text-slate-400">${v.parent_name || 'eth0'}</td>
  357. `;
  358. vlanTbody.appendChild(tr);
  359. });
  360. }
  361. }
  362. // Expand / Collapse Handlers
  363. function toggleExpand(parentName) {
  364. if (state.expandedParents.has(parentName)) {
  365. state.expandedParents.delete(parentName);
  366. } else {
  367. state.expandedParents.add(parentName);
  368. }
  369. renderInterfacesList();
  370. }
  371. function expandAllIfaces(expand) {
  372. if (expand) {
  373. (state.interfaces || []).forEach(i => {
  374. if (!i.is_vlan) state.expandedParents.add(i.name);
  375. });
  376. } else {
  377. state.expandedParents.clear();
  378. }
  379. renderInterfacesList();
  380. }
  381. // Filter and Render Hierarchical Interfaces List
  382. function filterIfaces(filter) {
  383. state.ifaceFilter = filter;
  384. document.querySelectorAll('.filter-btn').forEach(btn => {
  385. 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';
  386. });
  387. const activeBtn = document.getElementById(`filter-${filter}`);
  388. if (activeBtn) {
  389. activeBtn.className = 'filter-btn px-3 py-1.5 rounded-lg text-xs font-medium bg-slate-800 text-white border border-slate-700';
  390. }
  391. renderInterfacesList();
  392. }
  393. function renderInterfacesList() {
  394. const tbody = document.getElementById('interfaces-tree-tbody');
  395. const emptyState = document.getElementById('interfaces-empty-state');
  396. const summary = document.getElementById('ifaces-list-summary');
  397. const query = (document.getElementById('iface-search')?.value || '').toLowerCase();
  398. tbody.innerHTML = '';
  399. const allIfaces = state.interfaces || [];
  400. const allVlans = state.vlans || [];
  401. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  402. const filteredParents = parentIfaces.filter(parent => {
  403. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  404. if (query) {
  405. const matchParent = parent.name.toLowerCase().includes(query) || (parent.role || '').toLowerCase().includes(query);
  406. const matchVlan = childVlans.some(v => v.name.toLowerCase().includes(query) || String(v.vlan_id).includes(query) || (v.description || '').toLowerCase().includes(query));
  407. if (!matchParent && !matchVlan) return false;
  408. }
  409. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  410. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  411. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  412. return true;
  413. });
  414. if (summary) {
  415. summary.innerText = `${parentIfaces.length} Physical/Parent Links • ${allVlans.length} Active VLANs`;
  416. }
  417. if (filteredParents.length === 0) {
  418. emptyState?.classList.remove('hidden');
  419. return;
  420. }
  421. emptyState?.classList.add('hidden');
  422. filteredParents.forEach(parent => {
  423. const isUp = parent.state === 'UP';
  424. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  425. const isExpanded = state.expandedParents.has(parent.name);
  426. const parentRow = document.createElement('tr');
  427. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  428. parentRow.innerHTML = `
  429. <td class="py-3 px-3 text-center">
  430. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  431. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  432. <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">
  433. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  434. </svg>
  435. </button>
  436. </td>
  437. <td class="py-3 px-4">
  438. <div class="flex items-center space-x-2.5">
  439. <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">
  440. ${parent.type === 'loopback' ? 'LO' : 'NIC'}
  441. </div>
  442. <div>
  443. <div class="flex items-center gap-2">
  444. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400" onclick="toggleExpand('${parent.name}')">${parent.name}</span>
  445. ${childVlans.length > 0
  446. ? `<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>`
  447. : `<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>`
  448. }
  449. </div>
  450. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  451. </div>
  452. </div>
  453. </td>
  454. <td class="py-3 px-4 font-sans">
  455. <div class="flex items-center gap-1.5">
  456. <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>
  457. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  458. </div>
  459. </td>
  460. <td class="py-3 px-4">
  461. ${parent.ipv4 && parent.ipv4.length > 0
  462. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  463. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  464. }
  465. </td>
  466. <td class="py-3 px-4 text-slate-400 text-[11px]">
  467. <div>${parent.mac || 'N/A'}</div>
  468. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  469. </td>
  470. <td class="py-3 px-4 text-[11px]">
  471. <div class="flex items-center space-x-2">
  472. <span class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  473. <span class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  474. </div>
  475. </td>
  476. <td class="py-3 px-4 font-sans">
  477. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  478. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  479. 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'
  480. }" title="Click to toggle link status">
  481. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  482. <span>${parent.state}</span>
  483. </button>
  484. </td>
  485. <td class="py-3 px-4 text-right space-x-2 font-sans">
  486. <button onclick="openVlanModal('${parent.name}')"
  487. 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">
  488. + Add VLAN
  489. </button>
  490. <button onclick="openIfaceModal('${parent.name}')"
  491. 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">
  492. Configure
  493. </button>
  494. </td>
  495. `;
  496. tbody.appendChild(parentRow);
  497. if (isExpanded) {
  498. const drawerRow = document.createElement('tr');
  499. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  500. const drawerCell = document.createElement('td');
  501. drawerCell.colSpan = 8;
  502. drawerCell.className = 'p-0';
  503. drawerCell.innerHTML = `
  504. <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">
  505. <div class="flex items-center justify-between mb-3">
  506. <div class="flex items-center space-x-3">
  507. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  508. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  509. </span>
  510. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  511. ${childVlans.length} Attached
  512. </span>
  513. </div>
  514. <button onclick="openVlanModal('${parent.name}')"
  515. 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">
  516. <span>+ Create VLAN on ${parent.name}</span>
  517. </button>
  518. </div>
  519. ${childVlans.length === 0 ? `
  520. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  521. <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>
  522. <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">
  523. <span>+ Create Your First VLAN on ${parent.name}</span>
  524. </button>
  525. </div>
  526. ` : `
  527. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  528. <table class="w-full text-left text-xs font-mono">
  529. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  530. <tr>
  531. <th class="py-2.5 px-4">VLAN ID</th>
  532. <th class="py-2.5 px-4">Interface Device</th>
  533. <th class="py-2.5 px-4">Subnet Gateway</th>
  534. <th class="py-2.5 px-4">Role / Alias</th>
  535. <th class="py-2.5 px-4">MTU</th>
  536. <th class="py-2.5 px-4">Throughput</th>
  537. <th class="py-2.5 px-4">Status</th>
  538. <th class="py-2.5 px-4 text-right">Actions</th>
  539. </tr>
  540. </thead>
  541. <tbody class="divide-y divide-slate-800/70">
  542. ${childVlans.map(v => {
  543. const isVlanUp = v.state === 'UP';
  544. return `
  545. <tr class="hover:bg-slate-800/40 transition">
  546. <td class="py-2.5 px-4">
  547. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  548. VLAN ${v.vlan_id}
  549. </span>
  550. </td>
  551. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  552. <span class="text-cyan-500">└─</span>
  553. <span>${v.name}</span>
  554. </td>
  555. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  556. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  557. </td>
  558. <td class="py-2.5 px-4 font-sans text-slate-300">
  559. <span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 mr-1.5">${v.role || 'VLAN'}</span>
  560. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  561. </td>
  562. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  563. <td class="py-2.5 px-4 text-[11px]">
  564. <span class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  565. <span class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  566. </td>
  567. <td class="py-2.5 px-4 font-sans">
  568. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  569. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  570. 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'
  571. }">
  572. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  573. <span>${v.state}</span>
  574. </button>
  575. </td>
  576. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  577. <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>
  578. <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>
  579. </td>
  580. </tr>
  581. `;
  582. }).join('')}
  583. </tbody>
  584. </table>
  585. </div>
  586. `}
  587. </div>
  588. `;
  589. drawerRow.appendChild(drawerCell);
  590. tbody.appendChild(drawerRow);
  591. }
  592. });
  593. }
  594. // Render VLANs Dedicated View
  595. function renderVlansList() {
  596. const tbody = document.getElementById('vlans-table-body');
  597. const emptyState = document.getElementById('vlans-empty-state');
  598. const countBadge = document.getElementById('vlans-table-count');
  599. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  600. tbody.innerHTML = '';
  601. const allVlans = state.vlans || [];
  602. countBadge.innerText = allVlans.length;
  603. const filtered = allVlans.filter(v => {
  604. if (!query) return true;
  605. return v.name.toLowerCase().includes(query) ||
  606. String(v.vlan_id).includes(query) ||
  607. (v.description || '').toLowerCase().includes(query) ||
  608. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  609. });
  610. if (allVlans.length === 0) {
  611. emptyState.classList.remove('hidden');
  612. return;
  613. }
  614. emptyState.classList.add('hidden');
  615. filtered.forEach(v => {
  616. const isUp = v.state === 'UP';
  617. const tr = document.createElement('tr');
  618. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  619. tr.innerHTML = `
  620. <td class="py-3 px-4">
  621. <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">
  622. VLAN ${v.vlan_id}
  623. </span>
  624. </td>
  625. <td class="py-3 px-4 font-bold text-white">${v.name}</td>
  626. <td class="py-3 px-4 text-slate-300">
  627. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  628. </td>
  629. <td class="py-3 px-4 text-emerald-400 font-medium">
  630. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  631. </td>
  632. <td class="py-3 px-4 text-slate-300 font-sans">
  633. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  634. </td>
  635. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  636. <td class="py-3 px-4 font-sans">
  637. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  638. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  639. 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'
  640. }">
  641. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  642. <span>${v.state}</span>
  643. </button>
  644. </td>
  645. <td class="py-3 px-4 text-right space-x-2 font-sans">
  646. <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>
  647. <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>
  648. </td>
  649. `;
  650. tbody.appendChild(tr);
  651. });
  652. }
  653. // Toggle interface UP / DOWN
  654. async function toggleInterfaceState(name, newState) {
  655. try {
  656. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  657. method: 'POST',
  658. headers: { 'Content-Type': 'application/json' },
  659. body: JSON.stringify({ state: newState })
  660. });
  661. const data = await res.json();
  662. if (res.ok) {
  663. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  664. fetchData(false);
  665. } else {
  666. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  667. }
  668. } catch (err) {
  669. showToast('Error', err.message, 'error');
  670. }
  671. }
  672. // ---------------- MikroTik Flag & Utilities ----------------
  673. function renderMikroTikFlag(running, disabled) {
  674. if (running) {
  675. 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>`;
  676. }
  677. if (disabled) {
  678. 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>`;
  679. }
  680. 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>`;
  681. }
  682. function copyToClipboard(text, label = 'Text') {
  683. navigator.clipboard.writeText(text).then(() => {
  684. showToast('Copied', `${label} copied to clipboard`, 'success');
  685. }).catch(() => {
  686. prompt('Copy value:', text);
  687. });
  688. }
  689. // ======================== PPPoE Multi-Instance ========================
  690. async function loadPPPoE(populateInputs = true) {
  691. try {
  692. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  693. const list = await res.json();
  694. state.pppoeList = Array.isArray(list) ? list : [];
  695. const badge = document.getElementById('pppoe-count-badge');
  696. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  697. const tbody = document.getElementById('pppoe-table-body');
  698. const empty = document.getElementById('pppoe-empty');
  699. if (!tbody) return;
  700. tbody.innerHTML = '';
  701. if (state.pppoeList.length === 0) {
  702. if (empty) empty.classList.remove('hidden');
  703. } else {
  704. if (empty) empty.classList.add('hidden');
  705. state.pppoeList.forEach(inst => {
  706. const tr = document.createElement('tr');
  707. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  708. tr.innerHTML = `
  709. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  710. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  711. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.interface}</td>
  712. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  713. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  714. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  715. <td class="py-2.5 px-3 text-center">
  716. <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'}">
  717. ${inst.default_route ? 'Yes' : 'No'}
  718. </span>
  719. </td>
  720. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  721. ${inst.running ? `
  722. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  723. ` : `
  724. <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>
  725. `}
  726. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  727. ${inst.disabled ? 'Enable' : 'Disable'}
  728. </button>
  729. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  730. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  731. </td>
  732. `;
  733. tbody.appendChild(tr);
  734. });
  735. }
  736. } catch (err) {
  737. console.error('Failed to load PPPoE:', err);
  738. }
  739. }
  740. function openAddPPPoEModal() {
  741. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  742. document.getElementById('pppoe-modal-edit-orig').value = '';
  743. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  744. document.getElementById('pppoe-modal-name').readOnly = false;
  745. document.getElementById('pppoe-modal-user').value = '';
  746. document.getElementById('pppoe-modal-pass').value = '';
  747. document.getElementById('pppoe-modal-service').value = '';
  748. document.getElementById('pppoe-modal-mtu').value = '1492';
  749. document.getElementById('pppoe-modal-defroute').checked = true;
  750. document.getElementById('pppoe-modal-reconnect').checked = true;
  751. document.getElementById('pppoe-modal-disabled').checked = false;
  752. // Populate interfaces
  753. const sel = document.getElementById('pppoe-modal-iface');
  754. sel.innerHTML = '';
  755. (state.interfaces || []).forEach(i => {
  756. if (i.name === 'lo') return;
  757. const opt = document.createElement('option');
  758. opt.value = i.name;
  759. opt.innerText = `${i.name} (${i.role || i.type})`;
  760. sel.appendChild(opt);
  761. });
  762. document.getElementById('pppoe-modal').classList.remove('hidden');
  763. }
  764. function openEditPPPoEModal(name) {
  765. const inst = (state.pppoeList || []).find(i => i.name === name);
  766. if (!inst) return;
  767. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  768. document.getElementById('pppoe-modal-edit-orig').value = name;
  769. document.getElementById('pppoe-modal-name').value = inst.name;
  770. document.getElementById('pppoe-modal-name').readOnly = true;
  771. document.getElementById('pppoe-modal-user').value = inst.username || '';
  772. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  773. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  774. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  775. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  776. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  777. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  778. const sel = document.getElementById('pppoe-modal-iface');
  779. sel.innerHTML = '';
  780. (state.interfaces || []).forEach(i => {
  781. if (i.name === 'lo') return;
  782. const opt = document.createElement('option');
  783. opt.value = i.name;
  784. opt.innerText = `${i.name} (${i.role || i.type})`;
  785. if (i.name === inst.interface) opt.selected = true;
  786. sel.appendChild(opt);
  787. });
  788. document.getElementById('pppoe-modal').classList.remove('hidden');
  789. }
  790. function closePPPoEModal() {
  791. document.getElementById('pppoe-modal').classList.add('hidden');
  792. }
  793. async function submitSavePPPoE(e) {
  794. e.preventDefault();
  795. const name = document.getElementById('pppoe-modal-name').value.trim();
  796. const iface = document.getElementById('pppoe-modal-iface').value;
  797. const user = document.getElementById('pppoe-modal-user').value.trim();
  798. const pass = document.getElementById('pppoe-modal-pass').value;
  799. const service = document.getElementById('pppoe-modal-service').value.trim();
  800. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  801. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  802. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  803. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  804. try {
  805. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  806. method: 'POST',
  807. headers: { 'Content-Type': 'application/json' },
  808. body: JSON.stringify({
  809. name,
  810. interface: iface,
  811. username: user,
  812. password: pass,
  813. service_name: service,
  814. mtu,
  815. default_route: defRoute,
  816. auto_reconnect: reconnect,
  817. disabled
  818. })
  819. });
  820. if (res.ok) {
  821. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  822. closePPPoEModal();
  823. loadPPPoE(false);
  824. fetchData(false);
  825. } else {
  826. const err = await res.json();
  827. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  828. }
  829. } catch (err) {
  830. showToast('Error', err.message, 'error');
  831. }
  832. }
  833. async function connectPPPoEInstance(name) {
  834. try {
  835. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  836. if (res.ok) {
  837. showToast('Connecting', `Dialing ${name}...`, 'info');
  838. setTimeout(() => loadPPPoE(false), 2000);
  839. }
  840. } catch (err) {
  841. showToast('Error', err.message, 'error');
  842. }
  843. }
  844. async function disconnectPPPoEInstance(name) {
  845. try {
  846. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  847. if (res.ok) {
  848. showToast('Disconnected', `${name} session terminated`, 'info');
  849. setTimeout(() => loadPPPoE(false), 1000);
  850. }
  851. } catch (err) {
  852. showToast('Error', err.message, 'error');
  853. }
  854. }
  855. async function togglePPPoEState(name, enable) {
  856. try {
  857. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  858. method: 'POST',
  859. headers: { 'Content-Type': 'application/json' },
  860. body: JSON.stringify({ enabled: enable })
  861. });
  862. if (res.ok) {
  863. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  864. loadPPPoE(false);
  865. }
  866. } catch (err) {
  867. showToast('Error', err.message, 'error');
  868. }
  869. }
  870. async function deletePPPoEInstance(name) {
  871. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  872. try {
  873. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  874. if (res.ok) {
  875. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  876. loadPPPoE(false);
  877. fetchData(false);
  878. }
  879. } catch (err) {
  880. showToast('Error', err.message, 'error');
  881. }
  882. }
  883. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  884. state.wgSubTab = 'ifaces';
  885. function switchWGSubTab(tab) {
  886. state.wgSubTab = tab;
  887. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  888. const peersPanel = document.getElementById('wg-subtab-peers');
  889. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  890. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  891. if (tab === 'ifaces') {
  892. ifacesPanel?.classList.remove('hidden');
  893. peersPanel?.classList.add('hidden');
  894. 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';
  895. 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';
  896. } else {
  897. ifacesPanel?.classList.add('hidden');
  898. peersPanel?.classList.remove('hidden');
  899. 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';
  900. 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';
  901. renderWGPeers();
  902. }
  903. }
  904. async function loadWireGuard(populateInputs = true) {
  905. try {
  906. const [ifacesRes, peersRes] = await Promise.all([
  907. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  908. fetch(`${API_BASE}/vpn/wireguard/peers`)
  909. ]);
  910. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  911. const peers = peersRes.ok ? await peersRes.json() : [];
  912. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  913. state.wgPeers = Array.isArray(peers) ? peers : [];
  914. // Badges
  915. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  916. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  917. const peersCountBadge = document.getElementById('wg-peers-count');
  918. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  919. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  920. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  921. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  922. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  923. // Render Interfaces
  924. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  925. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  926. if (ifacesTbody) {
  927. ifacesTbody.innerHTML = '';
  928. if (state.wgInterfaces.length === 0) {
  929. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  930. } else {
  931. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  932. state.wgInterfaces.forEach(iface => {
  933. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  934. const tr = document.createElement('tr');
  935. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  936. tr.innerHTML = `
  937. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  938. <td class="py-2.5 px-3 font-bold text-white">${iface.name}</td>
  939. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  940. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '-'}</td>
  941. <td class="py-2.5 px-3 text-slate-300 font-mono">
  942. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  943. ${(iface.public_key || '').substring(0, 10)}... 📋
  944. </span>
  945. </td>
  946. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  947. <td class="py-2.5 px-3 text-center">
  948. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  949. </td>
  950. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  951. ${iface.running ? `
  952. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300">Stop</button>
  953. ` : `
  954. <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>
  955. `}
  956. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  957. ${iface.disabled ? 'Enable' : 'Disable'}
  958. </button>
  959. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  960. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  961. </td>
  962. `;
  963. ifacesTbody.appendChild(tr);
  964. });
  965. }
  966. }
  967. // Populate filter dropdown in peers tab
  968. const filterSel = document.getElementById('wg-peers-filter-iface');
  969. if (filterSel) {
  970. const currentVal = filterSel.value;
  971. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  972. state.wgInterfaces.forEach(i => {
  973. const opt = document.createElement('option');
  974. opt.value = i.name;
  975. opt.innerText = i.name;
  976. if (i.name === currentVal) opt.selected = true;
  977. filterSel.appendChild(opt);
  978. });
  979. }
  980. renderWGPeers();
  981. } catch (err) {
  982. console.error('Failed to load WireGuard:', err);
  983. }
  984. }
  985. function renderWGPeers() {
  986. const filterSel = document.getElementById('wg-peers-filter-iface');
  987. const selectedIface = filterSel ? filterSel.value : '';
  988. const tbody = document.getElementById('wg-peers-table-body');
  989. const empty = document.getElementById('wg-peers-empty');
  990. if (!tbody) return;
  991. tbody.innerHTML = '';
  992. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  993. if (filtered.length === 0) {
  994. if (empty) empty.classList.remove('hidden');
  995. } else {
  996. if (empty) empty.classList.add('hidden');
  997. filtered.forEach(p => {
  998. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  999. const tr = document.createElement('tr');
  1000. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1001. tr.innerHTML = `
  1002. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1003. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${p.interface}</td>
  1004. <td class="py-2.5 px-3 font-bold text-white font-sans">${p.name || 'Unnamed'}</td>
  1005. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1006. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1007. ${p.public_key.substring(0, 10)}... 📋
  1008. </span>
  1009. </td>
  1010. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1011. <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>
  1012. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1013. <td class="py-2.5 px-3 font-mono text-[11px]">
  1014. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1015. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1016. </td>
  1017. <td class="py-2.5 px-3 text-right font-sans space-x-2">
  1018. <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>
  1019. <button onclick="deleteWGPeer('${p.interface}', '${p.public_key}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  1020. </td>
  1021. `;
  1022. tbody.appendChild(tr);
  1023. });
  1024. }
  1025. }
  1026. function openAddWGInterfaceModal() {
  1027. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1028. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1029. document.getElementById('wg-iface-modal-name').value = `wg${(state.wgInterfaces || []).length}`;
  1030. document.getElementById('wg-iface-modal-name').readOnly = false;
  1031. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1032. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1033. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1034. document.getElementById('wg-iface-modal-pubkey').value = '';
  1035. document.getElementById('wg-iface-modal-privkey').value = '';
  1036. document.getElementById('wg-iface-modal-disabled').checked = false;
  1037. generateWGInterfaceKeys();
  1038. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1039. }
  1040. function openEditWGInterfaceModal(name) {
  1041. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1042. if (!iface) return;
  1043. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1044. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1045. document.getElementById('wg-iface-modal-name').value = iface.name;
  1046. document.getElementById('wg-iface-modal-name').readOnly = true;
  1047. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1048. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1049. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1050. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1051. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1052. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1053. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1054. }
  1055. function closeAddWGInterfaceModal() {
  1056. document.getElementById('wg-iface-modal').classList.add('hidden');
  1057. }
  1058. async function generateWGInterfaceKeys() {
  1059. try {
  1060. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1061. const keys = await res.json();
  1062. if (res.ok) {
  1063. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1064. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1065. }
  1066. } catch (err) {
  1067. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1068. }
  1069. }
  1070. async function submitSaveWGInterface(e) {
  1071. e.preventDefault();
  1072. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1073. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1074. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1075. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1076. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1077. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1078. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1079. try {
  1080. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1081. method: 'POST',
  1082. headers: { 'Content-Type': 'application/json' },
  1083. body: JSON.stringify({
  1084. name,
  1085. listen_port: port,
  1086. address: addr,
  1087. mtu,
  1088. public_key: pub,
  1089. private_key: priv,
  1090. disabled
  1091. })
  1092. });
  1093. if (res.ok) {
  1094. showToast('WireGuard Saved', `Interface ${name} configured`, 'success');
  1095. closeAddWGInterfaceModal();
  1096. loadWireGuard(false);
  1097. fetchData(false);
  1098. }
  1099. } catch (err) {
  1100. showToast('Error', err.message, 'error');
  1101. }
  1102. }
  1103. async function startWGInterface(name) {
  1104. try {
  1105. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1106. if (res.ok) {
  1107. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1108. loadWireGuard(false);
  1109. fetchData(false);
  1110. }
  1111. } catch (err) {
  1112. showToast('Error', err.message, 'error');
  1113. }
  1114. }
  1115. async function stopWGInterface(name) {
  1116. try {
  1117. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1118. if (res.ok) {
  1119. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1120. loadWireGuard(false);
  1121. fetchData(false);
  1122. }
  1123. } catch (err) {
  1124. showToast('Error', err.message, 'error');
  1125. }
  1126. }
  1127. async function toggleWGInterfaceState(name, enable) {
  1128. try {
  1129. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1130. method: 'POST',
  1131. headers: { 'Content-Type': 'application/json' },
  1132. body: JSON.stringify({ enabled: enable })
  1133. });
  1134. if (res.ok) {
  1135. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1136. loadWireGuard(false);
  1137. }
  1138. } catch (err) {
  1139. showToast('Error', err.message, 'error');
  1140. }
  1141. }
  1142. async function deleteWGInterface(name) {
  1143. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}?`)) return;
  1144. try {
  1145. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1146. if (res.ok) {
  1147. showToast('Deleted', `Interface ${name} removed`, 'success');
  1148. loadWireGuard(false);
  1149. fetchData(false);
  1150. }
  1151. } catch (err) {
  1152. showToast('Error', err.message, 'error');
  1153. }
  1154. }
  1155. function openAddWGPeerModal() {
  1156. const sel = document.getElementById('wg-peer-modal-iface');
  1157. sel.innerHTML = '';
  1158. (state.wgInterfaces || []).forEach(i => {
  1159. const opt = document.createElement('option');
  1160. opt.value = i.name;
  1161. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1162. sel.appendChild(opt);
  1163. });
  1164. if ((state.wgInterfaces || []).length === 0) {
  1165. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1166. openAddWGInterfaceModal();
  1167. return;
  1168. }
  1169. document.getElementById('wg-peer-modal-name').value = '';
  1170. document.getElementById('wg-peer-modal-pubkey').value = '';
  1171. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1172. document.getElementById('wg-peer-modal-endpoint').value = '';
  1173. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1174. document.getElementById('wg-peer-modal-preshared').value = '';
  1175. document.getElementById('wg-peer-modal-disabled').checked = false;
  1176. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1177. }
  1178. function closeAddWGPeerModal() {
  1179. document.getElementById('wg-peer-modal').classList.add('hidden');
  1180. }
  1181. async function submitSaveWGPeer(e) {
  1182. e.preventDefault();
  1183. const iface = document.getElementById('wg-peer-modal-iface').value;
  1184. const name = document.getElementById('wg-peer-modal-name').value.trim();
  1185. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1186. const allowed = document.getElementById('wg-peer-modal-allowedips').value.split(',').map(s => s.trim());
  1187. const ep = document.getElementById('wg-peer-modal-endpoint').value.trim();
  1188. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 25;
  1189. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  1190. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  1191. let epAddr = ep;
  1192. let epPort = 0;
  1193. if (ep.includes(':')) {
  1194. const parts = ep.split(':');
  1195. epAddr = parts[0];
  1196. epPort = parseInt(parts[1], 10) || 0;
  1197. }
  1198. try {
  1199. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  1200. method: 'POST',
  1201. headers: { 'Content-Type': 'application/json' },
  1202. body: JSON.stringify({
  1203. interface: iface,
  1204. name,
  1205. public_key: pub,
  1206. allowed_ips: allowed,
  1207. endpoint_address: epAddr,
  1208. endpoint_port: epPort,
  1209. persistent_keepalive: keepalive,
  1210. preshared_key: psk,
  1211. disabled
  1212. })
  1213. });
  1214. if (res.ok) {
  1215. showToast('Peer Saved', `Peer ${name} added to ${iface}`, 'success');
  1216. closeAddWGPeerModal();
  1217. loadWireGuard(false);
  1218. }
  1219. } catch (err) {
  1220. showToast('Error', err.message, 'error');
  1221. }
  1222. }
  1223. async function deleteWGPeer(iface, pubkey) {
  1224. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  1225. try {
  1226. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/${encodeURIComponent(iface)}/${encodeURIComponent(pubkey)}`, {
  1227. method: 'DELETE'
  1228. });
  1229. if (res.ok) {
  1230. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  1231. loadWireGuard(false);
  1232. }
  1233. } catch (err) {
  1234. showToast('Error', err.message, 'error');
  1235. }
  1236. }
  1237. // ======================== IPSec Multi-Tunnel ========================
  1238. async function loadIPSec(populateInputs = true) {
  1239. try {
  1240. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1241. const list = await res.json();
  1242. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1243. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1244. const badge = document.getElementById('ipsec-sas-badge');
  1245. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1246. const tbody = document.getElementById('ipsec-table-body');
  1247. const empty = document.getElementById('ipsec-empty');
  1248. if (!tbody) return;
  1249. tbody.innerHTML = '';
  1250. if (state.ipsecTunnels.length === 0) {
  1251. if (empty) empty.classList.remove('hidden');
  1252. } else {
  1253. if (empty) empty.classList.add('hidden');
  1254. state.ipsecTunnels.forEach(c => {
  1255. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1256. const tr = document.createElement('tr');
  1257. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1258. tr.innerHTML = `
  1259. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isEstablished, c.disabled)}</td>
  1260. <td class="py-2.5 px-4 font-bold text-white">${c.name}</td>
  1261. <td class="py-2.5 px-4 text-emerald-400 font-mono">${c.local_subnet || '-'}</td>
  1262. <td class="py-2.5 px-4 text-slate-300 font-mono">${c.remote_addrs || '-'}</td>
  1263. <td class="py-2.5 px-4 text-cyan-400 font-mono">${c.remote_subnet || '-'}</td>
  1264. <td class="py-2.5 px-4 font-sans">
  1265. <span class="px-2 py-0.5 rounded-full text-[10px] font-semibold ${
  1266. isEstablished ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-slate-800 text-slate-400'
  1267. }">${c.status || (isEstablished ? 'ESTABLISHED' : 'DISCONNECTED')}</span>
  1268. </td>
  1269. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  1270. ${isEstablished ? `
  1271. <button onclick="stopIPSecTunnel('${c.name}')" class="text-xs text-rose-400 hover:text-rose-300">Terminate</button>
  1272. ` : `
  1273. <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>
  1274. `}
  1275. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1276. ${c.disabled ? 'Enable' : 'Disable'}
  1277. </button>
  1278. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1279. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1280. </td>
  1281. `;
  1282. tbody.appendChild(tr);
  1283. });
  1284. }
  1285. } catch (err) {
  1286. console.error('Failed to load IPSec:', err);
  1287. }
  1288. }
  1289. function openAddIPSecModal() {
  1290. document.getElementById('ipsec-modal-title').innerText = 'Configure IPSec IKEv2 Tunnel';
  1291. document.getElementById('ipsec-modal-name').value = `ipsec-${(state.ipsecTunnels || []).length + 1}`;
  1292. document.getElementById('ipsec-modal-name').readOnly = false;
  1293. document.getElementById('ipsec-modal-localts').value = '192.168.10.0/24';
  1294. document.getElementById('ipsec-modal-remotets').value = '192.168.20.0/24';
  1295. document.getElementById('ipsec-modal-remotegw').value = '';
  1296. document.getElementById('ipsec-modal-psk').value = '';
  1297. document.getElementById('ipsec-modal-ikeprop').value = 'aes256-sha256-modp2048,default';
  1298. document.getElementById('ipsec-modal-espprop').value = 'aes256-sha256-modp2048,default';
  1299. document.getElementById('ipsec-modal-autostart').checked = true;
  1300. document.getElementById('ipsec-modal-disabled').checked = false;
  1301. document.getElementById('ipsec-modal').classList.remove('hidden');
  1302. }
  1303. function openEditIPSecModal(name) {
  1304. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  1305. if (!conn) return;
  1306. document.getElementById('ipsec-modal-title').innerText = `Edit IPSec Tunnel: ${name}`;
  1307. document.getElementById('ipsec-modal-name').value = conn.name;
  1308. document.getElementById('ipsec-modal-name').readOnly = true;
  1309. document.getElementById('ipsec-modal-localts').value = conn.local_subnet || '';
  1310. document.getElementById('ipsec-modal-remotets').value = conn.remote_subnet || '';
  1311. document.getElementById('ipsec-modal-remotegw').value = conn.remote_addrs || '';
  1312. document.getElementById('ipsec-modal-psk').value = conn.preshared_key || '';
  1313. document.getElementById('ipsec-modal-ikeprop').value = conn.ike_proposals || 'aes256-sha256-modp2048,default';
  1314. document.getElementById('ipsec-modal-espprop').value = conn.esp_proposals || 'aes256-sha256-modp2048,default';
  1315. document.getElementById('ipsec-modal-autostart').checked = conn.auto_start ?? true;
  1316. document.getElementById('ipsec-modal-disabled').checked = !!conn.disabled;
  1317. document.getElementById('ipsec-modal').classList.remove('hidden');
  1318. }
  1319. function closeAddIPSecModal() {
  1320. document.getElementById('ipsec-modal').classList.add('hidden');
  1321. }
  1322. async function submitSaveIPSec(e) {
  1323. e.preventDefault();
  1324. const name = document.getElementById('ipsec-modal-name').value.trim();
  1325. const localts = document.getElementById('ipsec-modal-localts').value.trim();
  1326. const remotets = document.getElementById('ipsec-modal-remotets').value.trim();
  1327. const remotegw = document.getElementById('ipsec-modal-remotegw').value.trim();
  1328. const psk = document.getElementById('ipsec-modal-psk').value;
  1329. const ike = document.getElementById('ipsec-modal-ikeprop').value.trim();
  1330. const esp = document.getElementById('ipsec-modal-espprop').value.trim();
  1331. const autostart = document.getElementById('ipsec-modal-autostart').checked;
  1332. const disabled = document.getElementById('ipsec-modal-disabled').checked;
  1333. try {
  1334. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  1335. method: 'POST',
  1336. headers: { 'Content-Type': 'application/json' },
  1337. body: JSON.stringify({
  1338. name,
  1339. local_addrs: '%any',
  1340. remote_addrs: remotegw,
  1341. local_subnet: localts,
  1342. remote_subnet: remotets,
  1343. preshared_key: psk,
  1344. ike_proposals: ike,
  1345. esp_proposals: esp,
  1346. auto_start: autostart,
  1347. disabled
  1348. })
  1349. });
  1350. if (res.ok) {
  1351. showToast('IPSec Saved', `Tunnel ${name} configured`, 'success');
  1352. closeAddIPSecModal();
  1353. loadIPSec(false);
  1354. fetchData(false);
  1355. }
  1356. } catch (err) {
  1357. showToast('Error', err.message, 'error');
  1358. }
  1359. }
  1360. async function startIPSecTunnel(name) {
  1361. try {
  1362. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1363. if (res.ok) {
  1364. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  1365. setTimeout(() => loadIPSec(false), 2000);
  1366. }
  1367. } catch (err) {
  1368. showToast('Error', err.message, 'error');
  1369. }
  1370. }
  1371. async function stopIPSecTunnel(name) {
  1372. try {
  1373. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1374. if (res.ok) {
  1375. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  1376. loadIPSec(false);
  1377. }
  1378. } catch (err) {
  1379. showToast('Error', err.message, 'error');
  1380. }
  1381. }
  1382. async function toggleIPSecState(name, enable) {
  1383. try {
  1384. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  1385. method: 'POST',
  1386. headers: { 'Content-Type': 'application/json' },
  1387. body: JSON.stringify({ enabled: enable })
  1388. });
  1389. if (res.ok) {
  1390. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  1391. loadIPSec(false);
  1392. }
  1393. } catch (err) {
  1394. showToast('Error', err.message, 'error');
  1395. }
  1396. }
  1397. async function deleteIPSecConn(name) {
  1398. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  1399. try {
  1400. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1401. if (res.ok) {
  1402. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  1403. loadIPSec(false);
  1404. fetchData(false);
  1405. }
  1406. } catch (err) {
  1407. showToast('Error', err.message, 'error');
  1408. }
  1409. }
  1410. // ======================== L2TP Multi-Instance ========================
  1411. async function loadL2TP(populateInputs = true) {
  1412. try {
  1413. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  1414. const list = await res.json();
  1415. state.l2tpList = Array.isArray(list) ? list : [];
  1416. const badge = document.getElementById('l2tp-count-badge');
  1417. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  1418. const tbody = document.getElementById('l2tp-table-body');
  1419. const empty = document.getElementById('l2tp-empty');
  1420. if (!tbody) return;
  1421. tbody.innerHTML = '';
  1422. if (state.l2tpList.length === 0) {
  1423. if (empty) empty.classList.remove('hidden');
  1424. } else {
  1425. if (empty) empty.classList.add('hidden');
  1426. state.l2tpList.forEach(inst => {
  1427. const tr = document.createElement('tr');
  1428. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1429. tr.innerHTML = `
  1430. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1431. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1432. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.connect_to}</td>
  1433. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1434. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1435. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1436. <td class="py-2.5 px-3 text-center">
  1437. <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'}">
  1438. ${inst.default_route ? 'Yes' : 'No'}
  1439. </span>
  1440. </td>
  1441. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1442. ${inst.running ? `
  1443. <button onclick="disconnectL2TPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1444. ` : `
  1445. <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>
  1446. `}
  1447. <button onclick="toggleL2TPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1448. ${inst.disabled ? 'Enable' : 'Disable'}
  1449. </button>
  1450. <button onclick="openEditL2TPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1451. <button onclick="deleteL2TPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1452. </td>
  1453. `;
  1454. tbody.appendChild(tr);
  1455. });
  1456. }
  1457. } catch (err) {
  1458. console.error('Failed to load L2TP:', err);
  1459. }
  1460. }
  1461. function openAddL2TPModal() {
  1462. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  1463. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  1464. document.getElementById('l2tp-modal-name').readOnly = false;
  1465. document.getElementById('l2tp-modal-server').value = '';
  1466. document.getElementById('l2tp-modal-user').value = '';
  1467. document.getElementById('l2tp-modal-pass').value = '';
  1468. document.getElementById('l2tp-modal-ipsec').value = '';
  1469. document.getElementById('l2tp-modal-defroute').checked = true;
  1470. document.getElementById('l2tp-modal-disabled').checked = false;
  1471. document.getElementById('l2tp-modal').classList.remove('hidden');
  1472. }
  1473. function openEditL2TPModal(name) {
  1474. const inst = (state.l2tpList || []).find(i => i.name === name);
  1475. if (!inst) return;
  1476. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  1477. document.getElementById('l2tp-modal-name').value = inst.name;
  1478. document.getElementById('l2tp-modal-name').readOnly = true;
  1479. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  1480. document.getElementById('l2tp-modal-user').value = inst.username || '';
  1481. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  1482. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  1483. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  1484. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  1485. document.getElementById('l2tp-modal').classList.remove('hidden');
  1486. }
  1487. function closeL2TPModal() {
  1488. document.getElementById('l2tp-modal').classList.add('hidden');
  1489. }
  1490. async function submitSaveL2TP(e) {
  1491. e.preventDefault();
  1492. const name = document.getElementById('l2tp-modal-name').value.trim();
  1493. const server = document.getElementById('l2tp-modal-server').value.trim();
  1494. const user = document.getElementById('l2tp-modal-user').value.trim();
  1495. const pass = document.getElementById('l2tp-modal-pass').value;
  1496. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  1497. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  1498. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  1499. try {
  1500. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  1501. method: 'POST',
  1502. headers: { 'Content-Type': 'application/json' },
  1503. body: JSON.stringify({
  1504. name,
  1505. connect_to: server,
  1506. username: user,
  1507. password: pass,
  1508. ipsec_secret: ipsec,
  1509. default_route: defRoute,
  1510. disabled
  1511. })
  1512. });
  1513. if (res.ok) {
  1514. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  1515. closeL2TPModal();
  1516. loadL2TP(false);
  1517. fetchData(false);
  1518. }
  1519. } catch (err) {
  1520. showToast('Error', err.message, 'error');
  1521. }
  1522. }
  1523. async function connectL2TPInstance(name) {
  1524. try {
  1525. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1526. if (res.ok) {
  1527. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  1528. setTimeout(() => loadL2TP(false), 2000);
  1529. }
  1530. } catch (err) {
  1531. showToast('Error', err.message, 'error');
  1532. }
  1533. }
  1534. async function disconnectL2TPInstance(name) {
  1535. try {
  1536. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1537. if (res.ok) {
  1538. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  1539. loadL2TP(false);
  1540. }
  1541. } catch (err) {
  1542. showToast('Error', err.message, 'error');
  1543. }
  1544. }
  1545. async function toggleL2TPState(name, enable) {
  1546. try {
  1547. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  1548. method: 'POST',
  1549. headers: { 'Content-Type': 'application/json' },
  1550. body: JSON.stringify({ enabled: enable })
  1551. });
  1552. if (res.ok) {
  1553. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1554. loadL2TP(false);
  1555. }
  1556. } catch (err) {
  1557. showToast('Error', err.message, 'error');
  1558. }
  1559. }
  1560. async function deleteL2TPInstance(name) {
  1561. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  1562. try {
  1563. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1564. if (res.ok) {
  1565. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  1566. loadL2TP(false);
  1567. fetchData(false);
  1568. }
  1569. } catch (err) {
  1570. showToast('Error', err.message, 'error');
  1571. }
  1572. }
  1573. // ======================== PPTP Multi-Instance ========================
  1574. async function loadPPTP(populateInputs = true) {
  1575. try {
  1576. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  1577. const list = await res.json();
  1578. state.pptpList = Array.isArray(list) ? list : [];
  1579. const badge = document.getElementById('pptp-count-badge');
  1580. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  1581. const tbody = document.getElementById('pptp-table-body');
  1582. const empty = document.getElementById('pptp-empty');
  1583. if (!tbody) return;
  1584. tbody.innerHTML = '';
  1585. if (state.pptpList.length === 0) {
  1586. if (empty) empty.classList.remove('hidden');
  1587. } else {
  1588. if (empty) empty.classList.add('hidden');
  1589. state.pptpList.forEach(inst => {
  1590. const tr = document.createElement('tr');
  1591. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1592. tr.innerHTML = `
  1593. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1594. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1595. <td class="py-2.5 px-3 text-purple-400 font-mono">${inst.connect_to}</td>
  1596. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1597. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1598. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1599. <td class="py-2.5 px-3 text-center">
  1600. <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'}">
  1601. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  1602. </span>
  1603. </td>
  1604. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1605. ${inst.running ? `
  1606. <button onclick="disconnectPPTPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1607. ` : `
  1608. <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>
  1609. `}
  1610. <button onclick="togglePPTPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1611. ${inst.disabled ? 'Enable' : 'Disable'}
  1612. </button>
  1613. <button onclick="openEditPPTPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1614. <button onclick="deletePPTPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1615. </td>
  1616. `;
  1617. tbody.appendChild(tr);
  1618. });
  1619. }
  1620. } catch (err) {
  1621. console.error('Failed to load PPTP:', err);
  1622. }
  1623. }
  1624. function openAddPPTPModal() {
  1625. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  1626. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  1627. document.getElementById('pptp-modal-name').readOnly = false;
  1628. document.getElementById('pptp-modal-server').value = '';
  1629. document.getElementById('pptp-modal-user').value = '';
  1630. document.getElementById('pptp-modal-pass').value = '';
  1631. document.getElementById('pptp-modal-mppe').checked = true;
  1632. document.getElementById('pptp-modal-defroute').checked = true;
  1633. document.getElementById('pptp-modal-disabled').checked = false;
  1634. document.getElementById('pptp-modal').classList.remove('hidden');
  1635. }
  1636. function openEditPPTPModal(name) {
  1637. const inst = (state.pptpList || []).find(i => i.name === name);
  1638. if (!inst) return;
  1639. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  1640. document.getElementById('pptp-modal-name').value = inst.name;
  1641. document.getElementById('pptp-modal-name').readOnly = true;
  1642. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  1643. document.getElementById('pptp-modal-user').value = inst.username || '';
  1644. document.getElementById('pptp-modal-pass').value = inst.password || '';
  1645. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  1646. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  1647. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  1648. document.getElementById('pptp-modal').classList.remove('hidden');
  1649. }
  1650. function closePPTPModal() {
  1651. document.getElementById('pptp-modal').classList.add('hidden');
  1652. }
  1653. async function submitSavePPTP(e) {
  1654. e.preventDefault();
  1655. const name = document.getElementById('pptp-modal-name').value.trim();
  1656. const server = document.getElementById('pptp-modal-server').value.trim();
  1657. const user = document.getElementById('pptp-modal-user').value.trim();
  1658. const pass = document.getElementById('pptp-modal-pass').value;
  1659. const mppe = document.getElementById('pptp-modal-mppe').checked;
  1660. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  1661. const disabled = document.getElementById('pptp-modal-disabled').checked;
  1662. try {
  1663. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  1664. method: 'POST',
  1665. headers: { 'Content-Type': 'application/json' },
  1666. body: JSON.stringify({
  1667. name,
  1668. connect_to: server,
  1669. username: user,
  1670. password: pass,
  1671. require_mppe: mppe,
  1672. default_route: defRoute,
  1673. auto_reconnect: true,
  1674. disabled
  1675. })
  1676. });
  1677. if (res.ok) {
  1678. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  1679. closePPTPModal();
  1680. loadPPTP(false);
  1681. fetchData(false);
  1682. }
  1683. } catch (err) {
  1684. showToast('Error', err.message, 'error');
  1685. }
  1686. }
  1687. async function connectPPTPInstance(name) {
  1688. try {
  1689. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1690. if (res.ok) {
  1691. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  1692. setTimeout(() => loadPPTP(false), 2000);
  1693. }
  1694. } catch (err) {
  1695. showToast('Error', err.message, 'error');
  1696. }
  1697. }
  1698. async function disconnectPPTPInstance(name) {
  1699. try {
  1700. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1701. if (res.ok) {
  1702. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  1703. loadPPTP(false);
  1704. }
  1705. } catch (err) {
  1706. showToast('Error', err.message, 'error');
  1707. }
  1708. }
  1709. async function togglePPTPState(name, enable) {
  1710. try {
  1711. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  1712. method: 'POST',
  1713. headers: { 'Content-Type': 'application/json' },
  1714. body: JSON.stringify({ enabled: enable })
  1715. });
  1716. if (res.ok) {
  1717. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1718. loadPPTP(false);
  1719. }
  1720. } catch (err) {
  1721. showToast('Error', err.message, 'error');
  1722. }
  1723. }
  1724. async function deletePPTPInstance(name) {
  1725. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  1726. try {
  1727. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1728. if (res.ok) {
  1729. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  1730. loadPPTP(false);
  1731. fetchData(false);
  1732. }
  1733. } catch (err) {
  1734. showToast('Error', err.message, 'error');
  1735. }
  1736. }
  1737. // ---------------- Modal & Helper Functions ----------------
  1738. function openVlanModal(defaultParent = '') {
  1739. const select = document.getElementById('vlan-parent');
  1740. select.innerHTML = '';
  1741. const allIfaces = state.interfaces || [];
  1742. const eligible = allIfaces.filter(i => !i.is_vlan && i.name !== 'lo');
  1743. if (eligible.length === 0) {
  1744. allIfaces.forEach(i => eligible.push(i));
  1745. }
  1746. eligible.forEach(i => {
  1747. const opt = document.createElement('option');
  1748. opt.value = i.name;
  1749. opt.innerText = `${i.name} (${i.role || 'Interface'} - ${i.state})`;
  1750. if (i.name === defaultParent) opt.selected = true;
  1751. select.appendChild(opt);
  1752. });
  1753. document.getElementById('vlan-id').value = '';
  1754. document.getElementById('vlan-name').value = '';
  1755. document.getElementById('vlan-ip').value = '';
  1756. document.getElementById('vlan-desc').value = '';
  1757. autoSuggestVlanName();
  1758. document.getElementById('vlan-modal').classList.remove('hidden');
  1759. }
  1760. function closeVlanModal() {
  1761. document.getElementById('vlan-modal').classList.add('hidden');
  1762. }
  1763. function autoSuggestVlanName() {
  1764. const parent = document.getElementById('vlan-parent').value;
  1765. const id = document.getElementById('vlan-id').value;
  1766. const nameInput = document.getElementById('vlan-name');
  1767. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  1768. }
  1769. function setSubnetPreset(cidr) {
  1770. const ipInput = document.getElementById('vlan-ip');
  1771. const id = document.getElementById('vlan-id').value || '10';
  1772. ipInput.value = `192.168.${id}.1${cidr}`;
  1773. }
  1774. async function submitCreateVlan(e) {
  1775. e.preventDefault();
  1776. const btn = document.getElementById('vlan-submit-btn');
  1777. btn.disabled = true;
  1778. btn.innerText = 'Creating...';
  1779. const parent = document.getElementById('vlan-parent').value;
  1780. const id = parseInt(document.getElementById('vlan-id').value, 10);
  1781. const name = document.getElementById('vlan-name').value.trim();
  1782. const ip = document.getElementById('vlan-ip').value.trim();
  1783. const role = document.getElementById('vlan-role').value;
  1784. const desc = document.getElementById('vlan-desc').value.trim();
  1785. try {
  1786. const res = await fetch(`${API_BASE}/vlans`, {
  1787. method: 'POST',
  1788. headers: { 'Content-Type': 'application/json' },
  1789. body: JSON.stringify({
  1790. parent_name: parent,
  1791. vlan_id: id,
  1792. name: name,
  1793. ip_address: ip,
  1794. role: role,
  1795. description: desc,
  1796. mtu: 1500,
  1797. auto_up: true
  1798. })
  1799. });
  1800. const data = await res.json();
  1801. if (res.ok) {
  1802. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  1803. state.expandedParents.add(parent);
  1804. closeVlanModal();
  1805. await fetchData(true);
  1806. if (state.activeTab !== 'interfaces') navigate('interfaces');
  1807. } else {
  1808. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  1809. }
  1810. } catch (err) {
  1811. showToast('Error', err.message, 'error');
  1812. } finally {
  1813. btn.disabled = false;
  1814. btn.innerText = 'Create VLAN';
  1815. }
  1816. }
  1817. async function confirmDeleteVlan(name) {
  1818. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  1819. try {
  1820. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1821. if (res.ok) {
  1822. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  1823. closeIfaceModal();
  1824. fetchData(true);
  1825. }
  1826. } catch (err) {
  1827. showToast('Error', err.message, 'error');
  1828. }
  1829. }
  1830. function openIfaceModal(name) {
  1831. const iface = (state.interfaces || []).find(i => i.name === name);
  1832. if (!iface) return;
  1833. state.currentModalIface = iface.name;
  1834. document.getElementById('modal-iface-name').innerText = iface.name;
  1835. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  1836. document.getElementById('modal-iface-mtu').value = iface.mtu;
  1837. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  1838. document.getElementById('modal-iface-desc').value = iface.description || '';
  1839. const delBtn = document.getElementById('modal-delete-vlan-btn');
  1840. if (iface.is_vlan) {
  1841. delBtn.classList.remove('hidden');
  1842. } else {
  1843. delBtn.classList.add('hidden');
  1844. }
  1845. renderModalIPs(iface);
  1846. document.getElementById('iface-modal').classList.remove('hidden');
  1847. }
  1848. function renderModalIPs(iface) {
  1849. const container = document.getElementById('modal-ip-list');
  1850. container.innerHTML = '';
  1851. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  1852. if (addrs.length === 0) {
  1853. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  1854. return;
  1855. }
  1856. addrs.forEach(addr => {
  1857. const row = document.createElement('div');
  1858. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  1859. row.innerHTML = `
  1860. <span class="text-white">${addr}</span>
  1861. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  1862. `;
  1863. container.appendChild(row);
  1864. });
  1865. }
  1866. function closeIfaceModal() {
  1867. document.getElementById('iface-modal').classList.add('hidden');
  1868. state.currentModalIface = null;
  1869. }
  1870. async function setIfaceState(name, newState) {
  1871. await toggleInterfaceState(name, newState);
  1872. const updated = (state.interfaces || []).find(i => i.name === name);
  1873. if (updated) openIfaceModal(name);
  1874. }
  1875. async function applyMTU() {
  1876. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  1877. try {
  1878. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  1879. method: 'POST',
  1880. headers: { 'Content-Type': 'application/json' },
  1881. body: JSON.stringify({ mtu })
  1882. });
  1883. if (res.ok) {
  1884. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  1885. fetchData(false);
  1886. }
  1887. } catch (err) {
  1888. showToast('Error', err.message, 'error');
  1889. }
  1890. }
  1891. async function addInterfaceIP() {
  1892. const ip = document.getElementById('modal-new-ip').value.trim();
  1893. if (!ip) return;
  1894. try {
  1895. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  1896. method: 'POST',
  1897. headers: { 'Content-Type': 'application/json' },
  1898. body: JSON.stringify({ ip })
  1899. });
  1900. if (res.ok) {
  1901. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  1902. document.getElementById('modal-new-ip').value = '';
  1903. await fetchData(false);
  1904. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  1905. if (iface) renderModalIPs(iface);
  1906. } else {
  1907. const err = await res.json();
  1908. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  1909. }
  1910. } catch (err) {
  1911. showToast('Error', err.message, 'error');
  1912. }
  1913. }
  1914. async function removeInterfaceIP(ip) {
  1915. if (!confirm(`Remove IP ${ip}?`)) return;
  1916. try {
  1917. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  1918. method: 'DELETE',
  1919. headers: { 'Content-Type': 'application/json' },
  1920. body: JSON.stringify({ ip })
  1921. });
  1922. if (res.ok) {
  1923. showToast('IP Removed', `Removed ${ip}`, 'success');
  1924. await fetchData(false);
  1925. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  1926. if (iface) renderModalIPs(iface);
  1927. }
  1928. } catch (err) {
  1929. showToast('Error', err.message, 'error');
  1930. }
  1931. }
  1932. async function saveInterfaceMetadata() {
  1933. const role = document.getElementById('modal-iface-role').value;
  1934. const desc = document.getElementById('modal-iface-desc').value.trim();
  1935. try {
  1936. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/metadata`, {
  1937. method: 'POST',
  1938. headers: { 'Content-Type': 'application/json' },
  1939. body: JSON.stringify({ role, description: desc })
  1940. });
  1941. if (res.ok) {
  1942. showToast('Saved', 'Metadata updated', 'success');
  1943. closeIfaceModal();
  1944. fetchData(false);
  1945. }
  1946. } catch (err) {
  1947. showToast('Error', err.message, 'error');
  1948. }
  1949. }
  1950. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  1951. state.fwSubTab = 'filter';
  1952. state.routesSubTab = 'routes';
  1953. function renderRuleFlag(disabled, hasComment) {
  1954. let flags = '';
  1955. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  1956. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  1957. return flags || '<span class="text-slate-600">-</span>';
  1958. }
  1959. function renderActionBadge(action) {
  1960. const act = (action || '').toLowerCase();
  1961. let color = 'bg-slate-800 text-slate-300';
  1962. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  1963. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  1964. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  1965. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  1966. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  1967. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  1968. }
  1969. function switchFWSubTab(tab) {
  1970. state.fwSubTab = tab;
  1971. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  1972. tabs.forEach(t => {
  1973. const panel = document.getElementById(`fw-subtab-${t}`);
  1974. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  1975. if (panel) {
  1976. if (t === tab) panel.classList.remove('hidden');
  1977. else panel.classList.add('hidden');
  1978. }
  1979. if (btn) {
  1980. if (t === tab) {
  1981. 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';
  1982. } else {
  1983. 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';
  1984. }
  1985. }
  1986. });
  1987. const addBtn = document.getElementById('fw-primary-add-btn');
  1988. if (addBtn) {
  1989. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  1990. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  1991. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  1992. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  1993. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  1994. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  1995. }
  1996. if (tab === 'geo') loadGeoIP();
  1997. if (tab === 'connections') loadConnections();
  1998. }
  1999. function openCurrentFWModal() {
  2000. if (state.fwSubTab === 'filter') openAddFilterModal();
  2001. else if (state.fwSubTab === 'nat') openAddNATModal();
  2002. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  2003. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  2004. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  2005. else if (state.fwSubTab === 'connections') loadConnections();
  2006. }
  2007. async function loadFirewall(populateDropdowns = true) {
  2008. try {
  2009. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  2010. fetch(`${API_BASE}/firewall/summary`),
  2011. fetch(`${API_BASE}/firewall/filter`),
  2012. fetch(`${API_BASE}/firewall/nat`),
  2013. fetch(`${API_BASE}/firewall/mangle`),
  2014. fetch(`${API_BASE}/firewall/address-lists`),
  2015. fetch(`${API_BASE}/firewall/geoip/status`),
  2016. fetch(`${API_BASE}/firewall/geoip/countries`)
  2017. ]);
  2018. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  2019. if (filterRes.ok) state.filterRules = await filterRes.json();
  2020. if (natRes.ok) state.natRules = await natRes.json();
  2021. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  2022. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  2023. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  2024. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  2025. // Badges
  2026. const bFilter = document.getElementById('fw-badge-filter');
  2027. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  2028. const bNat = document.getElementById('fw-badge-nat');
  2029. if (bNat) bNat.innerText = (state.natRules || []).length;
  2030. const bMangle = document.getElementById('fw-badge-mangle');
  2031. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  2032. const bAddr = document.getElementById('fw-badge-addrlist');
  2033. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  2034. const bGeo = document.getElementById('fw-badge-geo');
  2035. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  2036. renderFilterRules();
  2037. renderNATRules();
  2038. renderMangleRules();
  2039. renderAddressLists();
  2040. renderGeoCountries();
  2041. if (state.fwSubTab === 'connections') {
  2042. loadConnections();
  2043. }
  2044. } catch (err) {
  2045. console.error('Failed to load firewall:', err);
  2046. }
  2047. }
  2048. // ----------------- Filter Rules -----------------
  2049. function renderFilterRules() {
  2050. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  2051. const tbody = document.getElementById('filter-table-body');
  2052. const empty = document.getElementById('filter-empty');
  2053. if (!tbody) return;
  2054. tbody.innerHTML = '';
  2055. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2056. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2057. if (rules.length === 0) {
  2058. empty?.classList.remove('hidden');
  2059. return;
  2060. }
  2061. empty?.classList.add('hidden');
  2062. rules.forEach((r, idx) => {
  2063. const tr = document.createElement('tr');
  2064. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2065. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2066. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2067. tr.innerHTML = `
  2068. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2069. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2070. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2071. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2072. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2073. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2074. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2075. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2076. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2077. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2078. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2079. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2080. </td>
  2081. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2082. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2083. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2084. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2085. <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>
  2086. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2087. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2088. </td>
  2089. `;
  2090. tbody.appendChild(tr);
  2091. });
  2092. }
  2093. function formatTarget(addr, list, geo) {
  2094. const parts = [];
  2095. if (addr) parts.push(`<span>${addr}</span>`);
  2096. if (list) {
  2097. const inv = list.startsWith('!') ? '!' : '';
  2098. const clean = list.replace(/^!/, '');
  2099. 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>`);
  2100. }
  2101. if (geo) {
  2102. const inv = geo.startsWith('!') ? '!' : '';
  2103. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  2104. 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>`);
  2105. }
  2106. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  2107. return parts.join(' ');
  2108. }
  2109. function populateInterfaceSelect(selectId, currentVal = '') {
  2110. const sel = document.getElementById(selectId);
  2111. if (!sel) return;
  2112. sel.innerHTML = '<option value="">(Any Interface)</option>';
  2113. (state.interfaces || []).forEach(i => {
  2114. const opt = document.createElement('option');
  2115. opt.value = i.name;
  2116. opt.innerText = `${i.name} (${i.role || i.type})`;
  2117. if (i.name === currentVal) opt.selected = true;
  2118. sel.appendChild(opt);
  2119. });
  2120. }
  2121. function populateAddressListSelect(selectId, currentVal = '') {
  2122. const sel = document.getElementById(selectId);
  2123. if (!sel) return;
  2124. sel.innerHTML = '<option value="">(None)</option>';
  2125. const cleanVal = (currentVal || '').replace(/^!/, '');
  2126. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  2127. customNames.forEach(name => {
  2128. const count = (state.addressLists || []).filter(a => a.name === name).length;
  2129. const opt = document.createElement('option');
  2130. opt.value = name;
  2131. opt.innerText = `${name} (${count} entries)`;
  2132. if (name === cleanVal) opt.selected = true;
  2133. sel.appendChild(opt);
  2134. });
  2135. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  2136. const opt = document.createElement('option');
  2137. opt.value = cleanVal;
  2138. opt.innerText = cleanVal;
  2139. opt.selected = true;
  2140. sel.appendChild(opt);
  2141. }
  2142. }
  2143. function populateGeoIPSelect(selectId, currentVal = '') {
  2144. const sel = document.getElementById(selectId);
  2145. if (!sel) return;
  2146. sel.innerHTML = '<option value="">(None)</option>';
  2147. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  2148. // Presets optgroup
  2149. const grpPresets = document.createElement('optgroup');
  2150. grpPresets.label = '⚡ Regional Presets';
  2151. const presets = [
  2152. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  2153. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  2154. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  2155. ];
  2156. presets.forEach(p => {
  2157. const opt = document.createElement('option');
  2158. opt.value = p.code;
  2159. opt.innerText = p.label;
  2160. if (p.code === cleanVal) opt.selected = true;
  2161. grpPresets.appendChild(opt);
  2162. });
  2163. sel.appendChild(grpPresets);
  2164. // All Countries optgroup
  2165. const grpCountries = document.createElement('optgroup');
  2166. grpCountries.label = '🌍 All Countries';
  2167. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  2168. countries.forEach(c => {
  2169. const opt = document.createElement('option');
  2170. opt.value = c.code;
  2171. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  2172. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  2173. if (c.code === cleanVal) opt.selected = true;
  2174. grpCountries.appendChild(opt);
  2175. });
  2176. sel.appendChild(grpCountries);
  2177. }
  2178. function openAddFilterModal() {
  2179. document.getElementById('filter-modal-title').innerText = 'Add Firewall Filter Rule';
  2180. document.getElementById('filter-modal-id').value = '';
  2181. document.getElementById('filter-modal-chain').value = 'forward';
  2182. document.getElementById('filter-modal-action').value = 'accept';
  2183. document.getElementById('filter-modal-proto').value = 'all';
  2184. document.getElementById('filter-modal-src').value = '';
  2185. document.getElementById('filter-modal-dst').value = '';
  2186. document.getElementById('filter-modal-sport').value = '';
  2187. document.getElementById('filter-modal-dport').value = '';
  2188. document.getElementById('filter-modal-connmark').value = '';
  2189. document.getElementById('filter-modal-comment').value = '';
  2190. document.getElementById('filter-modal-disabled').checked = false;
  2191. document.getElementById('filter-modal-cs-established').checked = false;
  2192. document.getElementById('filter-modal-cs-related').checked = false;
  2193. document.getElementById('filter-modal-cs-new').checked = false;
  2194. document.getElementById('filter-modal-cs-invalid').checked = false;
  2195. populateInterfaceSelect('filter-modal-iniface');
  2196. populateInterfaceSelect('filter-modal-outiface');
  2197. if (document.getElementById('filter-modal-srclist-inv')) document.getElementById('filter-modal-srclist-inv').checked = false;
  2198. if (document.getElementById('filter-modal-dstlist-inv')) document.getElementById('filter-modal-dstlist-inv').checked = false;
  2199. populateAddressListSelect('filter-modal-srclist');
  2200. populateAddressListSelect('filter-modal-dstlist');
  2201. if (document.getElementById('filter-modal-srcgeoip-inv')) document.getElementById('filter-modal-srcgeoip-inv').checked = false;
  2202. if (document.getElementById('filter-modal-dstgeoip-inv')) document.getElementById('filter-modal-dstgeoip-inv').checked = false;
  2203. populateGeoIPSelect('filter-modal-srcgeoip');
  2204. populateGeoIPSelect('filter-modal-dstgeoip');
  2205. toggleFilterActionFields();
  2206. document.getElementById('filter-modal').classList.remove('hidden');
  2207. }
  2208. function openEditFilterModal(id) {
  2209. const r = (state.filterRules || []).find(rule => rule.id === id);
  2210. if (!r) return;
  2211. document.getElementById('filter-modal-title').innerText = `Edit Filter Rule (#${r.order})`;
  2212. document.getElementById('filter-modal-id').value = r.id;
  2213. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  2214. document.getElementById('filter-modal-action').value = r.action || 'accept';
  2215. document.getElementById('filter-modal-proto').value = r.protocol || 'all';
  2216. document.getElementById('filter-modal-src').value = r.src_address || '';
  2217. document.getElementById('filter-modal-dst').value = r.dst_address || '';
  2218. document.getElementById('filter-modal-sport').value = r.src_port || '';
  2219. document.getElementById('filter-modal-dport').value = r.dst_port || '';
  2220. document.getElementById('filter-modal-connmark').value = r.connection_mark || '';
  2221. document.getElementById('filter-modal-comment').value = r.comment || '';
  2222. document.getElementById('filter-modal-disabled').checked = !!r.disabled;
  2223. const states = r.connection_state || [];
  2224. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  2225. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  2226. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  2227. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  2228. populateInterfaceSelect('filter-modal-iniface', r.in_interface);
  2229. populateInterfaceSelect('filter-modal-outiface', r.out_interface);
  2230. const srcInv = (r.src_address_list || '').startsWith('!');
  2231. const dstInv = (r.dst_address_list || '').startsWith('!');
  2232. if (document.getElementById('filter-modal-srclist-inv')) document.getElementById('filter-modal-srclist-inv').checked = srcInv;
  2233. if (document.getElementById('filter-modal-dstlist-inv')) document.getElementById('filter-modal-dstlist-inv').checked = dstInv;
  2234. populateAddressListSelect('filter-modal-srclist', r.src_address_list || '');
  2235. populateAddressListSelect('filter-modal-dstlist', r.dst_address_list || '');
  2236. const srcGeoInv = (r.src_geoip || '').startsWith('!');
  2237. const dstGeoInv = (r.dst_geoip || '').startsWith('!');
  2238. if (document.getElementById('filter-modal-srcgeoip-inv')) document.getElementById('filter-modal-srcgeoip-inv').checked = srcGeoInv;
  2239. if (document.getElementById('filter-modal-dstgeoip-inv')) document.getElementById('filter-modal-dstgeoip-inv').checked = dstGeoInv;
  2240. populateGeoIPSelect('filter-modal-srcgeoip', r.src_geoip || '');
  2241. populateGeoIPSelect('filter-modal-dstgeoip', r.dst_geoip || '');
  2242. toggleFilterActionFields();
  2243. document.getElementById('filter-modal').classList.remove('hidden');
  2244. }
  2245. function closeFilterModal() {
  2246. document.getElementById('filter-modal').classList.add('hidden');
  2247. }
  2248. function toggleFilterActionFields() {
  2249. const act = document.getElementById('filter-modal-action').value;
  2250. const rejectBox = document.getElementById('filter-action-reject-box');
  2251. if (rejectBox) {
  2252. if (act === 'reject') rejectBox.classList.remove('hidden');
  2253. else rejectBox.classList.add('hidden');
  2254. }
  2255. }
  2256. async function submitSaveFilterRule(e) {
  2257. e.preventDefault();
  2258. const id = document.getElementById('filter-modal-id').value;
  2259. const chain = document.getElementById('filter-modal-chain').value;
  2260. const action = document.getElementById('filter-modal-action').value;
  2261. const proto = document.getElementById('filter-modal-proto').value;
  2262. const src = document.getElementById('filter-modal-src').value.trim();
  2263. const dst = document.getElementById('filter-modal-dst').value.trim();
  2264. const sport = document.getElementById('filter-modal-sport').value.trim();
  2265. const dport = document.getElementById('filter-modal-dport').value.trim();
  2266. const inIface = document.getElementById('filter-modal-iniface').value;
  2267. const outIface = document.getElementById('filter-modal-outiface').value;
  2268. const connmark = document.getElementById('filter-modal-connmark').value.trim();
  2269. let srclist = document.getElementById('filter-modal-srclist')?.value || '';
  2270. if (srclist && document.getElementById('filter-modal-srclist-inv')?.checked) {
  2271. srclist = '!' + srclist.replace(/^!/, '');
  2272. }
  2273. let dstlist = document.getElementById('filter-modal-dstlist')?.value || '';
  2274. if (dstlist && document.getElementById('filter-modal-dstlist-inv')?.checked) {
  2275. dstlist = '!' + dstlist.replace(/^!/, '');
  2276. }
  2277. let srcgeoip = document.getElementById('filter-modal-srcgeoip')?.value || '';
  2278. if (srcgeoip && document.getElementById('filter-modal-srcgeoip-inv')?.checked) {
  2279. srcgeoip = '!' + srcgeoip.replace(/^!/, '');
  2280. }
  2281. let dstgeoip = document.getElementById('filter-modal-dstgeoip')?.value || '';
  2282. if (dstgeoip && document.getElementById('filter-modal-dstgeoip-inv')?.checked) {
  2283. dstgeoip = '!' + dstgeoip.replace(/^!/, '');
  2284. }
  2285. const comment = document.getElementById('filter-modal-comment').value.trim();
  2286. const disabled = document.getElementById('filter-modal-disabled').checked;
  2287. const rejectWith = document.getElementById('filter-modal-rejectwith')?.value || '';
  2288. const states = [];
  2289. if (document.getElementById('filter-modal-cs-established').checked) states.push('established');
  2290. if (document.getElementById('filter-modal-cs-related').checked) states.push('related');
  2291. if (document.getElementById('filter-modal-cs-new').checked) states.push('new');
  2292. if (document.getElementById('filter-modal-cs-invalid').checked) states.push('invalid');
  2293. try {
  2294. const res = await fetch(`${API_BASE}/firewall/filter`, {
  2295. method: 'POST',
  2296. headers: { 'Content-Type': 'application/json' },
  2297. body: JSON.stringify({
  2298. id,
  2299. chain,
  2300. action,
  2301. reject_with: rejectWith,
  2302. protocol: proto,
  2303. src_address: src,
  2304. dst_address: dst,
  2305. src_port: sport,
  2306. dst_port: dport,
  2307. in_interface: inIface,
  2308. out_interface: outIface,
  2309. connection_state: states,
  2310. connection_mark: connmark,
  2311. src_address_list: srclist,
  2312. dst_address_list: dstlist,
  2313. src_geoip: srcgeoip,
  2314. dst_geoip: dstgeoip,
  2315. comment,
  2316. disabled
  2317. })
  2318. });
  2319. if (res.ok) {
  2320. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  2321. closeFilterModal();
  2322. loadFirewall(false);
  2323. } else {
  2324. const err = await res.json();
  2325. showToast('Error', err.message, 'error');
  2326. }
  2327. } catch (err) {
  2328. showToast('Error', err.message, 'error');
  2329. }
  2330. }
  2331. async function moveFilterRule(id, dir) {
  2332. try {
  2333. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  2334. method: 'POST',
  2335. headers: { 'Content-Type': 'application/json' },
  2336. body: JSON.stringify({ direction: dir })
  2337. });
  2338. if (res.ok) loadFirewall(false);
  2339. } catch (err) {
  2340. showToast('Error', err.message, 'error');
  2341. }
  2342. }
  2343. async function toggleFilterRuleState(id, disabled) {
  2344. try {
  2345. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  2346. method: 'POST',
  2347. headers: { 'Content-Type': 'application/json' },
  2348. body: JSON.stringify({ disabled })
  2349. });
  2350. if (res.ok) loadFirewall(false);
  2351. } catch (err) {
  2352. showToast('Error', err.message, 'error');
  2353. }
  2354. }
  2355. async function deleteFilterRule(id) {
  2356. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  2357. try {
  2358. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2359. if (res.ok) {
  2360. showToast('Deleted', 'Filter rule removed', 'success');
  2361. loadFirewall(false);
  2362. }
  2363. } catch (err) {
  2364. showToast('Error', err.message, 'error');
  2365. }
  2366. }
  2367. // ----------------- NAT Rules -----------------
  2368. function renderNATRules() {
  2369. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  2370. const tbody = document.getElementById('nat-table-body');
  2371. const empty = document.getElementById('nat-empty');
  2372. if (!tbody) return;
  2373. tbody.innerHTML = '';
  2374. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2375. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  2376. if (rules.length === 0) {
  2377. empty?.classList.remove('hidden');
  2378. return;
  2379. }
  2380. empty?.classList.add('hidden');
  2381. rules.forEach((r, idx) => {
  2382. const tr = document.createElement('tr');
  2383. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2384. const toTarget = [r.to_addresses, r.to_ports].filter(Boolean).join(':');
  2385. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  2386. tr.innerHTML = `
  2387. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2388. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2389. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  2390. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2391. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2392. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  2393. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2394. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2395. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${toTarget || '-'}</td>
  2396. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2397. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2398. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2399. </td>
  2400. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2401. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2402. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2403. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2404. <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>
  2405. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2406. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2407. </td>
  2408. `;
  2409. tbody.appendChild(tr);
  2410. });
  2411. }
  2412. function openAddNATModal() {
  2413. document.getElementById('nat-modal-title').innerText = 'Add NAT Rule';
  2414. document.getElementById('nat-modal-id').value = '';
  2415. document.getElementById('nat-modal-chain').value = 'srcnat';
  2416. document.getElementById('nat-modal-action').value = 'masquerade';
  2417. document.getElementById('nat-modal-toaddr').value = '';
  2418. document.getElementById('nat-modal-toport').value = '';
  2419. document.getElementById('nat-modal-proto').value = 'all';
  2420. document.getElementById('nat-modal-src').value = '';
  2421. document.getElementById('nat-modal-dst').value = '';
  2422. document.getElementById('nat-modal-dport').value = '';
  2423. document.getElementById('nat-modal-comment').value = '';
  2424. document.getElementById('nat-modal-disabled').checked = false;
  2425. populateInterfaceSelect('nat-modal-iniface');
  2426. populateInterfaceSelect('nat-modal-outiface');
  2427. populateAddressListSelect('nat-modal-srclist');
  2428. populateAddressListSelect('nat-modal-dstlist');
  2429. const srcInvEl = document.getElementById('nat-modal-srclist-inv');
  2430. if (srcInvEl) srcInvEl.checked = false;
  2431. const dstInvEl = document.getElementById('nat-modal-dstlist-inv');
  2432. if (dstInvEl) dstInvEl.checked = false;
  2433. populateGeoIPSelect('nat-modal-srcgeoip');
  2434. populateGeoIPSelect('nat-modal-dstgeoip');
  2435. const srcGeoInvEl = document.getElementById('nat-modal-srcgeoip-inv');
  2436. if (srcGeoInvEl) srcGeoInvEl.checked = false;
  2437. const dstGeoInvEl = document.getElementById('nat-modal-dstgeoip-inv');
  2438. if (dstGeoInvEl) dstGeoInvEl.checked = false;
  2439. toggleNATActionFields();
  2440. document.getElementById('nat-modal').classList.remove('hidden');
  2441. }
  2442. function openEditNATModal(id) {
  2443. const r = (state.natRules || []).find(rule => rule.id === id);
  2444. if (!r) return;
  2445. document.getElementById('nat-modal-title').innerText = `Edit NAT Rule (#${r.order})`;
  2446. document.getElementById('nat-modal-id').value = r.id;
  2447. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  2448. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  2449. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  2450. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  2451. document.getElementById('nat-modal-proto').value = r.protocol || 'all';
  2452. document.getElementById('nat-modal-src').value = r.src_address || '';
  2453. document.getElementById('nat-modal-dst').value = r.dst_address || '';
  2454. document.getElementById('nat-modal-dport').value = r.dst_port || '';
  2455. document.getElementById('nat-modal-comment').value = r.comment || '';
  2456. document.getElementById('nat-modal-disabled').checked = !!r.disabled;
  2457. populateInterfaceSelect('nat-modal-iniface', r.in_interface);
  2458. populateInterfaceSelect('nat-modal-outiface', r.out_interface);
  2459. const srcInv = (r.src_address_list || '').startsWith('!');
  2460. const dstInv = (r.dst_address_list || '').startsWith('!');
  2461. const srcInvEl = document.getElementById('nat-modal-srclist-inv');
  2462. if (srcInvEl) srcInvEl.checked = srcInv;
  2463. const dstInvEl = document.getElementById('nat-modal-dstlist-inv');
  2464. if (dstInvEl) dstInvEl.checked = dstInv;
  2465. populateAddressListSelect('nat-modal-srclist', r.src_address_list || '');
  2466. populateAddressListSelect('nat-modal-dstlist', r.dst_address_list || '');
  2467. const srcGeoInv = (r.src_geoip || '').startsWith('!');
  2468. const dstGeoInv = (r.dst_geoip || '').startsWith('!');
  2469. const srcGeoInvEl = document.getElementById('nat-modal-srcgeoip-inv');
  2470. if (srcGeoInvEl) srcGeoInvEl.checked = srcGeoInv;
  2471. const dstGeoInvEl = document.getElementById('nat-modal-dstgeoip-inv');
  2472. if (dstGeoInvEl) dstGeoInvEl.checked = dstGeoInv;
  2473. populateGeoIPSelect('nat-modal-srcgeoip', r.src_geoip || '');
  2474. populateGeoIPSelect('nat-modal-dstgeoip', r.dst_geoip || '');
  2475. toggleNATActionFields();
  2476. document.getElementById('nat-modal').classList.remove('hidden');
  2477. }
  2478. function closeNATModal() {
  2479. document.getElementById('nat-modal').classList.add('hidden');
  2480. }
  2481. function toggleNATChainFields() {
  2482. const ch = document.getElementById('nat-modal-chain').value;
  2483. const actSel = document.getElementById('nat-modal-action');
  2484. if (ch === 'srcnat' && actSel.value === 'dst-nat') {
  2485. actSel.value = 'masquerade';
  2486. } else if (ch === 'dstnat' && actSel.value === 'masquerade') {
  2487. actSel.value = 'dst-nat';
  2488. }
  2489. toggleNATActionFields();
  2490. }
  2491. function toggleNATActionFields() {
  2492. const act = document.getElementById('nat-modal-action').value;
  2493. const toBox = document.getElementById('nat-action-to-box');
  2494. if (toBox) {
  2495. if (act === 'masquerade' || act === 'accept') toBox.classList.add('hidden');
  2496. else toBox.classList.remove('hidden');
  2497. }
  2498. }
  2499. async function submitSaveNATRule(e) {
  2500. e.preventDefault();
  2501. const id = document.getElementById('nat-modal-id').value;
  2502. const chain = document.getElementById('nat-modal-chain').value;
  2503. const action = document.getElementById('nat-modal-action').value;
  2504. const toaddr = document.getElementById('nat-modal-toaddr').value.trim();
  2505. const toport = document.getElementById('nat-modal-toport').value.trim();
  2506. const proto = document.getElementById('nat-modal-proto').value;
  2507. const src = document.getElementById('nat-modal-src').value.trim();
  2508. const dst = document.getElementById('nat-modal-dst').value.trim();
  2509. const dport = document.getElementById('nat-modal-dport').value.trim();
  2510. const inIface = document.getElementById('nat-modal-iniface').value;
  2511. const outIface = document.getElementById('nat-modal-outiface').value;
  2512. let srclist = document.getElementById('nat-modal-srclist')?.value || '';
  2513. if (srclist && document.getElementById('nat-modal-srclist-inv')?.checked) {
  2514. srclist = '!' + srclist.replace(/^!/, '');
  2515. }
  2516. let dstlist = document.getElementById('nat-modal-dstlist')?.value || '';
  2517. if (dstlist && document.getElementById('nat-modal-dstlist-inv')?.checked) {
  2518. dstlist = '!' + dstlist.replace(/^!/, '');
  2519. }
  2520. let srcgeoip = document.getElementById('nat-modal-srcgeoip')?.value || '';
  2521. if (srcgeoip && document.getElementById('nat-modal-srcgeoip-inv')?.checked) {
  2522. srcgeoip = '!' + srcgeoip.replace(/^!/, '');
  2523. }
  2524. let dstgeoip = document.getElementById('nat-modal-dstgeoip')?.value || '';
  2525. if (dstgeoip && document.getElementById('nat-modal-dstgeoip-inv')?.checked) {
  2526. dstgeoip = '!' + dstgeoip.replace(/^!/, '');
  2527. }
  2528. const comment = document.getElementById('nat-modal-comment').value.trim();
  2529. const disabled = document.getElementById('nat-modal-disabled').checked;
  2530. try {
  2531. const res = await fetch(`${API_BASE}/firewall/nat`, {
  2532. method: 'POST',
  2533. headers: { 'Content-Type': 'application/json' },
  2534. body: JSON.stringify({
  2535. id,
  2536. chain,
  2537. action,
  2538. to_addresses: toaddr,
  2539. to_ports: toport,
  2540. protocol: proto,
  2541. src_address: src,
  2542. dst_address: dst,
  2543. dst_port: dport,
  2544. in_interface: inIface,
  2545. out_interface: outIface,
  2546. src_address_list: srclist,
  2547. dst_address_list: dstlist,
  2548. src_geoip: srcgeoip,
  2549. dst_geoip: dstgeoip,
  2550. comment,
  2551. disabled
  2552. })
  2553. });
  2554. if (res.ok) {
  2555. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  2556. closeNATModal();
  2557. loadFirewall(false);
  2558. }
  2559. } catch (err) {
  2560. showToast('Error', err.message, 'error');
  2561. }
  2562. }
  2563. async function moveNATRule(id, dir) {
  2564. try {
  2565. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  2566. method: 'POST',
  2567. headers: { 'Content-Type': 'application/json' },
  2568. body: JSON.stringify({ direction: dir })
  2569. });
  2570. if (res.ok) loadFirewall(false);
  2571. } catch (err) {
  2572. showToast('Error', err.message, 'error');
  2573. }
  2574. }
  2575. async function toggleNATRuleState(id, disabled) {
  2576. try {
  2577. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  2578. method: 'POST',
  2579. headers: { 'Content-Type': 'application/json' },
  2580. body: JSON.stringify({ disabled })
  2581. });
  2582. if (res.ok) loadFirewall(false);
  2583. } catch (err) {
  2584. showToast('Error', err.message, 'error');
  2585. }
  2586. }
  2587. async function deleteNATRule(id) {
  2588. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  2589. try {
  2590. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2591. if (res.ok) {
  2592. showToast('Deleted', 'NAT rule removed', 'success');
  2593. loadFirewall(false);
  2594. }
  2595. } catch (err) {
  2596. showToast('Error', err.message, 'error');
  2597. }
  2598. }
  2599. // ----------------- Mangle Rules -----------------
  2600. function renderMangleRules() {
  2601. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  2602. const tbody = document.getElementById('mangle-table-body');
  2603. const empty = document.getElementById('mangle-empty');
  2604. if (!tbody) return;
  2605. tbody.innerHTML = '';
  2606. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2607. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  2608. if (rules.length === 0) {
  2609. empty?.classList.remove('hidden');
  2610. return;
  2611. }
  2612. empty?.classList.add('hidden');
  2613. rules.forEach((r, idx) => {
  2614. const tr = document.createElement('tr');
  2615. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2616. const markVal = r.new_connection_mark || r.new_routing_mark || r.new_packet_mark || r.new_mss || (r.new_dscp ? 'DSCP:' + r.new_dscp : '');
  2617. tr.innerHTML = `
  2618. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2619. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2620. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  2621. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2622. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2623. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2624. <td class="py-2.5 px-3 font-mono font-bold text-cyan-300">${markVal || '-'}</td>
  2625. <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>
  2626. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2627. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2628. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2629. </td>
  2630. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2631. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2632. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2633. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2634. <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>
  2635. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2636. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2637. </td>
  2638. `;
  2639. tbody.appendChild(tr);
  2640. });
  2641. }
  2642. function openAddMangleModal() {
  2643. document.getElementById('mangle-modal-title').innerText = 'Add Mangle Rule';
  2644. document.getElementById('mangle-modal-id').value = '';
  2645. document.getElementById('mangle-modal-chain').value = 'prerouting';
  2646. document.getElementById('mangle-modal-action').value = 'mark-connection';
  2647. document.getElementById('mangle-modal-newmark').value = '';
  2648. document.getElementById('mangle-modal-passthrough').checked = true;
  2649. document.getElementById('mangle-modal-src').value = '';
  2650. document.getElementById('mangle-modal-dst').value = '';
  2651. document.getElementById('mangle-modal-connmark').value = '';
  2652. document.getElementById('mangle-modal-comment').value = '';
  2653. document.getElementById('mangle-modal-disabled').checked = false;
  2654. populateInterfaceSelect('mangle-modal-iniface');
  2655. populateAddressListSelect('mangle-modal-srclist');
  2656. populateAddressListSelect('mangle-modal-dstlist');
  2657. const srcInvEl = document.getElementById('mangle-modal-srclist-inv');
  2658. if (srcInvEl) srcInvEl.checked = false;
  2659. const dstInvEl = document.getElementById('mangle-modal-dstlist-inv');
  2660. if (dstInvEl) dstInvEl.checked = false;
  2661. populateGeoIPSelect('mangle-modal-srcgeoip');
  2662. populateGeoIPSelect('mangle-modal-dstgeoip');
  2663. const srcGeoInvEl = document.getElementById('mangle-modal-srcgeoip-inv');
  2664. if (srcGeoInvEl) srcGeoInvEl.checked = false;
  2665. const dstGeoInvEl = document.getElementById('mangle-modal-dstgeoip-inv');
  2666. if (dstGeoInvEl) dstGeoInvEl.checked = false;
  2667. document.getElementById('mangle-modal').classList.remove('hidden');
  2668. }
  2669. function openEditMangleModal(id) {
  2670. const r = (state.mangleRules || []).find(rule => rule.id === id);
  2671. if (!r) return;
  2672. document.getElementById('mangle-modal-title').innerText = `Edit Mangle Rule (#${r.order})`;
  2673. document.getElementById('mangle-modal-id').value = r.id;
  2674. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  2675. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  2676. document.getElementById('mangle-modal-newmark').value = r.new_connection_mark || r.new_routing_mark || r.new_packet_mark || r.new_mss || '';
  2677. document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  2678. document.getElementById('mangle-modal-src').value = r.src_address || '';
  2679. document.getElementById('mangle-modal-dst').value = r.dst_address || '';
  2680. document.getElementById('mangle-modal-connmark').value = r.connection_mark || '';
  2681. document.getElementById('mangle-modal-comment').value = r.comment || '';
  2682. document.getElementById('mangle-modal-disabled').checked = !!r.disabled;
  2683. populateInterfaceSelect('mangle-modal-iniface', r.in_interface);
  2684. const srcInv = (r.src_address_list || '').startsWith('!');
  2685. const dstInv = (r.dst_address_list || '').startsWith('!');
  2686. const srcInvEl = document.getElementById('mangle-modal-srclist-inv');
  2687. if (srcInvEl) srcInvEl.checked = srcInv;
  2688. const dstInvEl = document.getElementById('mangle-modal-dstlist-inv');
  2689. if (dstInvEl) dstInvEl.checked = dstInv;
  2690. populateAddressListSelect('mangle-modal-srclist', r.src_address_list || '');
  2691. populateAddressListSelect('mangle-modal-dstlist', r.dst_address_list || '');
  2692. const srcGeoInv = (r.src_geoip || '').startsWith('!');
  2693. const dstGeoInv = (r.dst_geoip || '').startsWith('!');
  2694. const srcGeoInvEl = document.getElementById('mangle-modal-srcgeoip-inv');
  2695. if (srcGeoInvEl) srcGeoInvEl.checked = srcGeoInv;
  2696. const dstGeoInvEl = document.getElementById('mangle-modal-dstgeoip-inv');
  2697. if (dstGeoInvEl) dstGeoInvEl.checked = dstGeoInv;
  2698. populateGeoIPSelect('mangle-modal-srcgeoip', r.src_geoip || '');
  2699. populateGeoIPSelect('mangle-modal-dstgeoip', r.dst_geoip || '');
  2700. document.getElementById('mangle-modal').classList.remove('hidden');
  2701. }
  2702. function closeMangleModal() {
  2703. document.getElementById('mangle-modal').classList.add('hidden');
  2704. }
  2705. function toggleMangleActionFields() {
  2706. // Handled smoothly by single dynamic input
  2707. }
  2708. async function submitSaveMangleRule(e) {
  2709. e.preventDefault();
  2710. const id = document.getElementById('mangle-modal-id').value;
  2711. const chain = document.getElementById('mangle-modal-chain').value;
  2712. const action = document.getElementById('mangle-modal-action').value;
  2713. const newmark = document.getElementById('mangle-modal-newmark').value.trim();
  2714. const passthrough = document.getElementById('mangle-modal-passthrough').checked;
  2715. const src = document.getElementById('mangle-modal-src').value.trim();
  2716. const dst = document.getElementById('mangle-modal-dst').value.trim();
  2717. const inIface = document.getElementById('mangle-modal-iniface').value;
  2718. let srclist = document.getElementById('mangle-modal-srclist')?.value || '';
  2719. if (srclist && document.getElementById('mangle-modal-srclist-inv')?.checked) {
  2720. srclist = '!' + srclist.replace(/^!/, '');
  2721. }
  2722. let dstlist = document.getElementById('mangle-modal-dstlist')?.value || '';
  2723. if (dstlist && document.getElementById('mangle-modal-dstlist-inv')?.checked) {
  2724. dstlist = '!' + dstlist.replace(/^!/, '');
  2725. }
  2726. let srcgeoip = document.getElementById('mangle-modal-srcgeoip')?.value || '';
  2727. if (srcgeoip && document.getElementById('mangle-modal-srcgeoip-inv')?.checked) {
  2728. srcgeoip = '!' + srcgeoip.replace(/^!/, '');
  2729. }
  2730. let dstgeoip = document.getElementById('mangle-modal-dstgeoip')?.value || '';
  2731. if (dstgeoip && document.getElementById('mangle-modal-dstgeoip-inv')?.checked) {
  2732. dstgeoip = '!' + dstgeoip.replace(/^!/, '');
  2733. }
  2734. const connmark = document.getElementById('mangle-modal-connmark').value.trim();
  2735. const comment = document.getElementById('mangle-modal-comment').value.trim();
  2736. const disabled = document.getElementById('mangle-modal-disabled').checked;
  2737. const payload = {
  2738. id,
  2739. chain,
  2740. action,
  2741. passthrough,
  2742. src_address: src,
  2743. dst_address: dst,
  2744. in_interface: inIface,
  2745. src_address_list: srclist,
  2746. dst_address_list: dstlist,
  2747. src_geoip: srcgeoip,
  2748. dst_geoip: dstgeoip,
  2749. connection_mark: connmark,
  2750. comment,
  2751. disabled
  2752. };
  2753. if (action === 'mark-connection') payload.new_connection_mark = newmark;
  2754. else if (action === 'mark-routing') payload.new_routing_mark = newmark;
  2755. else if (action === 'mark-packet') payload.new_packet_mark = newmark;
  2756. else if (action === 'change-mss') payload.new_mss = newmark || 'clamp-to-pmtu';
  2757. try {
  2758. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  2759. method: 'POST',
  2760. headers: { 'Content-Type': 'application/json' },
  2761. body: JSON.stringify(payload)
  2762. });
  2763. if (res.ok) {
  2764. showToast('Mangle Rule Saved', 'Marking rule applied', 'success');
  2765. closeMangleModal();
  2766. loadFirewall(false);
  2767. }
  2768. } catch (err) {
  2769. showToast('Error', err.message, 'error');
  2770. }
  2771. }
  2772. async function moveMangleRule(id, dir) {
  2773. try {
  2774. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  2775. method: 'POST',
  2776. headers: { 'Content-Type': 'application/json' },
  2777. body: JSON.stringify({ direction: dir })
  2778. });
  2779. if (res.ok) loadFirewall(false);
  2780. } catch (err) {
  2781. showToast('Error', err.message, 'error');
  2782. }
  2783. }
  2784. async function toggleMangleRuleState(id, disabled) {
  2785. try {
  2786. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  2787. method: 'POST',
  2788. headers: { 'Content-Type': 'application/json' },
  2789. body: JSON.stringify({ disabled })
  2790. });
  2791. if (res.ok) loadFirewall(false);
  2792. } catch (err) {
  2793. showToast('Error', err.message, 'error');
  2794. }
  2795. }
  2796. async function deleteMangleRule(id) {
  2797. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  2798. try {
  2799. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2800. if (res.ok) {
  2801. showToast('Deleted', 'Mangle rule removed', 'success');
  2802. loadFirewall(false);
  2803. }
  2804. } catch (err) {
  2805. showToast('Error', err.message, 'error');
  2806. }
  2807. }
  2808. // ----------------- Address Lists -----------------
  2809. function renderAddressLists() {
  2810. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  2811. const tbody = document.getElementById('addrlist-table-body');
  2812. const empty = document.getElementById('addrlist-empty');
  2813. if (!tbody) return;
  2814. tbody.innerHTML = '';
  2815. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  2816. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  2817. // Update filter select
  2818. const sel = document.getElementById('addrlist-filter-name');
  2819. if (sel) {
  2820. const cur = sel.value;
  2821. sel.innerHTML = '<option value="">All Lists</option>';
  2822. const set = new Set((state.addressLists || []).map(a => a.name));
  2823. set.forEach(n => {
  2824. const opt = document.createElement('option');
  2825. opt.value = n;
  2826. opt.innerText = n;
  2827. if (n === cur) opt.selected = true;
  2828. sel.appendChild(opt);
  2829. });
  2830. }
  2831. if (entries.length === 0) {
  2832. empty?.classList.remove('hidden');
  2833. return;
  2834. }
  2835. empty?.classList.add('hidden');
  2836. entries.forEach((e, idx) => {
  2837. const tr = document.createElement('tr');
  2838. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  2839. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  2840. tr.innerHTML = `
  2841. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  2842. <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>
  2843. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  2844. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  2845. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  2846. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  2847. <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>
  2848. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  2849. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2850. </td>
  2851. `;
  2852. tbody.appendChild(tr);
  2853. });
  2854. }
  2855. function openAddAddrListModal() {
  2856. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  2857. document.getElementById('addrlist-modal-id').value = '';
  2858. document.getElementById('addrlist-modal-name').value = '';
  2859. document.getElementById('addrlist-modal-addr').value = '';
  2860. document.getElementById('addrlist-modal-comment').value = '';
  2861. document.getElementById('addrlist-modal-disabled').checked = false;
  2862. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  2863. if (submitBtn) submitBtn.innerText = 'Add to List';
  2864. document.getElementById('addrlist-modal').classList.remove('hidden');
  2865. }
  2866. function openEditAddrListModal(id) {
  2867. const e = (state.addressLists || []).find(item => item.id === id);
  2868. if (!e) return;
  2869. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  2870. document.getElementById('addrlist-modal-id').value = e.id;
  2871. document.getElementById('addrlist-modal-name').value = e.name;
  2872. document.getElementById('addrlist-modal-addr').value = e.address;
  2873. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  2874. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  2875. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  2876. if (submitBtn) submitBtn.innerText = 'Save Changes';
  2877. document.getElementById('addrlist-modal').classList.remove('hidden');
  2878. }
  2879. function closeAddrListModal() {
  2880. document.getElementById('addrlist-modal').classList.add('hidden');
  2881. }
  2882. async function submitSaveAddrList(e) {
  2883. e.preventDefault();
  2884. const id = document.getElementById('addrlist-modal-id').value;
  2885. const name = document.getElementById('addrlist-modal-name').value.trim();
  2886. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  2887. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  2888. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  2889. try {
  2890. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  2891. method: 'POST',
  2892. headers: { 'Content-Type': 'application/json' },
  2893. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  2894. });
  2895. if (res.ok) {
  2896. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  2897. closeAddrListModal();
  2898. loadFirewall(false);
  2899. } else {
  2900. const err = await res.json();
  2901. showToast('Error', err.message || 'Failed to save address list', 'error');
  2902. }
  2903. } catch (err) {
  2904. showToast('Error', err.message, 'error');
  2905. }
  2906. }
  2907. async function toggleAddrListState(id, disabled) {
  2908. try {
  2909. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  2910. method: 'POST',
  2911. headers: { 'Content-Type': 'application/json' },
  2912. body: JSON.stringify({ disabled })
  2913. });
  2914. if (res.ok) {
  2915. loadFirewall(false);
  2916. }
  2917. } catch (err) {
  2918. showToast('Error', err.message, 'error');
  2919. }
  2920. }
  2921. async function deleteAddrList(id) {
  2922. if (!confirm('Are you sure you want to delete this address list item?')) return;
  2923. try {
  2924. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2925. if (res.ok) {
  2926. showToast('Deleted', 'Address list item removed', 'info');
  2927. loadFirewall(false);
  2928. }
  2929. } catch (err) {
  2930. showToast('Error', err.message, 'error');
  2931. }
  2932. }
  2933. // ----------------- Geo-Location IP Management -----------------
  2934. async function loadGeoIP() {
  2935. try {
  2936. const [statusRes, countriesRes] = await Promise.all([
  2937. fetch(`${API_BASE}/firewall/geoip/status`),
  2938. fetch(`${API_BASE}/firewall/geoip/countries`)
  2939. ]);
  2940. if (statusRes.ok) state.geoStatus = await statusRes.json();
  2941. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  2942. updateGeoHeader();
  2943. renderGeoCountries();
  2944. } catch (err) {
  2945. console.error('Failed to load GeoIP:', err);
  2946. }
  2947. }
  2948. function getGeoUsageMap() {
  2949. const usage = {};
  2950. const checkRule = (r, type) => {
  2951. ['src_geoip', 'dst_geoip'].forEach(field => {
  2952. let val = (r && r[field]) || '';
  2953. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  2954. if (code) {
  2955. if (!usage[code]) usage[code] = [];
  2956. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  2957. if (!usage[code].includes(label)) usage[code].push(label);
  2958. }
  2959. });
  2960. };
  2961. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  2962. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  2963. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  2964. return usage;
  2965. }
  2966. function updateGeoHeader() {
  2967. const s = state.geoStatus || {};
  2968. const statusBadge = document.getElementById('geo-status-badge');
  2969. if (statusBadge) {
  2970. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  2971. statusBadge.className = s.auto_update
  2972. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  2973. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  2974. }
  2975. const intervalLabel = document.getElementById('geo-interval-label');
  2976. if (intervalLabel) {
  2977. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  2978. }
  2979. const usageMap = getGeoUsageMap();
  2980. const inUseCount = Object.keys(usageMap).length;
  2981. const activeCountEl = document.getElementById('geo-stat-active-countries');
  2982. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  2983. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  2984. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  2985. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  2986. if (lastSyncEl) {
  2987. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  2988. const d = new Date(s.last_updated);
  2989. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  2990. } else {
  2991. lastSyncEl.innerText = 'Never (Sync Pending)';
  2992. }
  2993. }
  2994. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  2995. if (nextSyncEl) {
  2996. if (s.next_update && !s.next_update.startsWith('0001')) {
  2997. const d = new Date(s.next_update);
  2998. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  2999. } else {
  3000. nextSyncEl.innerText = '-';
  3001. }
  3002. }
  3003. const badge = document.getElementById('fw-badge-geo');
  3004. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  3005. }
  3006. function renderGeoCountries() {
  3007. const tbody = document.getElementById('geo-table-body');
  3008. const empty = document.getElementById('geo-empty');
  3009. if (!tbody) return;
  3010. tbody.innerHTML = '';
  3011. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  3012. const continent = document.getElementById('geo-continent-filter')?.value || '';
  3013. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  3014. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  3015. const usageMap = getGeoUsageMap();
  3016. const countries = (state.geoCountries || []).filter(c => {
  3017. const isUsed = !!usageMap[c.code];
  3018. if (inUseOnly && !isUsed) return false;
  3019. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  3020. if (continent && c.continent !== continent) return false;
  3021. if (q) {
  3022. const matchCode = c.code.toLowerCase().includes(q);
  3023. const matchName = c.name.toLowerCase().includes(q);
  3024. if (!matchCode && !matchName) return false;
  3025. }
  3026. return true;
  3027. });
  3028. if (countries.length === 0) {
  3029. empty?.classList.remove('hidden');
  3030. return;
  3031. }
  3032. empty?.classList.add('hidden');
  3033. countries.forEach(c => {
  3034. const tr = document.createElement('tr');
  3035. const isUsed = !!usageMap[c.code];
  3036. const rulesUsing = usageMap[c.code] || [];
  3037. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  3038. let statusHtml = '';
  3039. if (isUsed) {
  3040. statusHtml = `<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" title="Assigned in: ${rulesUsing.join(', ')}">IN USE (${rulesUsing.length})</span>`;
  3041. } else if (c.subnet_count > 0) {
  3042. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-cyan-300 bg-cyan-950/40 border border-cyan-800/40">CACHED</span>';
  3043. } else {
  3044. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  3045. }
  3046. tr.innerHTML = `
  3047. <td class="py-2.5 px-3 text-center">
  3048. <span class="px-2 py-0.5 rounded font-mono font-bold ${isUsed ? 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/40' : 'bg-slate-800 text-cyan-300 border border-slate-700'}">
  3049. ${c.code}
  3050. </span>
  3051. </td>
  3052. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  3053. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  3054. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  3055. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  3056. </td>
  3057. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  3058. <td class="py-2.5 px-3">
  3059. ${statusHtml}
  3060. </td>
  3061. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  3062. <button onclick="updateGeoCountry('${c.code}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium" title="Re-download latest country IP blocks">Sync</button>
  3063. <button onclick="viewGeoSubnets('${c.code}', '${c.name.replace(/'/g, "\\'")}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  3064. </td>
  3065. `;
  3066. tbody.appendChild(tr);
  3067. });
  3068. }
  3069. function quickFilterGeo(preset) {
  3070. const searchInput = document.getElementById('geo-search-input');
  3071. const continentSel = document.getElementById('geo-continent-filter');
  3072. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  3073. const cachedCheck = document.getElementById('geo-filter-cached-only');
  3074. if (searchInput) searchInput.value = '';
  3075. if (continentSel) continentSel.value = '';
  3076. if (inUseCheck) inUseCheck.checked = false;
  3077. if (cachedCheck) cachedCheck.checked = false;
  3078. if (preset === 'GR') {
  3079. if (searchInput) searchInput.value = 'Greece';
  3080. } else if (preset === 'Europe') {
  3081. if (continentSel) continentSel.value = 'Europe';
  3082. } else if (preset === 'HIGHRISK') {
  3083. if (searchInput) searchInput.value = 'China';
  3084. }
  3085. renderGeoCountries();
  3086. }
  3087. async function toggleGeoCountry(code, enabled) {
  3088. try {
  3089. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  3090. method: 'POST',
  3091. headers: { 'Content-Type': 'application/json' },
  3092. body: JSON.stringify({ enabled })
  3093. });
  3094. if (res.ok) {
  3095. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  3096. loadGeoIP();
  3097. } else {
  3098. const err = await res.json();
  3099. showToast('Error', err.message || 'Failed to toggle country', 'error');
  3100. }
  3101. } catch (err) {
  3102. showToast('Error', err.message, 'error');
  3103. }
  3104. }
  3105. async function updateGeoCountry(code) {
  3106. try {
  3107. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  3108. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  3109. if (res.ok) {
  3110. const data = await res.json();
  3111. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  3112. loadGeoIP();
  3113. } else {
  3114. const err = await res.json();
  3115. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  3116. }
  3117. } catch (err) {
  3118. showToast('Error', err.message, 'error');
  3119. }
  3120. }
  3121. async function triggerGeoUpdateNow() {
  3122. const spinner = document.getElementById('geo-update-spinner');
  3123. if (spinner) spinner.classList.remove('hidden');
  3124. try {
  3125. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  3126. if (res.ok) {
  3127. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  3128. setTimeout(() => {
  3129. loadGeoIP();
  3130. if (spinner) spinner.classList.add('hidden');
  3131. }, 2500);
  3132. } else {
  3133. const err = await res.json();
  3134. showToast('Notice', err.message || 'Update in progress', 'info');
  3135. if (spinner) spinner.classList.add('hidden');
  3136. }
  3137. } catch (err) {
  3138. showToast('Error', err.message, 'error');
  3139. if (spinner) spinner.classList.add('hidden');
  3140. }
  3141. }
  3142. async function applyGeoPreset(preset) {
  3143. try {
  3144. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  3145. method: 'POST',
  3146. headers: { 'Content-Type': 'application/json' },
  3147. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  3148. });
  3149. if (res.ok) {
  3150. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  3151. loadGeoIP();
  3152. }
  3153. } catch (err) {
  3154. showToast('Error', err.message, 'error');
  3155. }
  3156. }
  3157. function openGeoIntervalModal() {
  3158. const s = state.geoStatus || {};
  3159. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  3160. const sel = document.getElementById('geo-cfg-interval');
  3161. const customBox = document.getElementById('geo-cfg-custom-box');
  3162. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  3163. const curHours = s.interval_hours || 24;
  3164. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  3165. if (matchOption) {
  3166. sel.value = String(curHours);
  3167. customBox.classList.add('hidden');
  3168. } else {
  3169. sel.value = 'custom';
  3170. customHoursInput.value = curHours;
  3171. customBox.classList.remove('hidden');
  3172. }
  3173. document.getElementById('geo-interval-modal').classList.remove('hidden');
  3174. }
  3175. function closeGeoIntervalModal() {
  3176. document.getElementById('geo-interval-modal').classList.add('hidden');
  3177. }
  3178. function toggleCustomGeoInterval() {
  3179. const val = document.getElementById('geo-cfg-interval').value;
  3180. const customBox = document.getElementById('geo-cfg-custom-box');
  3181. if (val === 'custom') {
  3182. customBox.classList.remove('hidden');
  3183. } else {
  3184. customBox.classList.add('hidden');
  3185. }
  3186. }
  3187. async function submitGeoIntervalSettings(e) {
  3188. e.preventDefault();
  3189. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  3190. const intervalVal = document.getElementById('geo-cfg-interval').value;
  3191. let hours = 24;
  3192. if (intervalVal === 'custom') {
  3193. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  3194. } else {
  3195. hours = parseInt(intervalVal, 10) || 24;
  3196. }
  3197. try {
  3198. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  3199. method: 'POST',
  3200. headers: { 'Content-Type': 'application/json' },
  3201. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  3202. });
  3203. if (res.ok) {
  3204. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  3205. closeGeoIntervalModal();
  3206. loadGeoIP();
  3207. } else {
  3208. const err = await res.json();
  3209. showToast('Error', err.message || 'Failed to save schedule', 'error');
  3210. }
  3211. } catch (err) {
  3212. showToast('Error', err.message, 'error');
  3213. }
  3214. }
  3215. async function viewGeoSubnets(code, name) {
  3216. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  3217. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  3218. const listEl = document.getElementById('geo-subnets-list');
  3219. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  3220. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  3221. try {
  3222. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  3223. if (res.ok) {
  3224. const data = await res.json();
  3225. const subnets = data.subnets || [];
  3226. if (subnets.length === 0) {
  3227. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  3228. } else {
  3229. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  3230. }
  3231. } else {
  3232. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  3233. }
  3234. } catch (err) {
  3235. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  3236. }
  3237. }
  3238. function closeGeoSubnetsModal() {
  3239. document.getElementById('geo-subnets-modal').classList.add('hidden');
  3240. }
  3241. // ----------------- Active Connections Tracking -----------------
  3242. async function loadConnections() {
  3243. try {
  3244. const res = await fetch(`${API_BASE}/firewall/connections`);
  3245. const data = await res.json();
  3246. state.connections = Array.isArray(data) ? data : [];
  3247. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  3248. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  3249. renderConnections();
  3250. } catch (err) {
  3251. console.error('Failed to load connections:', err);
  3252. }
  3253. }
  3254. function renderConnections() {
  3255. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  3256. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  3257. const tbody = document.getElementById('conns-table-body');
  3258. const empty = document.getElementById('conns-empty');
  3259. if (!tbody) return;
  3260. tbody.innerHTML = '';
  3261. const conns = (state.connections || []).filter(c => {
  3262. if (protoFilter && c.protocol !== protoFilter) return false;
  3263. if (search) {
  3264. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  3265. if (!line.includes(search)) return false;
  3266. }
  3267. return true;
  3268. });
  3269. if (conns.length === 0) {
  3270. empty?.classList.remove('hidden');
  3271. return;
  3272. }
  3273. empty?.classList.add('hidden');
  3274. conns.slice(0, 150).forEach(c => {
  3275. const tr = document.createElement('tr');
  3276. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  3277. let stateColor = 'text-slate-400';
  3278. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  3279. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  3280. tr.innerHTML = `
  3281. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  3282. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  3283. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  3284. <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>
  3285. <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>
  3286. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  3287. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  3288. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  3289. <td class="py-2.5 px-3 text-right font-sans">
  3290. <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>
  3291. </td>
  3292. `;
  3293. tbody.appendChild(tr);
  3294. });
  3295. }
  3296. async function killConnection(protocol, src, sport, dst, dport) {
  3297. try {
  3298. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  3299. method: 'POST',
  3300. headers: { 'Content-Type': 'application/json' },
  3301. body: JSON.stringify({ protocol, src, sport, dst, dport })
  3302. });
  3303. if (res.ok) {
  3304. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  3305. loadConnections();
  3306. }
  3307. } catch (err) {
  3308. showToast('Error', err.message, 'error');
  3309. }
  3310. }
  3311. async function resetFirewallCounters() {
  3312. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  3313. try {
  3314. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3315. if (res.ok) {
  3316. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  3317. loadFirewall(false);
  3318. }
  3319. } catch (err) {
  3320. showToast('Error', err.message, 'error');
  3321. }
  3322. }
  3323. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  3324. function switchRoutesSubTab(tab) {
  3325. state.routesSubTab = tab;
  3326. const tabs = ['routes', 'rules', 'tables'];
  3327. tabs.forEach(t => {
  3328. const panel = document.getElementById(`routes-subtab-${t}`);
  3329. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  3330. if (panel) {
  3331. if (t === tab) panel.classList.remove('hidden');
  3332. else panel.classList.add('hidden');
  3333. }
  3334. if (btn) {
  3335. if (t === tab) {
  3336. 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';
  3337. } else {
  3338. 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';
  3339. }
  3340. }
  3341. });
  3342. }
  3343. async function loadRoutes() {
  3344. try {
  3345. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  3346. fetch(`${API_BASE}/routes`),
  3347. fetch(`${API_BASE}/routing/rules`),
  3348. fetch(`${API_BASE}/routing/tables`)
  3349. ]);
  3350. if (routesRes.ok) state.routes = await routesRes.json();
  3351. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  3352. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  3353. const bRoutes = document.getElementById('routes-badge-routes');
  3354. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  3355. const bRules = document.getElementById('routes-badge-rules');
  3356. if (bRules) bRules.innerText = (state.policyRules || []).length;
  3357. const bTables = document.getElementById('routes-badge-tables');
  3358. if (bTables) bTables.innerText = (state.routingTables || []).length;
  3359. const bRoutesCount = document.getElementById('badge-routes-count');
  3360. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  3361. renderRoutesList();
  3362. renderPolicyRules();
  3363. renderRoutingTables();
  3364. } catch (err) {
  3365. console.error('Failed to load routing:', err);
  3366. }
  3367. }
  3368. function renderRoutesList() {
  3369. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  3370. const tbody = document.getElementById('routes-table-body');
  3371. const empty = document.getElementById('routes-empty');
  3372. if (!tbody) return;
  3373. tbody.innerHTML = '';
  3374. // Update table filter select
  3375. const sel = document.getElementById('routes-filter-table');
  3376. if (sel) {
  3377. const cur = sel.value;
  3378. sel.innerHTML = '<option value="">All Tables</option>';
  3379. (state.routingTables || []).forEach(t => {
  3380. const opt = document.createElement('option');
  3381. opt.value = t.name;
  3382. opt.innerText = t.name;
  3383. if (t.name === cur) opt.selected = true;
  3384. sel.appendChild(opt);
  3385. });
  3386. }
  3387. const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
  3388. document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
  3389. if (routes.length === 0) {
  3390. empty?.classList.remove('hidden');
  3391. return;
  3392. }
  3393. empty?.classList.add('hidden');
  3394. routes.forEach(r => {
  3395. const tr = document.createElement('tr');
  3396. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  3397. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  3398. // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
  3399. let flags = '';
  3400. if (r.dynamic) flags += 'D';
  3401. if (r.active) flags += 'A';
  3402. if (r.connect) flags += 'C';
  3403. if (r.static) flags += 'S';
  3404. if (r.disabled) flags += 'X';
  3405. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  3406. tr.innerHTML = `
  3407. <td class="py-2.5 px-3 text-center">
  3408. <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'}">
  3409. ${flags || '-'}
  3410. </span>
  3411. </td>
  3412. <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
  3413. <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>
  3414. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  3415. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  3416. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  3417. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  3418. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  3419. ${r.static ? `
  3420. <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>
  3421. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  3422. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3423. ` : `
  3424. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  3425. `}
  3426. </td>
  3427. `;
  3428. tbody.appendChild(tr);
  3429. });
  3430. }
  3431. function openAddRouteModal() {
  3432. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  3433. document.getElementById('route-modal-id').value = '';
  3434. document.getElementById('route-modal-old-dst').value = '';
  3435. document.getElementById('route-modal-old-gw').value = '';
  3436. document.getElementById('route-modal-old-distance').value = '';
  3437. document.getElementById('route-modal-old-table').value = '';
  3438. document.getElementById('route-modal-old-iface').value = '';
  3439. const dstInput = document.getElementById('route-modal-dst');
  3440. const gwInput = document.getElementById('route-modal-gw');
  3441. const distInput = document.getElementById('route-modal-distance');
  3442. const ifaceSelect = document.getElementById('route-modal-iface');
  3443. const tableSelect = document.getElementById('route-modal-table');
  3444. const commentInput = document.getElementById('route-modal-comment');
  3445. const disCheck = document.getElementById('route-modal-disabled');
  3446. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  3447. dstInput.disabled = false;
  3448. dstInput.value = '0.0.0.0/0';
  3449. gwInput.disabled = false;
  3450. gwInput.value = '';
  3451. distInput.disabled = false;
  3452. distInput.value = '1';
  3453. ifaceSelect.disabled = false;
  3454. tableSelect.disabled = false;
  3455. commentInput.disabled = false;
  3456. commentInput.value = '';
  3457. disCheck.disabled = false;
  3458. disCheck.checked = false;
  3459. if (saveBtn) saveBtn.classList.remove('hidden');
  3460. populateInterfaceSelect('route-modal-iface');
  3461. // Populate tables
  3462. tableSelect.innerHTML = '';
  3463. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  3464. const opt = document.createElement('option');
  3465. opt.value = t.name;
  3466. opt.innerText = t.name;
  3467. if (t.name === 'main') opt.selected = true;
  3468. tableSelect.appendChild(opt);
  3469. });
  3470. document.getElementById('route-modal').classList.remove('hidden');
  3471. }
  3472. function openEditRouteModal(id) {
  3473. const r = (state.routes || []).find(route => route.id === id);
  3474. if (!r) return;
  3475. const isStatic = !!r.static;
  3476. document.getElementById('route-modal-title').innerText = isStatic
  3477. ? `Edit Route: ${r.dst_address}`
  3478. : `Route Properties (Read Only): ${r.dst_address}`;
  3479. document.getElementById('route-modal-id').value = r.id;
  3480. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  3481. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  3482. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  3483. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  3484. document.getElementById('route-modal-old-iface').value = r.interface || '';
  3485. const dstInput = document.getElementById('route-modal-dst');
  3486. const gwInput = document.getElementById('route-modal-gw');
  3487. const distInput = document.getElementById('route-modal-distance');
  3488. const ifaceSelect = document.getElementById('route-modal-iface');
  3489. const tableSelect = document.getElementById('route-modal-table');
  3490. const commentInput = document.getElementById('route-modal-comment');
  3491. const disCheck = document.getElementById('route-modal-disabled');
  3492. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  3493. dstInput.value = r.dst_address;
  3494. gwInput.value = r.gateway || '';
  3495. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  3496. commentInput.value = r.comment || '';
  3497. disCheck.checked = !!r.disabled;
  3498. dstInput.disabled = !isStatic;
  3499. gwInput.disabled = !isStatic;
  3500. distInput.disabled = !isStatic;
  3501. ifaceSelect.disabled = !isStatic;
  3502. tableSelect.disabled = !isStatic;
  3503. commentInput.disabled = !isStatic;
  3504. disCheck.disabled = !isStatic;
  3505. if (saveBtn) {
  3506. if (isStatic) {
  3507. saveBtn.classList.remove('hidden');
  3508. } else {
  3509. saveBtn.classList.add('hidden');
  3510. }
  3511. }
  3512. populateInterfaceSelect('route-modal-iface', r.interface);
  3513. tableSelect.innerHTML = '';
  3514. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  3515. const opt = document.createElement('option');
  3516. opt.value = t.name;
  3517. opt.innerText = t.name;
  3518. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  3519. tableSelect.appendChild(opt);
  3520. });
  3521. document.getElementById('route-modal').classList.remove('hidden');
  3522. }
  3523. function closeRouteModal() {
  3524. document.getElementById('route-modal').classList.add('hidden');
  3525. }
  3526. async function submitSaveRoute(e) {
  3527. e.preventDefault();
  3528. const id = document.getElementById('route-modal-id').value;
  3529. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  3530. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  3531. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  3532. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  3533. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  3534. const dst = document.getElementById('route-modal-dst').value.trim();
  3535. const gw = document.getElementById('route-modal-gw').value.trim();
  3536. const table = document.getElementById('route-modal-table').value;
  3537. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  3538. const iface = document.getElementById('route-modal-iface').value;
  3539. const comment = document.getElementById('route-modal-comment').value.trim();
  3540. const disabled = document.getElementById('route-modal-disabled').checked;
  3541. if (!dst) {
  3542. showToast('Error', 'Destination address is required', 'error');
  3543. return;
  3544. }
  3545. if (!gw && !iface) {
  3546. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  3547. return;
  3548. }
  3549. const payload = {
  3550. id,
  3551. old_dst_address: oldDst,
  3552. old_gateway: oldGw,
  3553. old_routing_table: oldTable,
  3554. old_interface: oldIface,
  3555. dst_address: dst,
  3556. gateway: gw || iface,
  3557. routing_table: table,
  3558. distance,
  3559. interface: iface,
  3560. comment,
  3561. disabled
  3562. };
  3563. if (oldDistStr !== undefined && oldDistStr !== '') {
  3564. payload.old_distance = parseInt(oldDistStr, 10);
  3565. }
  3566. try {
  3567. const res = await fetch(`${API_BASE}/routes`, {
  3568. method: 'POST',
  3569. headers: { 'Content-Type': 'application/json' },
  3570. body: JSON.stringify(payload)
  3571. });
  3572. if (res.ok) {
  3573. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  3574. closeRouteModal();
  3575. loadRoutes();
  3576. } else {
  3577. const err = await res.json();
  3578. showToast('Error', err.message || 'Failed to save route', 'error');
  3579. }
  3580. } catch (err) {
  3581. showToast('Error', err.message, 'error');
  3582. }
  3583. }
  3584. async function toggleRouteState(id, disabled) {
  3585. try {
  3586. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  3587. method: 'POST',
  3588. headers: { 'Content-Type': 'application/json' },
  3589. body: JSON.stringify({ disabled })
  3590. });
  3591. if (res.ok) loadRoutes();
  3592. } catch (err) {
  3593. showToast('Error', err.message, 'error');
  3594. }
  3595. }
  3596. async function deleteRoute(id) {
  3597. if (!confirm('Are you sure you want to delete this route?')) return;
  3598. try {
  3599. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3600. if (res.ok) {
  3601. showToast('Deleted', 'Route removed', 'success');
  3602. loadRoutes();
  3603. }
  3604. } catch (err) {
  3605. showToast('Error', err.message, 'error');
  3606. }
  3607. }
  3608. // ----------------- Policy Rules (/ip route rule) -----------------
  3609. function renderPolicyRules() {
  3610. const tbody = document.getElementById('rules-table-body');
  3611. const empty = document.getElementById('rules-empty');
  3612. if (!tbody) return;
  3613. tbody.innerHTML = '';
  3614. const rules = state.policyRules || [];
  3615. document.getElementById('rules-count-badge').innerText = `${rules.length} Rules`;
  3616. if (rules.length === 0) {
  3617. empty?.classList.remove('hidden');
  3618. return;
  3619. }
  3620. empty?.classList.add('hidden');
  3621. rules.forEach(pr => {
  3622. const tr = document.createElement('tr');
  3623. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  3624. tr.innerHTML = `
  3625. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  3626. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  3627. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  3628. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  3629. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  3630. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  3631. <td class="py-2.5 px-3 text-right font-sans">
  3632. ${pr.priority < 32766 && pr.priority > 0 ? `
  3633. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3634. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  3635. </td>
  3636. `;
  3637. tbody.appendChild(tr);
  3638. });
  3639. }
  3640. function openAddPolicyRuleModal() {
  3641. document.getElementById('prule-modal-pref').value = (state.policyRules || []).length * 10 + 1000;
  3642. document.getElementById('prule-modal-mark').value = '';
  3643. document.getElementById('prule-modal-src').value = '';
  3644. document.getElementById('prule-modal-dst').value = '';
  3645. const sel = document.getElementById('prule-modal-table');
  3646. sel.innerHTML = '';
  3647. (state.routingTables || []).forEach(t => {
  3648. const opt = document.createElement('option');
  3649. opt.value = t.name;
  3650. opt.innerText = t.name;
  3651. sel.appendChild(opt);
  3652. });
  3653. document.getElementById('prule-modal').classList.remove('hidden');
  3654. }
  3655. function closePolicyRuleModal() {
  3656. document.getElementById('prule-modal').classList.add('hidden');
  3657. }
  3658. async function submitSavePolicyRule(e) {
  3659. e.preventDefault();
  3660. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  3661. const mark = document.getElementById('prule-modal-mark').value.trim();
  3662. const src = document.getElementById('prule-modal-src').value.trim();
  3663. const dst = document.getElementById('prule-modal-dst').value.trim();
  3664. const table = document.getElementById('prule-modal-table').value;
  3665. const action = document.getElementById('prule-modal-action').value;
  3666. try {
  3667. const res = await fetch(`${API_BASE}/routing/rules`, {
  3668. method: 'POST',
  3669. headers: { 'Content-Type': 'application/json' },
  3670. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  3671. });
  3672. if (res.ok) {
  3673. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  3674. closePolicyRuleModal();
  3675. loadRoutes();
  3676. } else {
  3677. const err = await res.json();
  3678. showToast('Error', err.message, 'error');
  3679. }
  3680. } catch (err) {
  3681. showToast('Error', err.message, 'error');
  3682. }
  3683. }
  3684. async function deletePolicyRule(id) {
  3685. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  3686. try {
  3687. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3688. if (res.ok) {
  3689. showToast('Rule Removed', 'Policy rule deleted', 'success');
  3690. loadRoutes();
  3691. }
  3692. } catch (err) {
  3693. showToast('Error', err.message, 'error');
  3694. }
  3695. }
  3696. // ----------------- Routing Tables -----------------
  3697. function renderRoutingTables() {
  3698. const tbody = document.getElementById('tables-table-body');
  3699. if (!tbody) return;
  3700. tbody.innerHTML = '';
  3701. (state.routingTables || []).forEach(t => {
  3702. const tr = document.createElement('tr');
  3703. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  3704. tr.innerHTML = `
  3705. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  3706. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  3707. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  3708. `;
  3709. tbody.appendChild(tr);
  3710. });
  3711. }
  3712. function openAddTableModal() {
  3713. document.getElementById('table-modal-name').value = '';
  3714. document.getElementById('table-modal-id').value = '';
  3715. document.getElementById('table-modal-comment').value = '';
  3716. document.getElementById('table-modal').classList.remove('hidden');
  3717. }
  3718. function closeTableModal() {
  3719. document.getElementById('table-modal').classList.add('hidden');
  3720. }
  3721. async function submitSaveTable(e) {
  3722. e.preventDefault();
  3723. const name = document.getElementById('table-modal-name').value.trim();
  3724. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  3725. const comment = document.getElementById('table-modal-comment').value.trim();
  3726. try {
  3727. const res = await fetch(`${API_BASE}/routing/tables`, {
  3728. method: 'POST',
  3729. headers: { 'Content-Type': 'application/json' },
  3730. body: JSON.stringify({ name, table_id: id, comment })
  3731. });
  3732. if (res.ok) {
  3733. showToast('Table Created', `Routing table ${name} registered`, 'success');
  3734. closeTableModal();
  3735. loadRoutes();
  3736. } else {
  3737. const err = await res.json();
  3738. showToast('Error', err.message, 'error');
  3739. }
  3740. } catch (err) {
  3741. showToast('Error', err.message, 'error');
  3742. }
  3743. }
  3744. async function loadDebianConfig() {
  3745. const view = document.getElementById('debian-config-view');
  3746. view.innerText = 'Generating live configuration...';
  3747. try {
  3748. const res = await fetch(`${API_BASE}/debian/config`);
  3749. const data = await res.json();
  3750. view.innerText = data.content || '# Empty config';
  3751. } catch (err) {
  3752. view.innerText = 'Failed to generate Debian network config.';
  3753. }
  3754. }
  3755. async function saveDebianConfig() {
  3756. try {
  3757. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  3758. const data = await res.json();
  3759. if (res.ok) {
  3760. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  3761. loadDebianConfig();
  3762. }
  3763. } catch (err) {
  3764. showToast('Error', err.message, 'error');
  3765. }
  3766. }
  3767. function showToast(title, message, type = 'info') {
  3768. const container = document.getElementById('toast-container');
  3769. const toast = document.createElement('div');
  3770. const borderColors = {
  3771. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  3772. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  3773. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  3774. };
  3775. 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}`;
  3776. toast.innerHTML = `
  3777. <div class="flex-1">
  3778. <div class="font-bold text-xs text-white">${title}</div>
  3779. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  3780. </div>
  3781. `;
  3782. container.appendChild(toast);
  3783. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  3784. setTimeout(() => {
  3785. toast.classList.add('opacity-0', 'translate-y-2');
  3786. setTimeout(() => toast.remove(), 300);
  3787. }, 4000);
  3788. }
  3789. function formatTraffic(bytesPerSec) {
  3790. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  3791. const kb = bytesPerSec / 1024;
  3792. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  3793. const mb = kb / 1024;
  3794. return `${mb.toFixed(2)} MB/s`;
  3795. }
  3796. function toggleSidebar() {
  3797. const sb = document.getElementById('sidebar');
  3798. sb.classList.toggle('-translate-x-full');
  3799. }
  3800. // ======================== EoIP (Ethernet over IP) ========================
  3801. async function loadEoIP(populate = true) {
  3802. try {
  3803. const res = await fetch(`${API_BASE}/vpn/eoip`);
  3804. const data = await res.json();
  3805. state.eoipTunnels = Array.isArray(data) ? data : [];
  3806. const badge = document.getElementById('eoip-count-badge');
  3807. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  3808. const sideBadge = document.getElementById('badge-eoip-count');
  3809. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  3810. renderEoIPTunnels();
  3811. } catch (err) {
  3812. console.error('Failed to load EoIP:', err);
  3813. }
  3814. }
  3815. function renderEoIPTunnels() {
  3816. const tbody = document.getElementById('eoip-table-body');
  3817. const empty = document.getElementById('eoip-empty');
  3818. if (!tbody) return;
  3819. tbody.innerHTML = '';
  3820. const tunnels = state.eoipTunnels || [];
  3821. if (tunnels.length === 0) {
  3822. empty?.classList.remove('hidden');
  3823. return;
  3824. }
  3825. empty?.classList.add('hidden');
  3826. tunnels.forEach(t => {
  3827. const tr = document.createElement('tr');
  3828. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  3829. tr.innerHTML = `
  3830. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  3831. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  3832. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  3833. <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>
  3834. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  3835. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  3836. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  3837. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  3838. <td class="py-2.5 px-3 font-mono text-[11px]">
  3839. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  3840. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  3841. </td>
  3842. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  3843. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3844. <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>
  3845. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3846. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  3847. </td>
  3848. `;
  3849. tbody.appendChild(tr);
  3850. });
  3851. }
  3852. function openAddEoIPModal() {
  3853. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  3854. document.getElementById('eoip-modal-id').value = '';
  3855. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  3856. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  3857. document.getElementById('eoip-modal-remote').value = '';
  3858. document.getElementById('eoip-modal-ip').value = '';
  3859. document.getElementById('eoip-modal-local').value = '';
  3860. document.getElementById('eoip-modal-mac').value = '';
  3861. document.getElementById('eoip-modal-mtu').value = '1500';
  3862. document.getElementById('eoip-modal-comment').value = '';
  3863. document.getElementById('eoip-modal-clampmss').checked = true;
  3864. document.getElementById('eoip-modal-disabled').checked = false;
  3865. document.getElementById('eoip-modal').classList.remove('hidden');
  3866. }
  3867. function openEditEoIPModal(id) {
  3868. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  3869. if (!t) return;
  3870. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  3871. document.getElementById('eoip-modal-id').value = t.id;
  3872. document.getElementById('eoip-modal-name').value = t.name;
  3873. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  3874. document.getElementById('eoip-modal-remote').value = t.remote_address;
  3875. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  3876. document.getElementById('eoip-modal-local').value = t.local_address || '';
  3877. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  3878. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  3879. document.getElementById('eoip-modal-comment').value = t.comment || '';
  3880. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  3881. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  3882. document.getElementById('eoip-modal').classList.remove('hidden');
  3883. }
  3884. function closeEoIPModal() {
  3885. document.getElementById('eoip-modal').classList.add('hidden');
  3886. }
  3887. async function submitSaveEoIP(e) {
  3888. e.preventDefault();
  3889. const id = document.getElementById('eoip-modal-id').value;
  3890. const name = document.getElementById('eoip-modal-name').value.trim();
  3891. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  3892. const remote = document.getElementById('eoip-modal-remote').value.trim();
  3893. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  3894. const local = document.getElementById('eoip-modal-local').value.trim();
  3895. const mac = document.getElementById('eoip-modal-mac').value.trim();
  3896. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  3897. const comment = document.getElementById('eoip-modal-comment').value.trim();
  3898. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  3899. const disabled = document.getElementById('eoip-modal-disabled').checked;
  3900. try {
  3901. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  3902. method: 'POST',
  3903. headers: { 'Content-Type': 'application/json' },
  3904. body: JSON.stringify({
  3905. id,
  3906. name,
  3907. tunnel_id: tunnelId,
  3908. remote_address: remote,
  3909. ip_address: ipAddress,
  3910. local_address: local,
  3911. mac_address: mac,
  3912. mtu,
  3913. clamp_mss: clampMss,
  3914. comment,
  3915. disabled
  3916. })
  3917. });
  3918. if (res.ok) {
  3919. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  3920. closeEoIPModal();
  3921. loadEoIP(false);
  3922. fetchData(false);
  3923. } else {
  3924. const err = await res.json();
  3925. showToast('Error', err.message, 'error');
  3926. }
  3927. } catch (err) {
  3928. showToast('Error', err.message, 'error');
  3929. }
  3930. }
  3931. async function toggleEoIPState(id, disabled) {
  3932. try {
  3933. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  3934. method: 'POST',
  3935. headers: { 'Content-Type': 'application/json' },
  3936. body: JSON.stringify({ disabled })
  3937. });
  3938. if (res.ok) {
  3939. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  3940. loadEoIP(false);
  3941. fetchData(false);
  3942. }
  3943. } catch (err) {
  3944. showToast('Error', err.message, 'error');
  3945. }
  3946. }
  3947. async function deleteEoIP(id) {
  3948. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  3949. try {
  3950. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3951. if (res.ok) {
  3952. showToast('Deleted', 'EoIP tunnel removed', 'success');
  3953. loadEoIP(false);
  3954. fetchData(false);
  3955. }
  3956. } catch (err) {
  3957. showToast('Error', err.message, 'error');
  3958. }
  3959. }
  3960. // ======================== PPP Central Hub & Servers ========================
  3961. function switchPPPSubTab(tab) {
  3962. state.pppSubTab = tab;
  3963. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  3964. tabs.forEach(t => {
  3965. const panel = document.getElementById(`ppp-subtab-${t}`);
  3966. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  3967. if (panel) {
  3968. if (t === tab) panel.classList.remove('hidden');
  3969. else panel.classList.add('hidden');
  3970. }
  3971. if (btn) {
  3972. if (t === tab) {
  3973. 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';
  3974. } else {
  3975. 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';
  3976. }
  3977. }
  3978. });
  3979. const addBtn = document.getElementById('ppp-primary-add-btn');
  3980. if (addBtn) {
  3981. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  3982. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  3983. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  3984. else addBtn.innerHTML = '<span>Save Config</span>';
  3985. }
  3986. if (tab === 'active') loadPPPSessions();
  3987. }
  3988. function openCurrentPPPModal() {
  3989. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  3990. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  3991. else if (state.pppSubTab === 'active') loadPPPSessions();
  3992. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  3993. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  3994. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  3995. }
  3996. async function loadPPP(populateDropdowns = true) {
  3997. await Promise.all([
  3998. loadPPPSecrets(),
  3999. loadPPPProfiles(),
  4000. loadPPPServers(),
  4001. loadPPPSessions()
  4002. ]);
  4003. }
  4004. async function loadPPPSecrets() {
  4005. try {
  4006. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  4007. const data = await res.json();
  4008. state.pppSecrets = Array.isArray(data) ? data : [];
  4009. const b = document.getElementById('ppp-badge-secrets');
  4010. if (b) b.innerText = state.pppSecrets.length;
  4011. const b2 = document.getElementById('secrets-count-badge');
  4012. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  4013. renderPPPSecrets();
  4014. } catch (err) {
  4015. console.error('Failed to load PPP secrets:', err);
  4016. }
  4017. }
  4018. function renderPPPSecrets() {
  4019. const tbody = document.getElementById('secrets-table-body');
  4020. const empty = document.getElementById('secrets-empty');
  4021. if (!tbody) return;
  4022. tbody.innerHTML = '';
  4023. const secrets = state.pppSecrets || [];
  4024. if (secrets.length === 0) {
  4025. empty?.classList.remove('hidden');
  4026. return;
  4027. }
  4028. empty?.classList.add('hidden');
  4029. secrets.forEach(s => {
  4030. const tr = document.createElement('tr');
  4031. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  4032. tr.innerHTML = `
  4033. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  4034. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  4035. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  4036. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  4037. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  4038. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  4039. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  4040. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4041. <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>
  4042. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4043. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  4044. </td>
  4045. `;
  4046. tbody.appendChild(tr);
  4047. });
  4048. }
  4049. async function loadPPPProfiles() {
  4050. try {
  4051. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  4052. const data = await res.json();
  4053. state.pppProfiles = Array.isArray(data) ? data : [];
  4054. const b = document.getElementById('ppp-badge-profiles');
  4055. if (b) b.innerText = state.pppProfiles.length;
  4056. const b2 = document.getElementById('profiles-count-badge');
  4057. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  4058. // Populate profile selects across modals
  4059. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  4060. selects.forEach(sid => {
  4061. const el = document.getElementById(sid);
  4062. if (!el) return;
  4063. const cur = el.value;
  4064. el.innerHTML = '';
  4065. state.pppProfiles.forEach(p => {
  4066. const opt = document.createElement('option');
  4067. opt.value = p.name;
  4068. opt.innerText = `${p.name} (${p.remote_address})`;
  4069. if (p.name === cur) opt.selected = true;
  4070. el.appendChild(opt);
  4071. });
  4072. });
  4073. renderPPPProfiles();
  4074. } catch (err) {
  4075. console.error('Failed to load PPP profiles:', err);
  4076. }
  4077. }
  4078. function renderPPPProfiles() {
  4079. const tbody = document.getElementById('profiles-table-body');
  4080. if (!tbody) return;
  4081. tbody.innerHTML = '';
  4082. (state.pppProfiles || []).forEach(p => {
  4083. const isDefault = p.name.startsWith('default');
  4084. const tr = document.createElement('tr');
  4085. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  4086. tr.innerHTML = `
  4087. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  4088. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  4089. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  4090. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  4091. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  4092. <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>
  4093. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  4094. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  4095. ${!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>`}
  4096. </td>
  4097. `;
  4098. tbody.appendChild(tr);
  4099. });
  4100. }
  4101. async function loadPPPServers() {
  4102. try {
  4103. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  4104. fetch(`${API_BASE}/vpn/servers/pppoe`),
  4105. fetch(`${API_BASE}/vpn/servers/pptp`),
  4106. fetch(`${API_BASE}/vpn/servers/l2tp`),
  4107. fetch(`${API_BASE}/vpn/servers/ipsec`)
  4108. ]);
  4109. if (pppoeRes.ok) {
  4110. state.pppoeServer = await pppoeRes.json();
  4111. const s = state.pppoeServer;
  4112. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  4113. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  4114. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  4115. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  4116. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  4117. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  4118. const pill = document.getElementById('pppoe-server-status-pill');
  4119. if (pill) {
  4120. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  4121. 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';
  4122. }
  4123. setDotBadge('ppp-badge-pppoe-state', s.running);
  4124. }
  4125. if (pptpRes.ok) {
  4126. state.pptpServer = await pptpRes.json();
  4127. const s = state.pptpServer;
  4128. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  4129. document.getElementById('pptp-server-port').value = s.port || 1723;
  4130. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  4131. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  4132. const pill = document.getElementById('pptp-server-status-pill');
  4133. if (pill) {
  4134. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  4135. 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';
  4136. }
  4137. setDotBadge('ppp-badge-pptp-state', s.running);
  4138. }
  4139. if (l2tpRes.ok) {
  4140. state.l2tpServer = await l2tpRes.json();
  4141. const s = state.l2tpServer;
  4142. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  4143. document.getElementById('l2tp-server-port').value = s.port || 1701;
  4144. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  4145. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  4146. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  4147. const pill = document.getElementById('l2tp-server-status-pill');
  4148. if (pill) {
  4149. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  4150. 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';
  4151. }
  4152. setDotBadge('ppp-badge-l2tp-state', s.running);
  4153. }
  4154. if (ipsecRes.ok) {
  4155. state.ipsecServer = await ipsecRes.json();
  4156. const s = state.ipsecServer;
  4157. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  4158. if (modalEn) modalEn.checked = !!s.enabled;
  4159. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  4160. if (modalPsk) modalPsk.value = s.preshared_key || '';
  4161. const modalPool = document.getElementById('modal-ipsec-server-pool');
  4162. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  4163. const modalDns = document.getElementById('modal-ipsec-server-dns');
  4164. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  4165. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  4166. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  4167. const pill = document.getElementById('modal-ipsec-server-status');
  4168. if (pill) {
  4169. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  4170. 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';
  4171. }
  4172. }
  4173. } catch (err) {
  4174. console.error('Failed to load VPN servers:', err);
  4175. }
  4176. }
  4177. async function loadPPPSessions() {
  4178. try {
  4179. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  4180. const data = await res.json();
  4181. state.pppActiveSessions = Array.isArray(data) ? data : [];
  4182. const b = document.getElementById('ppp-badge-active');
  4183. if (b) b.innerText = state.pppActiveSessions.length;
  4184. const sideB = document.getElementById('badge-ppp-sessions');
  4185. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  4186. renderPPPSessions();
  4187. } catch (err) {
  4188. console.error('Failed to load active PPP sessions:', err);
  4189. }
  4190. }
  4191. function renderPPPSessions() {
  4192. const tbody = document.getElementById('active-ppp-table-body');
  4193. const empty = document.getElementById('active-ppp-empty');
  4194. if (!tbody) return;
  4195. tbody.innerHTML = '';
  4196. const list = state.pppActiveSessions || [];
  4197. if (list.length === 0) {
  4198. empty?.classList.remove('hidden');
  4199. return;
  4200. }
  4201. empty?.classList.add('hidden');
  4202. list.forEach(s => {
  4203. const tr = document.createElement('tr');
  4204. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  4205. tr.innerHTML = `
  4206. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  4207. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  4208. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  4209. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  4210. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  4211. <td class="py-2.5 px-3 text-[11px]">
  4212. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  4213. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  4214. </td>
  4215. <td class="py-2.5 px-3 text-right font-sans">
  4216. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  4217. </td>
  4218. `;
  4219. tbody.appendChild(tr);
  4220. });
  4221. }
  4222. async function disconnectPPPSession(iface) {
  4223. if (!confirm(`Disconnect session ${iface}?`)) return;
  4224. try {
  4225. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  4226. if (res.ok) {
  4227. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  4228. loadPPPSessions();
  4229. }
  4230. } catch (err) {
  4231. showToast('Error', err.message, 'error');
  4232. }
  4233. }
  4234. // PPP Secret Modal handlers
  4235. function openAddPPPSecretModal() {
  4236. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  4237. document.getElementById('secret-modal-id').value = '';
  4238. document.getElementById('secret-modal-name').value = '';
  4239. document.getElementById('secret-modal-password').value = '';
  4240. document.getElementById('secret-modal-service').value = 'any';
  4241. document.getElementById('secret-modal-profile').value = 'default';
  4242. document.getElementById('secret-modal-local').value = '';
  4243. document.getElementById('secret-modal-remote').value = '';
  4244. document.getElementById('secret-modal-comment').value = '';
  4245. document.getElementById('secret-modal-disabled').checked = false;
  4246. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  4247. }
  4248. function openEditPPPSecretModal(id) {
  4249. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  4250. if (!s) return;
  4251. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  4252. document.getElementById('secret-modal-id').value = s.id;
  4253. document.getElementById('secret-modal-name').value = s.name;
  4254. document.getElementById('secret-modal-password').value = s.password;
  4255. document.getElementById('secret-modal-service').value = s.service || 'any';
  4256. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  4257. document.getElementById('secret-modal-local').value = s.local_address || '';
  4258. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  4259. document.getElementById('secret-modal-comment').value = s.comment || '';
  4260. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  4261. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  4262. }
  4263. function closePPPSecretModal() {
  4264. document.getElementById('ppp-secret-modal').classList.add('hidden');
  4265. }
  4266. async function submitSavePPPSecret(e) {
  4267. e.preventDefault();
  4268. const id = document.getElementById('secret-modal-id').value;
  4269. const name = document.getElementById('secret-modal-name').value.trim();
  4270. const password = document.getElementById('secret-modal-password').value.trim();
  4271. const service = document.getElementById('secret-modal-service').value;
  4272. const profile = document.getElementById('secret-modal-profile').value;
  4273. const local = document.getElementById('secret-modal-local').value.trim();
  4274. const remote = document.getElementById('secret-modal-remote').value.trim();
  4275. const comment = document.getElementById('secret-modal-comment').value.trim();
  4276. const disabled = document.getElementById('secret-modal-disabled').checked;
  4277. try {
  4278. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  4279. method: 'POST',
  4280. headers: { 'Content-Type': 'application/json' },
  4281. body: JSON.stringify({
  4282. id,
  4283. name,
  4284. password,
  4285. service,
  4286. profile,
  4287. local_address: local,
  4288. remote_address: remote,
  4289. comment,
  4290. disabled
  4291. })
  4292. });
  4293. if (res.ok) {
  4294. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  4295. closePPPSecretModal();
  4296. loadPPPSecrets();
  4297. } else {
  4298. const err = await res.json();
  4299. showToast('Error', err.message, 'error');
  4300. }
  4301. } catch (err) {
  4302. showToast('Error', err.message, 'error');
  4303. }
  4304. }
  4305. async function togglePPPSecretState(id, disabled) {
  4306. try {
  4307. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  4308. method: 'POST',
  4309. headers: { 'Content-Type': 'application/json' },
  4310. body: JSON.stringify({ disabled })
  4311. });
  4312. if (res.ok) {
  4313. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  4314. loadPPPSecrets();
  4315. }
  4316. } catch (err) {
  4317. showToast('Error', err.message, 'error');
  4318. }
  4319. }
  4320. async function deletePPPSecret(id) {
  4321. if (!confirm('Are you sure you want to delete this secret account?')) return;
  4322. try {
  4323. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4324. if (res.ok) {
  4325. showToast('Deleted', 'Secret account removed', 'success');
  4326. loadPPPSecrets();
  4327. }
  4328. } catch (err) {
  4329. showToast('Error', err.message, 'error');
  4330. }
  4331. }
  4332. // PPP Profile Modal handlers
  4333. function openAddPPPProfileModal() {
  4334. document.getElementById('profile-modal-name').value = '';
  4335. document.getElementById('profile-modal-local').value = '10.10.10.1';
  4336. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  4337. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  4338. document.getElementById('profile-modal-encryption').value = 'required';
  4339. document.getElementById('profile-modal-onlyone').checked = true;
  4340. document.getElementById('profile-modal-comment').value = '';
  4341. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  4342. }
  4343. function closePPPProfileModal() {
  4344. document.getElementById('ppp-profile-modal').classList.add('hidden');
  4345. }
  4346. async function submitSavePPPProfile(e) {
  4347. e.preventDefault();
  4348. const name = document.getElementById('profile-modal-name').value.trim();
  4349. const local = document.getElementById('profile-modal-local').value.trim();
  4350. const remote = document.getElementById('profile-modal-remote').value.trim();
  4351. const dns = document.getElementById('profile-modal-dns').value.trim();
  4352. const enc = document.getElementById('profile-modal-encryption').value;
  4353. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  4354. const comment = document.getElementById('profile-modal-comment').value.trim();
  4355. try {
  4356. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  4357. method: 'POST',
  4358. headers: { 'Content-Type': 'application/json' },
  4359. body: JSON.stringify({
  4360. id: name,
  4361. name,
  4362. local_address: local,
  4363. remote_address: remote,
  4364. dns_servers: dns,
  4365. use_encryption: enc,
  4366. only_one: onlyone,
  4367. comment
  4368. })
  4369. });
  4370. if (res.ok) {
  4371. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  4372. closePPPProfileModal();
  4373. loadPPPProfiles();
  4374. } else {
  4375. const err = await res.json();
  4376. showToast('Error', err.message, 'error');
  4377. }
  4378. } catch (err) {
  4379. showToast('Error', err.message, 'error');
  4380. }
  4381. }
  4382. async function deletePPPProfile(name) {
  4383. if (!confirm(`Delete PPP profile ${name}?`)) return;
  4384. try {
  4385. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  4386. if (res.ok) {
  4387. showToast('Deleted', 'Profile removed', 'success');
  4388. loadPPPProfiles();
  4389. } else {
  4390. const err = await res.json();
  4391. showToast('Error', err.message, 'error');
  4392. }
  4393. } catch (err) {
  4394. showToast('Error', err.message, 'error');
  4395. }
  4396. }
  4397. // Server Config submissions
  4398. async function savePPPoEServerConfig(e) {
  4399. e.preventDefault();
  4400. const enabled = document.getElementById('pppoe-server-enabled').checked;
  4401. const name = document.getElementById('pppoe-server-name').value.trim();
  4402. const iface = document.getElementById('pppoe-server-iface').value;
  4403. const profile = document.getElementById('pppoe-server-profile').value;
  4404. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  4405. const onesession = document.getElementById('pppoe-server-onesession').checked;
  4406. try {
  4407. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  4408. method: 'POST',
  4409. headers: { 'Content-Type': 'application/json' },
  4410. body: JSON.stringify({
  4411. enabled,
  4412. service_name: name,
  4413. interface: iface,
  4414. default_profile: profile,
  4415. max_mtu: mtu,
  4416. max_mru: mtu,
  4417. one_session_per_host: onesession
  4418. })
  4419. });
  4420. if (res.ok) {
  4421. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  4422. loadPPPServers();
  4423. fetchData(false);
  4424. } else {
  4425. const err = await res.json();
  4426. showToast('Error', err.message, 'error');
  4427. }
  4428. } catch (err) {
  4429. showToast('Error', err.message, 'error');
  4430. }
  4431. }
  4432. async function savePPTPServerConfig(e) {
  4433. e.preventDefault();
  4434. const enabled = document.getElementById('pptp-server-enabled').checked;
  4435. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  4436. const profile = document.getElementById('pptp-server-profile').value;
  4437. const mppe = document.getElementById('pptp-server-mppe').checked;
  4438. try {
  4439. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  4440. method: 'POST',
  4441. headers: { 'Content-Type': 'application/json' },
  4442. body: JSON.stringify({
  4443. enabled,
  4444. port,
  4445. default_profile: profile,
  4446. require_mppe: mppe
  4447. })
  4448. });
  4449. if (res.ok) {
  4450. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  4451. loadPPPServers();
  4452. fetchData(false);
  4453. } else {
  4454. const err = await res.json();
  4455. showToast('Error', err.message, 'error');
  4456. }
  4457. } catch (err) {
  4458. showToast('Error', err.message, 'error');
  4459. }
  4460. }
  4461. async function saveL2TPServerConfig(e) {
  4462. e.preventDefault();
  4463. const enabled = document.getElementById('l2tp-server-enabled').checked;
  4464. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  4465. const profile = document.getElementById('l2tp-server-profile').value;
  4466. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  4467. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  4468. try {
  4469. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  4470. method: 'POST',
  4471. headers: { 'Content-Type': 'application/json' },
  4472. body: JSON.stringify({
  4473. enabled,
  4474. port,
  4475. default_profile: profile,
  4476. use_ipsec: useipsec,
  4477. ipsec_secret: psk
  4478. })
  4479. });
  4480. if (res.ok) {
  4481. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  4482. loadPPPServers();
  4483. fetchData(false);
  4484. } else {
  4485. const err = await res.json();
  4486. showToast('Error', err.message, 'error');
  4487. }
  4488. } catch (err) {
  4489. showToast('Error', err.message, 'error');
  4490. }
  4491. }
  4492. // IPSec Server Modal
  4493. function openIPSecServerModal() {
  4494. loadPPPServers();
  4495. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  4496. }
  4497. function closeIPSecServerModal() {
  4498. document.getElementById('ipsec-server-modal').classList.add('hidden');
  4499. }
  4500. async function submitSaveIPSecServer(e) {
  4501. e.preventDefault();
  4502. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  4503. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  4504. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  4505. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  4506. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  4507. try {
  4508. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  4509. method: 'POST',
  4510. headers: { 'Content-Type': 'application/json' },
  4511. body: JSON.stringify({
  4512. enabled,
  4513. preshared_key: psk,
  4514. pool_address: pool,
  4515. dns_servers: dns,
  4516. local_subnet: subnet
  4517. })
  4518. });
  4519. if (res.ok) {
  4520. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  4521. closeIPSecServerModal();
  4522. loadPPPServers();
  4523. fetchData(false);
  4524. } else {
  4525. const err = await res.json();
  4526. showToast('Error', err.message, 'error');
  4527. }
  4528. } catch (err) {
  4529. showToast('Error', err.message, 'error');
  4530. }
  4531. }
  4532. // WireGuard Client Config Viewer
  4533. let currentWGClientConf = '';
  4534. async function openWGClientConfModal(iface, clientIP) {
  4535. try {
  4536. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  4537. method: 'POST',
  4538. headers: { 'Content-Type': 'application/json' },
  4539. body: JSON.stringify({
  4540. interface: iface,
  4541. address: clientIP || '10.10.0.2/32',
  4542. dns: '1.1.1.1, 8.8.8.8'
  4543. })
  4544. });
  4545. if (res.ok) {
  4546. const data = await res.json();
  4547. currentWGClientConf = data.config;
  4548. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  4549. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  4550. } else {
  4551. const err = await res.json();
  4552. showToast('Error', err.message, 'error');
  4553. }
  4554. } catch (err) {
  4555. showToast('Error', err.message, 'error');
  4556. }
  4557. }
  4558. function closeWGClientConfModal() {
  4559. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  4560. }
  4561. function copyWGClientConf() {
  4562. if (!currentWGClientConf) return;
  4563. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  4564. }
  4565. function downloadWGClientConf() {
  4566. if (!currentWGClientConf) return;
  4567. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  4568. const a = document.createElement('a');
  4569. a.href = URL.createObjectURL(blob);
  4570. a.download = 'wireguard-client.conf';
  4571. document.body.appendChild(a);
  4572. a.click();
  4573. document.body.removeChild(a);
  4574. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  4575. }
  4576. // =========================================================================
  4577. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  4578. // =========================================================================
  4579. state.activeDynSubTab = 'bgp-peers';
  4580. state.activeBgpSubTab = 'bgp-peers';
  4581. state.activeOspfSubTab = 'ospf-ifaces';
  4582. state.bgpInstance = null;
  4583. state.bgpPeers = [];
  4584. state.bgpNets = [];
  4585. state.bgpRoutes = [];
  4586. state.ospfInstance = null;
  4587. state.ospfInterfaces = [];
  4588. state.ospfAreas = [];
  4589. state.ospfNeighbors = [];
  4590. state.ospfRoutes = [];
  4591. function switchBgpSubTab(subTab) {
  4592. state.activeBgpSubTab = subTab;
  4593. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  4594. tabs.forEach(t => {
  4595. const el = document.getElementById(`dyn-subtab-${t}`);
  4596. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  4597. if (el) el.classList.toggle('hidden', t !== subTab);
  4598. if (btn) {
  4599. if (t === subTab) {
  4600. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-purple-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  4601. } else {
  4602. 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';
  4603. }
  4604. }
  4605. });
  4606. }
  4607. function switchOspfSubTab(subTab) {
  4608. state.activeOspfSubTab = subTab;
  4609. const tabs = ['ospf-ifaces', 'ospf-areas', 'ospf-nbrs', 'ospf-routes'];
  4610. tabs.forEach(t => {
  4611. const el = document.getElementById(`dyn-subtab-${t}`);
  4612. const btn = document.getElementById(`ospf-subtab-btn-${t}`);
  4613. if (el) el.classList.toggle('hidden', t !== subTab);
  4614. if (btn) {
  4615. if (t === subTab) {
  4616. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-indigo-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  4617. } else {
  4618. 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';
  4619. }
  4620. }
  4621. });
  4622. }
  4623. function switchDynSubTab(subTab) {
  4624. if (subTab.startsWith('bgp')) {
  4625. if (state.activeTab !== 'bgp') navigate('bgp');
  4626. switchBgpSubTab(subTab);
  4627. } else if (subTab.startsWith('ospf')) {
  4628. if (state.activeTab !== 'ospf') navigate('ospf');
  4629. switchOspfSubTab(subTab);
  4630. }
  4631. }
  4632. async function loadDynamicRouting(showToastMsg = true) {
  4633. try {
  4634. const [sumRes, bgpInstRes, bgpPeersRes, bgpNetsRes, bgpRoutesRes, ospfInstRes, ospfIfacesRes, ospfAreasRes, ospfNbrsRes, ospfRoutesRes] = await Promise.all([
  4635. fetch(`${API_BASE}/routing/dynamic/summary`),
  4636. fetch(`${API_BASE}/routing/bgp/instance`),
  4637. fetch(`${API_BASE}/routing/bgp/peers`),
  4638. fetch(`${API_BASE}/routing/bgp/networks`),
  4639. fetch(`${API_BASE}/routing/bgp/routes`),
  4640. fetch(`${API_BASE}/routing/ospf/instance`),
  4641. fetch(`${API_BASE}/routing/ospf/interfaces`),
  4642. fetch(`${API_BASE}/routing/ospf/areas`),
  4643. fetch(`${API_BASE}/routing/ospf/neighbors`),
  4644. fetch(`${API_BASE}/routing/ospf/routes`)
  4645. ]);
  4646. if (sumRes.ok) state.dynSummary = await sumRes.json();
  4647. if (bgpInstRes.ok) state.bgpInstance = await bgpInstRes.json();
  4648. if (bgpPeersRes.ok) state.bgpPeers = await bgpPeersRes.json();
  4649. if (bgpNetsRes.ok) state.bgpNets = await bgpNetsRes.json();
  4650. if (bgpRoutesRes.ok) state.bgpRoutes = await bgpRoutesRes.json();
  4651. if (ospfInstRes.ok) state.ospfInstance = await ospfInstRes.json();
  4652. if (ospfIfacesRes.ok) state.ospfInterfaces = await ospfIfacesRes.json();
  4653. if (ospfAreasRes.ok) state.ospfAreas = await ospfAreasRes.json();
  4654. if (ospfNbrsRes.ok) state.ospfNeighbors = await ospfNbrsRes.json();
  4655. if (ospfRoutesRes.ok) state.ospfRoutes = await ospfRoutesRes.json();
  4656. renderBgpStatusPill();
  4657. renderBgpPeers();
  4658. renderBgpNetworks();
  4659. renderBgpRoutes();
  4660. renderOspfStatusPill();
  4661. renderOspfInterfaces();
  4662. renderOspfAreas();
  4663. renderOspfNeighbors();
  4664. renderOspfRoutes();
  4665. updateBadges();
  4666. } catch (err) {
  4667. console.error('Failed to load dynamic routing:', err);
  4668. if (showToastMsg) showToast('Error', 'Failed to load dynamic routing telemetry', 'error');
  4669. }
  4670. }
  4671. function renderBgpStatusPill() {
  4672. const pill = document.getElementById('bgp-live-status-pill');
  4673. if (!pill) return;
  4674. const inst = state.bgpInstance;
  4675. if (!inst || !inst.enabled) {
  4676. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  4677. pill.innerText = 'BGP DISABLED';
  4678. } else if (inst.running) {
  4679. 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';
  4680. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  4681. } else {
  4682. 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';
  4683. pill.innerText = 'BGP STARTING...';
  4684. }
  4685. }
  4686. function renderBgpPeers() {
  4687. const tbody = document.getElementById('bgp-peers-table-body');
  4688. const empty = document.getElementById('bgp-peers-empty');
  4689. const countBadge = document.getElementById('bgp-peers-count-badge');
  4690. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  4691. const peers = state.bgpPeers || [];
  4692. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  4693. if (navBadge) navBadge.innerText = peers.length;
  4694. if (peers.length === 0) {
  4695. tbody.innerHTML = '';
  4696. empty.classList.remove('hidden');
  4697. return;
  4698. }
  4699. empty.classList.add('hidden');
  4700. tbody.innerHTML = peers.map(p => {
  4701. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  4702. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  4703. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  4704. let stateBadge = '';
  4705. if (p.disabled) {
  4706. 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>';
  4707. } else if (p.state === 'Established') {
  4708. 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>';
  4709. } else if (p.state === 'Connect' || p.state === 'Active') {
  4710. 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>`;
  4711. } else {
  4712. 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>`;
  4713. }
  4714. return `
  4715. <tr class="hover:bg-slate-800/40 transition">
  4716. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  4717. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  4718. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  4719. <td class="py-2.5 px-3 font-bold text-slate-200">AS ${p.remote_as}</td>
  4720. <td class="py-2.5 px-3">${stateBadge}</td>
  4721. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  4722. <td class="py-2.5 px-3 text-slate-300">
  4723. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  4724. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  4725. </td>
  4726. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  4727. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  4728. <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'}">
  4729. ${p.disabled ? 'Enable' : 'Disable'}
  4730. </button>
  4731. <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">
  4732. Edit
  4733. </button>
  4734. <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">
  4735. Delete
  4736. </button>
  4737. </td>
  4738. </tr>
  4739. `;
  4740. }).join('');
  4741. }
  4742. function renderBgpNetworks() {
  4743. const tbody = document.getElementById('bgp-nets-table-body');
  4744. const empty = document.getElementById('bgp-nets-empty');
  4745. const countBadge = document.getElementById('bgp-nets-count-badge');
  4746. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  4747. const nets = state.bgpNets || [];
  4748. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  4749. if (navBadge) navBadge.innerText = nets.length;
  4750. if (nets.length === 0) {
  4751. tbody.innerHTML = '';
  4752. empty.classList.remove('hidden');
  4753. return;
  4754. }
  4755. empty.classList.add('hidden');
  4756. tbody.innerHTML = nets.map(n => `
  4757. <tr class="hover:bg-slate-800/40 transition">
  4758. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  4759. <td class="py-2.5 px-3">
  4760. ${n.disabled
  4761. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  4762. : '<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>'}
  4763. </td>
  4764. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  4765. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  4766. <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">
  4767. Delete
  4768. </button>
  4769. </td>
  4770. </tr>
  4771. `).join('');
  4772. }
  4773. function renderBgpRoutes() {
  4774. const tbody = document.getElementById('bgp-routes-table-body');
  4775. const empty = document.getElementById('bgp-routes-empty');
  4776. const countBadge = document.getElementById('bgp-routes-count-badge');
  4777. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  4778. const routes = state.bgpRoutes || [];
  4779. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  4780. if (navBadge) navBadge.innerText = routes.length;
  4781. if (routes.length === 0) {
  4782. tbody.innerHTML = '';
  4783. empty.classList.remove('hidden');
  4784. return;
  4785. }
  4786. empty.classList.add('hidden');
  4787. tbody.innerHTML = routes.map(r => `
  4788. <tr class="hover:bg-slate-800/40 transition">
  4789. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  4790. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  4791. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  4792. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  4793. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  4794. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  4795. </tr>
  4796. `).join('');
  4797. }
  4798. function renderOspfStatusPill() {
  4799. const pill = document.getElementById('ospf-live-status-pill');
  4800. if (!pill) return;
  4801. const inst = state.ospfInstance;
  4802. if (!inst || !inst.enabled) {
  4803. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  4804. pill.innerText = 'OSPF DISABLED';
  4805. } else if (inst.running) {
  4806. 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';
  4807. pill.innerText = `OSPF ACTIVE (ID: ${inst.router_id || 'Auto'})`;
  4808. } else {
  4809. 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';
  4810. pill.innerText = 'OSPF STARTING...';
  4811. }
  4812. }
  4813. function renderOspfInterfaces() {
  4814. const tbody = document.getElementById('ospf-ifaces-table-body');
  4815. const empty = document.getElementById('ospf-ifaces-empty');
  4816. const countBadge = document.getElementById('ospf-ifaces-count-badge');
  4817. const navBadge = document.getElementById('dyn-badge-ospf-ifaces');
  4818. const ifaces = state.ospfInterfaces || [];
  4819. if (countBadge) countBadge.innerText = `${ifaces.length} Interfaces`;
  4820. if (navBadge) navBadge.innerText = ifaces.length;
  4821. if (ifaces.length === 0) {
  4822. tbody.innerHTML = '';
  4823. empty.classList.remove('hidden');
  4824. return;
  4825. }
  4826. empty.classList.add('hidden');
  4827. tbody.innerHTML = ifaces.map(i => {
  4828. let flagA = !i.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  4829. let flagP = i.passive ? '<span class="text-amber-400 font-bold ml-1" title="Passive">P</span>' : '';
  4830. let flagX = i.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  4831. return `
  4832. <tr class="hover:bg-slate-800/40 transition">
  4833. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagP}${flagX}</td>
  4834. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(i.network)}</td>
  4835. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(i.area)}</td>
  4836. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(i.interface || 'Any')}</td>
  4837. <td class="py-2.5 px-3 text-slate-300">${i.cost}</td>
  4838. <td class="py-2.5 px-3 text-slate-300">${i.priority}</td>
  4839. <td class="py-2.5 px-3 text-slate-400">${i.hello_interval}s / ${i.dead_interval}s</td>
  4840. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(i.auth_type || 'none')}</td>
  4841. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(i.comment || '')}</td>
  4842. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  4843. <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'}">
  4844. ${i.disabled ? 'Enable' : 'Disable'}
  4845. </button>
  4846. <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">
  4847. Edit
  4848. </button>
  4849. <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">
  4850. Delete
  4851. </button>
  4852. </td>
  4853. </tr>
  4854. `;
  4855. }).join('');
  4856. }
  4857. function renderOspfAreas() {
  4858. const tbody = document.getElementById('ospf-areas-table-body');
  4859. const countBadge = document.getElementById('ospf-areas-count-badge');
  4860. const navBadge = document.getElementById('dyn-badge-ospf-areas');
  4861. const areas = state.ospfAreas || [];
  4862. if (countBadge) countBadge.innerText = `${areas.length} Areas`;
  4863. if (navBadge) navBadge.innerText = areas.length;
  4864. tbody.innerHTML = areas.map(a => `
  4865. <tr class="hover:bg-slate-800/40 transition">
  4866. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(a.name)}</td>
  4867. <td class="py-2.5 px-3 font-bold text-indigo-300">${escapeHtml(a.area_id)}</td>
  4868. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(a.area_type || 'default')}</td>
  4869. <td class="py-2.5 px-3 text-slate-400 font-sans">${escapeHtml(a.comment || '')}</td>
  4870. <td class="py-2.5 px-3 text-right font-sans">
  4871. <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">
  4872. Delete
  4873. </button>
  4874. </td>
  4875. </tr>
  4876. `).join('');
  4877. }
  4878. function renderOspfNeighbors() {
  4879. const tbody = document.getElementById('ospf-nbrs-table-body');
  4880. const empty = document.getElementById('ospf-nbrs-empty');
  4881. const countBadge = document.getElementById('ospf-nbrs-count-badge');
  4882. const navBadge = document.getElementById('dyn-badge-ospf-nbrs');
  4883. const nbrs = state.ospfNeighbors || [];
  4884. if (countBadge) countBadge.innerText = `${nbrs.length} Neighbors`;
  4885. if (navBadge) navBadge.innerText = nbrs.length;
  4886. if (nbrs.length === 0) {
  4887. tbody.innerHTML = '';
  4888. empty.classList.remove('hidden');
  4889. return;
  4890. }
  4891. empty.classList.add('hidden');
  4892. tbody.innerHTML = nbrs.map(n => {
  4893. let stateBadge = '';
  4894. if (n.state && (n.state.startsWith('Full') || n.state.includes('DR') || n.state.includes('Backup'))) {
  4895. 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>`;
  4896. } else {
  4897. 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>`;
  4898. }
  4899. return `
  4900. <tr class="hover:bg-slate-800/40 transition">
  4901. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(n.neighbor_id)}</td>
  4902. <td class="py-2.5 px-3 text-indigo-300 font-bold">${escapeHtml(n.address)}</td>
  4903. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(n.interface)}</td>
  4904. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.area || '0.0.0.0')}</td>
  4905. <td class="py-2.5 px-3">${stateBadge}</td>
  4906. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.dead_timer || '-')}</td>
  4907. </tr>
  4908. `;
  4909. }).join('');
  4910. }
  4911. function renderOspfRoutes() {
  4912. const tbody = document.getElementById('ospf-routes-table-body');
  4913. const empty = document.getElementById('ospf-routes-empty');
  4914. const countBadge = document.getElementById('ospf-routes-count-badge');
  4915. const navBadge = document.getElementById('dyn-badge-ospf-routes');
  4916. const routes = state.ospfRoutes || [];
  4917. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  4918. if (navBadge) navBadge.innerText = routes.length;
  4919. if (routes.length === 0) {
  4920. tbody.innerHTML = '';
  4921. empty.classList.remove('hidden');
  4922. return;
  4923. }
  4924. empty.classList.add('hidden');
  4925. tbody.innerHTML = routes.map(r => `
  4926. <tr class="hover:bg-slate-800/40 transition">
  4927. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(r.prefix)}</td>
  4928. <td class="py-2.5 px-3 text-slate-300">${escapeHtml(r.route_type || 'Network')}</td>
  4929. <td class="py-2.5 px-3 text-slate-300">${r.cost}</td>
  4930. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(r.area || '0.0.0.0')}</td>
  4931. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(r.next_hop || r.interface || '-')}</td>
  4932. </tr>
  4933. `).join('');
  4934. }
  4935. // BGP Modals & Actions
  4936. function openBgpInstanceModal() {
  4937. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  4938. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  4939. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  4940. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  4941. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  4942. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  4943. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  4944. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  4945. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  4946. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  4947. }
  4948. function closeBgpInstanceModal() {
  4949. document.getElementById('bgp-instance-modal').classList.add('hidden');
  4950. }
  4951. async function submitBgpInstance(e) {
  4952. e.preventDefault();
  4953. const payload = {
  4954. enabled: document.getElementById('modal-bgp-enabled').checked,
  4955. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  4956. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  4957. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  4958. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  4959. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  4960. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  4961. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  4962. };
  4963. try {
  4964. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  4965. method: 'POST',
  4966. headers: { 'Content-Type': 'application/json' },
  4967. body: JSON.stringify(payload)
  4968. });
  4969. if (res.ok) {
  4970. closeBgpInstanceModal();
  4971. showToast('Success', 'BGP instance configuration updated', 'success');
  4972. loadDynamicRouting();
  4973. } else {
  4974. const err = await res.json();
  4975. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  4976. }
  4977. } catch (err) {
  4978. showToast('Error', err.message, 'error');
  4979. }
  4980. }
  4981. function openAddBgpPeerModal() {
  4982. document.getElementById('bgp-peer-form').reset();
  4983. document.getElementById('modal-bgp-peer-id').value = '';
  4984. document.getElementById('bgp-peer-modal-title').innerText = 'Add BGP Peer Connection';
  4985. document.getElementById('modal-bgp-peer-nexthop-self').checked = true;
  4986. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  4987. }
  4988. function openEditBgpPeerModal(id) {
  4989. const p = (state.bgpPeers || []).find(item => item.id === id);
  4990. if (!p) return;
  4991. document.getElementById('modal-bgp-peer-id').value = p.id;
  4992. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  4993. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  4994. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  4995. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  4996. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  4997. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  4998. document.getElementById('modal-bgp-peer-nexthop-self').checked = !!p.nexthop_self;
  4999. document.getElementById('modal-bgp-peer-passive').checked = !!p.passive;
  5000. document.getElementById('modal-bgp-peer-disabled').checked = !!p.disabled;
  5001. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  5002. document.getElementById('bgp-peer-modal-title').innerText = 'Edit BGP Peer Connection';
  5003. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  5004. }
  5005. function closeBgpPeerModal() {
  5006. document.getElementById('bgp-peer-modal').classList.add('hidden');
  5007. }
  5008. async function submitBgpPeer(e) {
  5009. e.preventDefault();
  5010. const payload = {
  5011. id: document.getElementById('modal-bgp-peer-id').value,
  5012. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  5013. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  5014. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10),
  5015. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  5016. password: document.getElementById('modal-bgp-peer-password').value,
  5017. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  5018. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-self').checked,
  5019. passive: document.getElementById('modal-bgp-peer-passive').checked,
  5020. disabled: document.getElementById('modal-bgp-peer-disabled').checked,
  5021. comment: document.getElementById('modal-bgp-peer-comment').value.trim()
  5022. };
  5023. try {
  5024. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  5025. method: 'POST',
  5026. headers: { 'Content-Type': 'application/json' },
  5027. body: JSON.stringify(payload)
  5028. });
  5029. if (res.ok) {
  5030. closeBgpPeerModal();
  5031. showToast('Success', 'BGP Peer saved', 'success');
  5032. loadDynamicRouting();
  5033. } else {
  5034. const err = await res.json();
  5035. showToast('Error', err.error || 'Failed to save peer', 'error');
  5036. }
  5037. } catch (err) {
  5038. showToast('Error', err.message, 'error');
  5039. }
  5040. }
  5041. async function deleteBgpPeer(id) {
  5042. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  5043. try {
  5044. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5045. if (res.ok) {
  5046. showToast('Deleted', 'BGP peer removed', 'success');
  5047. loadDynamicRouting();
  5048. }
  5049. } catch (err) {
  5050. showToast('Error', err.message, 'error');
  5051. }
  5052. }
  5053. async function toggleBgpPeerState(id, disabled) {
  5054. try {
  5055. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  5056. method: 'POST',
  5057. headers: { 'Content-Type': 'application/json' },
  5058. body: JSON.stringify({ disabled })
  5059. });
  5060. if (res.ok) {
  5061. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  5062. loadDynamicRouting();
  5063. }
  5064. } catch (err) {
  5065. showToast('Error', err.message, 'error');
  5066. }
  5067. }
  5068. function openAddBgpNetworkModal() {
  5069. document.getElementById('bgp-network-form').reset();
  5070. document.getElementById('modal-bgp-net-id').value = '';
  5071. document.getElementById('bgp-network-modal').classList.remove('hidden');
  5072. }
  5073. function closeBgpNetworkModal() {
  5074. document.getElementById('bgp-network-modal').classList.add('hidden');
  5075. }
  5076. async function submitBgpNetwork(e) {
  5077. e.preventDefault();
  5078. const payload = {
  5079. id: document.getElementById('modal-bgp-net-id').value,
  5080. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  5081. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  5082. disabled: document.getElementById('modal-bgp-net-disabled').checked
  5083. };
  5084. try {
  5085. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  5086. method: 'POST',
  5087. headers: { 'Content-Type': 'application/json' },
  5088. body: JSON.stringify(payload)
  5089. });
  5090. if (res.ok) {
  5091. closeBgpNetworkModal();
  5092. showToast('Success', 'BGP network advertisement saved', 'success');
  5093. loadDynamicRouting();
  5094. } else {
  5095. const err = await res.json();
  5096. showToast('Error', err.error || 'Failed to save network', 'error');
  5097. }
  5098. } catch (err) {
  5099. showToast('Error', err.message, 'error');
  5100. }
  5101. }
  5102. async function deleteBgpNetwork(id) {
  5103. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  5104. try {
  5105. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5106. if (res.ok) {
  5107. showToast('Deleted', 'Network advertisement removed', 'success');
  5108. loadDynamicRouting();
  5109. }
  5110. } catch (err) {
  5111. showToast('Error', err.message, 'error');
  5112. }
  5113. }
  5114. // OSPF Modals & Actions
  5115. function openOspfInstanceModal() {
  5116. const inst = state.ospfInstance || { enabled: false, router_id: '192.168.131.56', default_metric: 10 };
  5117. document.getElementById('modal-ospf-enabled').checked = !!inst.enabled;
  5118. document.getElementById('modal-ospf-router-id').value = inst.router_id || '';
  5119. document.getElementById('modal-ospf-metric').value = inst.default_metric || 10;
  5120. document.getElementById('modal-ospf-redist-conn').checked = !!inst.redistribute_connected;
  5121. document.getElementById('modal-ospf-redist-static').checked = !!inst.redistribute_static;
  5122. document.getElementById('modal-ospf-redist-bgp').checked = !!inst.redistribute_bgp;
  5123. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  5124. }
  5125. function closeOspfInstanceModal() {
  5126. document.getElementById('ospf-instance-modal').classList.add('hidden');
  5127. }
  5128. async function submitOspfInstance(e) {
  5129. e.preventDefault();
  5130. const payload = {
  5131. enabled: document.getElementById('modal-ospf-enabled').checked,
  5132. router_id: document.getElementById('modal-ospf-router-id').value.trim(),
  5133. default_metric: parseInt(document.getElementById('modal-ospf-metric').value, 10),
  5134. redistribute_connected: document.getElementById('modal-ospf-redist-conn').checked,
  5135. redistribute_static: document.getElementById('modal-ospf-redist-static').checked,
  5136. redistribute_bgp: document.getElementById('modal-ospf-redist-bgp').checked
  5137. };
  5138. try {
  5139. const res = await fetch(`${API_BASE}/routing/ospf/instance`, {
  5140. method: 'POST',
  5141. headers: { 'Content-Type': 'application/json' },
  5142. body: JSON.stringify(payload)
  5143. });
  5144. if (res.ok) {
  5145. closeOspfInstanceModal();
  5146. showToast('Success', 'OSPF instance configuration updated', 'success');
  5147. loadDynamicRouting();
  5148. } else {
  5149. const err = await res.json();
  5150. showToast('Error', err.error || 'Failed to update OSPF instance', 'error');
  5151. }
  5152. } catch (err) {
  5153. showToast('Error', err.message, 'error');
  5154. }
  5155. }
  5156. function openAddOspfAreaModal() {
  5157. document.getElementById('ospf-area-form').reset();
  5158. document.getElementById('modal-ospf-area-id').value = '';
  5159. document.getElementById('modal-ospf-area-areaid').value = '0.0.0.0';
  5160. document.getElementById('ospf-area-modal').classList.remove('hidden');
  5161. }
  5162. function closeOspfAreaModal() {
  5163. document.getElementById('ospf-area-modal').classList.add('hidden');
  5164. }
  5165. async function submitOspfArea(e) {
  5166. e.preventDefault();
  5167. const payload = {
  5168. id: document.getElementById('modal-ospf-area-id').value,
  5169. name: document.getElementById('modal-ospf-area-name').value.trim(),
  5170. area_id: document.getElementById('modal-ospf-area-areaid').value.trim(),
  5171. area_type: document.getElementById('modal-ospf-area-type').value,
  5172. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  5173. };
  5174. try {
  5175. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  5176. method: 'POST',
  5177. headers: { 'Content-Type': 'application/json' },
  5178. body: JSON.stringify(payload)
  5179. });
  5180. if (res.ok) {
  5181. closeOspfAreaModal();
  5182. showToast('Success', 'OSPF area saved', 'success');
  5183. loadDynamicRouting();
  5184. } else {
  5185. const err = await res.json();
  5186. showToast('Error', err.error || 'Failed to save area', 'error');
  5187. }
  5188. } catch (err) {
  5189. showToast('Error', err.message, 'error');
  5190. }
  5191. }
  5192. async function deleteOspfArea(id) {
  5193. if (!confirm('Are you sure you want to delete this OSPF area?')) return;
  5194. try {
  5195. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5196. if (res.ok) {
  5197. showToast('Deleted', 'OSPF area removed', 'success');
  5198. loadDynamicRouting();
  5199. }
  5200. } catch (err) {
  5201. showToast('Error', err.message, 'error');
  5202. }
  5203. }
  5204. function populateOspfInterfaceDevices() {
  5205. const select = document.getElementById('modal-ospf-iface-device');
  5206. if (!select) return;
  5207. const current = select.value;
  5208. select.innerHTML = '<option value="">Any matching interface</option>';
  5209. (state.interfaces || []).forEach(iface => {
  5210. select.innerHTML += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)} (${iface.type})</option>`;
  5211. });
  5212. if (current) select.value = current;
  5213. }
  5214. function openAddOspfInterfaceModal() {
  5215. document.getElementById('ospf-interface-form').reset();
  5216. document.getElementById('modal-ospf-iface-id').value = '';
  5217. document.getElementById('modal-ospf-iface-area').value = '0.0.0.0';
  5218. document.getElementById('modal-ospf-iface-cost').value = '10';
  5219. document.getElementById('modal-ospf-iface-priority').value = '1';
  5220. document.getElementById('modal-ospf-iface-hello').value = '10';
  5221. document.getElementById('modal-ospf-iface-dead').value = '40';
  5222. document.getElementById('ospf-interface-modal-title').innerText = 'Add OSPF Interface';
  5223. populateOspfInterfaceDevices();
  5224. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  5225. }
  5226. function openEditOspfInterfaceModal(id) {
  5227. const item = (state.ospfInterfaces || []).find(i => i.id === id);
  5228. if (!item) return;
  5229. populateOspfInterfaceDevices();
  5230. document.getElementById('modal-ospf-iface-id').value = item.id;
  5231. document.getElementById('modal-ospf-iface-net').value = item.network || '';
  5232. document.getElementById('modal-ospf-iface-area').value = item.area || '0.0.0.0';
  5233. document.getElementById('modal-ospf-iface-device').value = item.interface || '';
  5234. document.getElementById('modal-ospf-iface-cost').value = item.cost || 10;
  5235. document.getElementById('modal-ospf-iface-priority').value = item.priority || 1;
  5236. document.getElementById('modal-ospf-iface-hello').value = item.hello_interval || 10;
  5237. document.getElementById('modal-ospf-iface-dead').value = item.dead_interval || 40;
  5238. document.getElementById('modal-ospf-iface-auth-type').value = item.auth_type || 'none';
  5239. document.getElementById('modal-ospf-iface-auth-key').value = item.auth_key || '';
  5240. document.getElementById('modal-ospf-iface-passive').checked = !!item.passive;
  5241. document.getElementById('modal-ospf-iface-disabled').checked = !!item.disabled;
  5242. document.getElementById('modal-ospf-iface-comment').value = item.comment || '';
  5243. document.getElementById('ospf-interface-modal-title').innerText = 'Edit OSPF Interface';
  5244. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  5245. }
  5246. function closeOspfInterfaceModal() {
  5247. document.getElementById('ospf-interface-modal').classList.add('hidden');
  5248. }
  5249. async function submitOspfInterface(e) {
  5250. e.preventDefault();
  5251. const payload = {
  5252. id: document.getElementById('modal-ospf-iface-id').value,
  5253. network: document.getElementById('modal-ospf-iface-net').value.trim(),
  5254. area: document.getElementById('modal-ospf-iface-area').value.trim(),
  5255. interface: document.getElementById('modal-ospf-iface-device').value,
  5256. cost: parseInt(document.getElementById('modal-ospf-iface-cost').value, 10),
  5257. priority: parseInt(document.getElementById('modal-ospf-iface-priority').value, 10),
  5258. hello_interval: parseInt(document.getElementById('modal-ospf-iface-hello').value, 10),
  5259. dead_interval: parseInt(document.getElementById('modal-ospf-iface-dead').value, 10),
  5260. auth_type: document.getElementById('modal-ospf-iface-auth-type').value,
  5261. auth_key: document.getElementById('modal-ospf-iface-auth-key').value,
  5262. passive: document.getElementById('modal-ospf-iface-passive').checked,
  5263. disabled: document.getElementById('modal-ospf-iface-disabled').checked,
  5264. comment: document.getElementById('modal-ospf-iface-comment').value.trim()
  5265. };
  5266. try {
  5267. const res = await fetch(`${API_BASE}/routing/ospf/interfaces`, {
  5268. method: 'POST',
  5269. headers: { 'Content-Type': 'application/json' },
  5270. body: JSON.stringify(payload)
  5271. });
  5272. if (res.ok) {
  5273. closeOspfInterfaceModal();
  5274. showToast('Success', 'OSPF interface template saved', 'success');
  5275. loadDynamicRouting();
  5276. } else {
  5277. const err = await res.json();
  5278. showToast('Error', err.error || 'Failed to save interface', 'error');
  5279. }
  5280. } catch (err) {
  5281. showToast('Error', err.message, 'error');
  5282. }
  5283. }
  5284. async function deleteOspfInterface(id) {
  5285. if (!confirm('Are you sure you want to delete this OSPF interface?')) return;
  5286. try {
  5287. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5288. if (res.ok) {
  5289. showToast('Deleted', 'OSPF interface removed', 'success');
  5290. loadDynamicRouting();
  5291. }
  5292. } catch (err) {
  5293. showToast('Error', err.message, 'error');
  5294. }
  5295. }
  5296. async function toggleOspfInterfaceState(id, disabled) {
  5297. try {
  5298. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}/state`, {
  5299. method: 'POST',
  5300. headers: { 'Content-Type': 'application/json' },
  5301. body: JSON.stringify({ disabled })
  5302. });
  5303. if (res.ok) {
  5304. showToast('Updated', `Interface ${disabled ? 'disabled' : 'enabled'}`, 'success');
  5305. loadDynamicRouting();
  5306. }
  5307. } catch (err) {
  5308. showToast('Error', err.message, 'error');
  5309. }
  5310. }
  5311. // ============================================================================
  5312. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  5313. // ============================================================================
  5314. function switchBridgeSubTab(tab) {
  5315. state.bridgeSubTab = tab;
  5316. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  5317. tabs.forEach(t => {
  5318. const panel = document.getElementById(`bridge-subtab-${t}`);
  5319. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  5320. if (panel) {
  5321. if (t === tab) panel.classList.remove('hidden');
  5322. else panel.classList.add('hidden');
  5323. }
  5324. if (btn) {
  5325. if (t === tab) {
  5326. btn.className = 'px-4 py-2 text-xs font-bold rounded-lg bg-slate-800 text-white shadow-sm transition flex items-center gap-2';
  5327. } else {
  5328. btn.className = 'px-4 py-2 text-xs font-bold rounded-lg text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  5329. }
  5330. }
  5331. });
  5332. const addBtn = document.getElementById('bridge-top-action-btn');
  5333. if (addBtn) {
  5334. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  5335. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  5336. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  5337. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  5338. }
  5339. if (tab === 'hosts') loadBridgeHosts();
  5340. }
  5341. function openCurrentBridgeModal() {
  5342. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  5343. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  5344. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  5345. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  5346. }
  5347. async function loadBridge() {
  5348. try {
  5349. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  5350. fetch(`${API_BASE}/bridge/bridges`),
  5351. fetch(`${API_BASE}/bridge/ports`),
  5352. fetch(`${API_BASE}/bridge/vlans`),
  5353. fetch(`${API_BASE}/bridge/summary`),
  5354. fetch(`${API_BASE}/vpn/eoip`),
  5355. fetch(`${API_BASE}/vlans`)
  5356. ]);
  5357. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  5358. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  5359. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  5360. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  5361. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  5362. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  5363. // Badges & Stats
  5364. const bBridges = document.getElementById('bridge-badge-bridges');
  5365. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  5366. const bPorts = document.getElementById('bridge-badge-ports');
  5367. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  5368. const bVlans = document.getElementById('bridge-badge-vlans');
  5369. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  5370. const bHosts = document.getElementById('bridge-badge-hosts');
  5371. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  5372. const sBr = document.getElementById('bridge-stat-bridges');
  5373. if (sBr) sBr.innerText = (state.bridges || []).length;
  5374. const sPorts = document.getElementById('bridge-stat-ports');
  5375. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  5376. const sHosts = document.getElementById('bridge-stat-hosts');
  5377. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  5378. renderBridges();
  5379. renderBridgePorts();
  5380. renderBridgeVLANs();
  5381. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  5382. } catch (err) {
  5383. console.error('Failed to load bridge subsystem:', err);
  5384. }
  5385. }
  5386. // ----------------- Bridges -----------------
  5387. function renderBridges() {
  5388. const tbody = document.getElementById('bridge-table-body');
  5389. const empty = document.getElementById('bridge-empty-bridges');
  5390. const countBadge = document.getElementById('bridge-count-badge');
  5391. if (!tbody) return;
  5392. tbody.innerHTML = '';
  5393. const bridges = state.bridges || [];
  5394. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  5395. if (bridges.length === 0) {
  5396. empty?.classList.remove('hidden');
  5397. return;
  5398. }
  5399. empty?.classList.add('hidden');
  5400. bridges.forEach((b, idx) => {
  5401. const tr = document.createElement('tr');
  5402. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  5403. // Format IP addresses pill list
  5404. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  5405. if (b.ip_addresses && b.ip_addresses.length > 0) {
  5406. ipsHtml = b.ip_addresses.map(ip => `
  5407. <span class="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-mono bg-sky-950/80 border border-sky-800/40 text-sky-300">
  5408. <span>${ip}</span>
  5409. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  5410. </span>
  5411. `).join(' ');
  5412. }
  5413. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  5414. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  5415. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  5416. tr.innerHTML = `
  5417. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5418. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  5419. <td class="py-2.5 px-3 font-bold text-white text-sm">
  5420. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  5421. </td>
  5422. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  5423. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  5424. <td class="py-2.5 px-3">
  5425. <span class="px-1.5 py-0.5 rounded text-[10px] font-bold ${b.stp === 'none' ? 'bg-slate-800 text-slate-400' : 'bg-sky-950 text-sky-300 border border-sky-800/40'} uppercase">${b.stp}</span>
  5426. </td>
  5427. <td class="py-2.5 px-3 text-center">
  5428. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  5429. </td>
  5430. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  5431. <td class="py-2.5 px-3">
  5432. <span class="px-2 py-0.5 rounded-full text-[10px] font-bold ${b.ports_count > 0 ? 'bg-sky-950 text-sky-400 border border-sky-800/40' : 'bg-slate-800 text-slate-500'} font-mono">${b.ports_count}</span>
  5433. </td>
  5434. <td class="py-2.5 px-3">
  5435. <div class="flex items-center gap-1.5 flex-wrap">
  5436. ${ipsHtml}
  5437. <button onclick="openAddBridgeIPModal('${b.id}', '${b.name}')" class="px-1.5 py-0.2 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700 font-sans" title="Add IP to Bridge">+ IP</button>
  5438. </div>
  5439. </td>
  5440. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  5441. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  5442. </td>
  5443. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  5444. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5445. <button onclick="toggleBridgeState('${b.id}', ${!b.disabled})" class="text-xs ${b.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline font-semibold">${b.disabled ? 'Enable' : 'Disable'}</button>
  5446. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5447. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5448. </td>
  5449. `;
  5450. tbody.appendChild(tr);
  5451. });
  5452. }
  5453. function openAddBridgeModal() {
  5454. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  5455. document.getElementById('bridge-modal-id').value = '';
  5456. document.getElementById('bridge-modal-name').value = 'bridge1';
  5457. document.getElementById('bridge-modal-name').disabled = false;
  5458. document.getElementById('bridge-modal-mtu').value = '1500';
  5459. document.getElementById('bridge-modal-mac').value = '';
  5460. document.getElementById('bridge-modal-stp').value = 'rstp';
  5461. document.getElementById('bridge-modal-priority').value = '32768';
  5462. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  5463. document.getElementById('bridge-modal-pvid').value = '1';
  5464. document.getElementById('bridge-modal-fastforward').checked = true;
  5465. document.getElementById('bridge-modal-comment').value = '';
  5466. document.getElementById('bridge-modal-disabled').checked = false;
  5467. toggleBridgeModalVlanFiltering();
  5468. document.getElementById('bridge-modal').classList.remove('hidden');
  5469. }
  5470. function openEditBridgeModal(id) {
  5471. const b = (state.bridges || []).find(x => x.id === id);
  5472. if (!b) return;
  5473. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  5474. document.getElementById('bridge-modal-id').value = b.id;
  5475. document.getElementById('bridge-modal-name').value = b.name;
  5476. document.getElementById('bridge-modal-name').disabled = true;
  5477. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  5478. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  5479. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  5480. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  5481. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  5482. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  5483. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  5484. document.getElementById('bridge-modal-comment').value = b.comment || '';
  5485. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  5486. toggleBridgeModalVlanFiltering();
  5487. document.getElementById('bridge-modal').classList.remove('hidden');
  5488. }
  5489. function closeBridgeModal() {
  5490. document.getElementById('bridge-modal').classList.add('hidden');
  5491. }
  5492. function toggleBridgeModalVlanFiltering() {
  5493. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  5494. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  5495. if (pvidBox) {
  5496. if (chk) pvidBox.classList.remove('opacity-40');
  5497. else pvidBox.classList.add('opacity-40');
  5498. }
  5499. }
  5500. async function submitSaveBridge(e) {
  5501. e.preventDefault();
  5502. const id = document.getElementById('bridge-modal-id').value;
  5503. const name = document.getElementById('bridge-modal-name').value.trim();
  5504. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  5505. const mac = document.getElementById('bridge-modal-mac').value.trim();
  5506. const stp = document.getElementById('bridge-modal-stp').value;
  5507. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  5508. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  5509. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  5510. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  5511. const comment = document.getElementById('bridge-modal-comment').value.trim();
  5512. const disabled = document.getElementById('bridge-modal-disabled').checked;
  5513. try {
  5514. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  5515. method: 'POST',
  5516. headers: { 'Content-Type': 'application/json' },
  5517. body: JSON.stringify({
  5518. id,
  5519. name,
  5520. mtu,
  5521. mac_address: mac,
  5522. stp,
  5523. priority,
  5524. vlan_filtering: vlanFiltering,
  5525. pvid,
  5526. fast_forward: fastForward,
  5527. comment,
  5528. disabled
  5529. })
  5530. });
  5531. if (res.ok) {
  5532. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  5533. closeBridgeModal();
  5534. loadBridge();
  5535. fetchData(false);
  5536. } else {
  5537. const err = await res.json();
  5538. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  5539. }
  5540. } catch (err) {
  5541. showToast('Error', err.message, 'error');
  5542. }
  5543. }
  5544. async function toggleBridgeState(id, disabled) {
  5545. try {
  5546. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  5547. method: 'POST',
  5548. headers: { 'Content-Type': 'application/json' },
  5549. body: JSON.stringify({ disabled })
  5550. });
  5551. if (res.ok) {
  5552. loadBridge();
  5553. fetchData(false);
  5554. }
  5555. } catch (err) {
  5556. showToast('Error', err.message, 'error');
  5557. }
  5558. }
  5559. async function deleteBridge(id) {
  5560. const b = (state.bridges || []).find(x => x.id === id);
  5561. const name = b ? b.name : id;
  5562. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  5563. try {
  5564. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5565. if (res.ok) {
  5566. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  5567. loadBridge();
  5568. fetchData(false);
  5569. } else {
  5570. const err = await res.json();
  5571. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  5572. }
  5573. } catch (err) {
  5574. showToast('Error', err.message, 'error');
  5575. }
  5576. }
  5577. // ----------------- Bridge IP Assignments -----------------
  5578. function openAddBridgeIPModal(id, name) {
  5579. document.getElementById('bridge-ip-modal-id').value = id;
  5580. document.getElementById('bridge-ip-modal-sub').innerText = name;
  5581. document.getElementById('bridge-ip-modal-cidr').value = '';
  5582. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  5583. }
  5584. function closeBridgeIPModal() {
  5585. document.getElementById('bridge-ip-modal').classList.add('hidden');
  5586. }
  5587. async function submitAddBridgeIP(e) {
  5588. e.preventDefault();
  5589. const id = document.getElementById('bridge-ip-modal-id').value;
  5590. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  5591. try {
  5592. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  5593. method: 'POST',
  5594. headers: { 'Content-Type': 'application/json' },
  5595. body: JSON.stringify({ ip })
  5596. });
  5597. if (res.ok) {
  5598. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  5599. closeBridgeIPModal();
  5600. loadBridge();
  5601. fetchData(false);
  5602. } else {
  5603. const err = await res.json();
  5604. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  5605. }
  5606. } catch (err) {
  5607. showToast('Error', err.message, 'error');
  5608. }
  5609. }
  5610. async function deleteBridgeIP(id, ip) {
  5611. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  5612. try {
  5613. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  5614. method: 'DELETE',
  5615. headers: { 'Content-Type': 'application/json' },
  5616. body: JSON.stringify({ ip })
  5617. });
  5618. if (res.ok) {
  5619. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  5620. loadBridge();
  5621. fetchData(false);
  5622. }
  5623. } catch (err) {
  5624. showToast('Error', err.message, 'error');
  5625. }
  5626. }
  5627. // ----------------- Bridge Ports -----------------
  5628. function renderBridgePorts() {
  5629. const tbody = document.getElementById('bridge-ports-table-body');
  5630. const empty = document.getElementById('bridge-empty-ports');
  5631. const countBadge = document.getElementById('bridge-ports-count-badge');
  5632. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  5633. if (!tbody) return;
  5634. tbody.innerHTML = '';
  5635. // Update filter select
  5636. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  5637. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  5638. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  5639. if (ports.length === 0) {
  5640. empty?.classList.remove('hidden');
  5641. return;
  5642. }
  5643. empty?.classList.add('hidden');
  5644. ports.forEach((p, idx) => {
  5645. const tr = document.createElement('tr');
  5646. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  5647. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  5648. tr.innerHTML = `
  5649. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5650. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  5651. <td class="py-2.5 px-3 font-bold text-white text-sm">
  5652. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  5653. </td>
  5654. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  5655. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  5656. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  5657. <td class="py-2.5 px-3 text-center">${p.ingress_filtering ? '<span class="text-amber-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  5658. <td class="py-2.5 px-3">
  5659. ${p.horizon > 0 ? `<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-950 text-purple-300 border border-purple-800/40 font-mono">domain ${p.horizon}</span>` : '<span class="text-slate-500">none</span>'}
  5660. </td>
  5661. <td class="py-2.5 px-3">
  5662. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${p.status === 'forwarding' ? 'bg-emerald-950 text-emerald-400 border border-emerald-800/40' : 'bg-slate-800 text-slate-400'} uppercase font-mono">${p.status}</span>
  5663. </td>
  5664. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  5665. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5666. <button onclick="toggleBridgePortState('${p.id}', ${!p.disabled})" class="text-xs ${p.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline font-semibold">${p.disabled ? 'Enable' : 'Disable'}</button>
  5667. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5668. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5669. </td>
  5670. `;
  5671. tbody.appendChild(tr);
  5672. });
  5673. }
  5674. function openAddBridgePortModal() {
  5675. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  5676. document.getElementById('bridge-port-modal-id').value = '';
  5677. populateBridgeSelect('bridge-port-modal-bridge');
  5678. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  5679. document.getElementById('bridge-port-modal-pvid').value = '1';
  5680. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  5681. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  5682. document.getElementById('bridge-port-modal-horizon').value = '0';
  5683. document.getElementById('bridge-port-modal-pathcost').value = '10';
  5684. document.getElementById('bridge-port-modal-priority').value = '128';
  5685. document.getElementById('bridge-port-modal-learn').checked = true;
  5686. document.getElementById('bridge-port-modal-comment').value = '';
  5687. document.getElementById('bridge-port-modal-disabled').checked = false;
  5688. document.getElementById('bridge-port-modal').classList.remove('hidden');
  5689. }
  5690. function openEditBridgePortModal(id) {
  5691. const p = (state.bridgePorts || []).find(x => x.id === id);
  5692. if (!p) return;
  5693. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  5694. document.getElementById('bridge-port-modal-id').value = p.id;
  5695. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  5696. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  5697. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  5698. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  5699. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  5700. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  5701. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  5702. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  5703. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  5704. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  5705. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  5706. document.getElementById('bridge-port-modal').classList.remove('hidden');
  5707. }
  5708. function closeBridgePortModal() {
  5709. document.getElementById('bridge-port-modal').classList.add('hidden');
  5710. }
  5711. async function submitSaveBridgePort(e) {
  5712. e.preventDefault();
  5713. const id = document.getElementById('bridge-port-modal-id').value;
  5714. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  5715. const iface = document.getElementById('bridge-port-modal-interface').value;
  5716. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  5717. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  5718. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  5719. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  5720. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  5721. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  5722. const learn = document.getElementById('bridge-port-modal-learn').checked;
  5723. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  5724. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  5725. try {
  5726. const res = await fetch(`${API_BASE}/bridge/ports`, {
  5727. method: 'POST',
  5728. headers: { 'Content-Type': 'application/json' },
  5729. body: JSON.stringify({
  5730. id,
  5731. bridge,
  5732. interface: iface,
  5733. pvid,
  5734. frame_types: frameTypes,
  5735. ingress_filtering: ingressFiltering,
  5736. horizon,
  5737. path_cost: pathCost,
  5738. priority,
  5739. learn,
  5740. comment,
  5741. disabled
  5742. })
  5743. });
  5744. if (res.ok) {
  5745. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  5746. closeBridgePortModal();
  5747. loadBridge();
  5748. fetchData(false);
  5749. } else {
  5750. const err = await res.json();
  5751. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  5752. }
  5753. } catch (err) {
  5754. showToast('Error', err.message, 'error');
  5755. }
  5756. }
  5757. async function toggleBridgePortState(id, disabled) {
  5758. try {
  5759. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  5760. method: 'POST',
  5761. headers: { 'Content-Type': 'application/json' },
  5762. body: JSON.stringify({ disabled })
  5763. });
  5764. if (res.ok) {
  5765. loadBridge();
  5766. fetchData(false);
  5767. }
  5768. } catch (err) {
  5769. showToast('Error', err.message, 'error');
  5770. }
  5771. }
  5772. async function deleteBridgePort(id) {
  5773. const p = (state.bridgePorts || []).find(x => x.id === id);
  5774. const iface = p ? p.interface : id;
  5775. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  5776. try {
  5777. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5778. if (res.ok) {
  5779. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  5780. loadBridge();
  5781. fetchData(false);
  5782. }
  5783. } catch (err) {
  5784. showToast('Error', err.message, 'error');
  5785. }
  5786. }
  5787. // ----------------- Bridge VLANs -----------------
  5788. function renderBridgeVLANs() {
  5789. const tbody = document.getElementById('bridge-vlans-table-body');
  5790. const empty = document.getElementById('bridge-empty-vlans');
  5791. const countBadge = document.getElementById('bridge-vlans-count-badge');
  5792. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  5793. if (!tbody) return;
  5794. tbody.innerHTML = '';
  5795. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  5796. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  5797. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  5798. if (vlans.length === 0) {
  5799. empty?.classList.remove('hidden');
  5800. return;
  5801. }
  5802. empty?.classList.add('hidden');
  5803. vlans.forEach((v, idx) => {
  5804. const tr = document.createElement('tr');
  5805. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  5806. const taggedHtml = (v.tagged && v.tagged.length > 0)
  5807. ? v.tagged.map(p => `<span class="px-1.5 py-0.5 rounded text-[10px] bg-cyan-950/80 border border-cyan-800/40 text-cyan-300 font-mono">${p}</span>`).join(' ')
  5808. : '<span class="text-slate-600">none</span>';
  5809. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  5810. ? v.untagged.map(p => `<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700/60 text-slate-300 font-mono">${p}</span>`).join(' ')
  5811. : '<span class="text-slate-600">none</span>';
  5812. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  5813. tr.innerHTML = `
  5814. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5815. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  5816. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  5817. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  5818. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  5819. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  5820. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  5821. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5822. <button onclick="toggleBridgeVLANState('${v.id}', ${!v.disabled})" class="text-xs ${v.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline font-semibold">${v.disabled ? 'Enable' : 'Disable'}</button>
  5823. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5824. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5825. </td>
  5826. `;
  5827. tbody.appendChild(tr);
  5828. });
  5829. }
  5830. function openAddBridgeVLANModal() {
  5831. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  5832. document.getElementById('bridge-vlan-modal-id').value = '';
  5833. populateBridgeSelect('bridge-vlan-modal-bridge');
  5834. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  5835. document.getElementById('bridge-vlan-modal-comment').value = '';
  5836. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  5837. updateBridgeVlanPortCheckboxes();
  5838. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  5839. }
  5840. function openEditBridgeVLANModal(id) {
  5841. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  5842. if (!v) return;
  5843. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  5844. document.getElementById('bridge-vlan-modal-id').value = v.id;
  5845. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  5846. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  5847. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  5848. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  5849. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  5850. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  5851. }
  5852. function closeBridgeVlanModal() {
  5853. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  5854. }
  5855. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  5856. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  5857. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  5858. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  5859. if (!taggedBox || !untaggedBox) return;
  5860. // Ports belonging to the selected bridge
  5861. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  5862. if (memberPorts.length === 0) {
  5863. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  5864. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  5865. return;
  5866. }
  5867. taggedBox.innerHTML = memberPorts.map(p => `
  5868. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  5869. <input type="checkbox" name="bvlan-tagged" value="${p.interface}" ${taggedSelected.includes(p.interface) ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-cyan-500">
  5870. <span>${p.interface}</span>
  5871. </label>
  5872. `).join('');
  5873. untaggedBox.innerHTML = memberPorts.map(p => `
  5874. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  5875. <input type="checkbox" name="bvlan-untagged" value="${p.interface}" ${untaggedSelected.includes(p.interface) ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-slate-400">
  5876. <span>${p.interface}</span>
  5877. </label>
  5878. `).join('');
  5879. }
  5880. async function submitSaveBridgeVLAN(e) {
  5881. e.preventDefault();
  5882. const id = document.getElementById('bridge-vlan-modal-id').value;
  5883. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  5884. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  5885. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  5886. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  5887. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  5888. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  5889. try {
  5890. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  5891. method: 'POST',
  5892. headers: { 'Content-Type': 'application/json' },
  5893. body: JSON.stringify({
  5894. id,
  5895. bridge,
  5896. vlan_ids: vlanIDs,
  5897. tagged,
  5898. untagged,
  5899. comment,
  5900. disabled
  5901. })
  5902. });
  5903. if (res.ok) {
  5904. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  5905. closeBridgeVlanModal();
  5906. loadBridge();
  5907. } else {
  5908. const err = await res.json();
  5909. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  5910. }
  5911. } catch (err) {
  5912. showToast('Error', err.message, 'error');
  5913. }
  5914. }
  5915. async function toggleBridgeVLANState(id, disabled) {
  5916. try {
  5917. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  5918. method: 'POST',
  5919. headers: { 'Content-Type': 'application/json' },
  5920. body: JSON.stringify({ disabled })
  5921. });
  5922. if (res.ok) loadBridge();
  5923. } catch (err) {
  5924. showToast('Error', err.message, 'error');
  5925. }
  5926. }
  5927. async function deleteBridgeVLAN(id) {
  5928. if (!confirm('Delete this bridge VLAN entry?')) return;
  5929. try {
  5930. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5931. if (res.ok) {
  5932. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  5933. loadBridge();
  5934. }
  5935. } catch (err) {
  5936. showToast('Error', err.message, 'error');
  5937. }
  5938. }
  5939. // ----------------- Hosts / MAC Table -----------------
  5940. async function loadBridgeHosts() {
  5941. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  5942. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  5943. try {
  5944. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  5945. const res = await fetch(url);
  5946. if (res.ok) {
  5947. state.bridgeHosts = await res.json();
  5948. renderBridgeHosts();
  5949. }
  5950. } catch (err) {
  5951. console.error('Failed to load bridge hosts:', err);
  5952. }
  5953. }
  5954. function renderBridgeHosts() {
  5955. const tbody = document.getElementById('bridge-hosts-table-body');
  5956. const empty = document.getElementById('bridge-empty-hosts');
  5957. const countBadge = document.getElementById('bridge-hosts-count-badge');
  5958. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  5959. if (!tbody) return;
  5960. tbody.innerHTML = '';
  5961. const hosts = (state.bridgeHosts || []).filter(h => {
  5962. if (!search) return true;
  5963. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  5964. });
  5965. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  5966. if (hosts.length === 0) {
  5967. empty?.classList.remove('hidden');
  5968. return;
  5969. }
  5970. empty?.classList.add('hidden');
  5971. hosts.forEach(h => {
  5972. const tr = document.createElement('tr');
  5973. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5974. let flagBadges = '';
  5975. if (h.local) flagBadges += '<span class="px-1.5 py-0.2 rounded text-[10px] bg-sky-950 text-sky-400 border border-sky-800/40 font-mono font-bold mr-1" title="Local router interface MAC">L</span>';
  5976. if (h.static) flagBadges += '<span class="px-1.5 py-0.2 rounded text-[10px] bg-purple-950 text-purple-400 border border-purple-800/40 font-mono font-bold mr-1" title="Static entry">S</span>';
  5977. if (!h.local && !h.static) flagBadges += '<span class="px-1.5 py-0.2 rounded text-[10px] bg-emerald-950 text-emerald-400 border border-emerald-800/40 font-mono font-bold mr-1" title="Dynamically learned">D</span>';
  5978. tr.innerHTML = `
  5979. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  5980. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  5981. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  5982. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  5983. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  5984. <td class="py-2.5 px-3">${flagBadges}</td>
  5985. `;
  5986. tbody.appendChild(tr);
  5987. });
  5988. }
  5989. async function flushBridgeHosts() {
  5990. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  5991. if (!selBridge) {
  5992. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  5993. return;
  5994. }
  5995. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  5996. try {
  5997. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  5998. method: 'POST',
  5999. headers: { 'Content-Type': 'application/json' },
  6000. body: JSON.stringify({ bridge: selBridge })
  6001. });
  6002. if (res.ok) {
  6003. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  6004. loadBridgeHosts();
  6005. }
  6006. } catch (err) {
  6007. showToast('Error', err.message, 'error');
  6008. }
  6009. }
  6010. // ----------------- Helpers -----------------
  6011. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  6012. const sel = document.getElementById(selectId);
  6013. if (!sel) return;
  6014. const prevVal = currentVal || sel.value;
  6015. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  6016. (state.bridges || []).forEach(b => {
  6017. const opt = document.createElement('option');
  6018. opt.value = b.name;
  6019. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  6020. if (b.name === prevVal) opt.selected = true;
  6021. sel.appendChild(opt);
  6022. });
  6023. }
  6024. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  6025. const sel = document.getElementById(selectId);
  6026. if (!sel) return;
  6027. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  6028. // 1. Physical Interfaces
  6029. const grpPhys = document.createElement('optgroup');
  6030. grpPhys.label = 'Physical Interfaces';
  6031. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  6032. const opt = document.createElement('option');
  6033. opt.value = i.name;
  6034. opt.innerText = `${i.name} (${i.role || i.type})`;
  6035. if (i.name === currentVal) opt.selected = true;
  6036. grpPhys.appendChild(opt);
  6037. });
  6038. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  6039. // 2. VLAN Sub-interfaces
  6040. const grpVlans = document.createElement('optgroup');
  6041. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  6042. (state.vlans || []).forEach(v => {
  6043. const opt = document.createElement('option');
  6044. opt.value = v.name;
  6045. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  6046. if (v.name === currentVal) opt.selected = true;
  6047. grpVlans.appendChild(opt);
  6048. });
  6049. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  6050. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  6051. const grpEoip = document.createElement('optgroup');
  6052. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  6053. (state.eoipTunnels || []).forEach(t => {
  6054. const opt = document.createElement('option');
  6055. opt.value = t.name;
  6056. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  6057. if (t.name === currentVal) opt.selected = true;
  6058. grpEoip.appendChild(opt);
  6059. });
  6060. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  6061. }