app.js 280 KB

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