app.js 298 KB

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