app.js 608 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454
  1. // DebTik - Debian Linux Router Frontend Application Logic
  2. let state = {
  3. interfaces: [],
  4. vlans: [],
  5. systemStatus: null,
  6. vpnStatus: null,
  7. routes: [],
  8. activeTab: 'dashboard',
  9. fwSubTab: 'filter',
  10. bridgeSubTab: 'bridges',
  11. bridges: [],
  12. bridgePorts: [],
  13. bridgeVLANs: [],
  14. bridgeHosts: [],
  15. bridgeSummary: null,
  16. routesSubTab: 'routes',
  17. pppSubTab: 'secrets',
  18. eoipTunnels: [],
  19. pppSecrets: [],
  20. pppProfiles: [],
  21. pppActiveSessions: [],
  22. pppoeServer: null,
  23. pptpServer: null,
  24. l2tpServer: null,
  25. ipsecServer: null,
  26. ifaceFilter: 'all',
  27. currentModalIface: null,
  28. isPolling: true,
  29. expandedParents: new Set(['eth0']),
  30. pppoeData: null,
  31. wgData: null,
  32. ipsecData: null,
  33. l2tpData: null,
  34. pptpData: null,
  35. fwSummary: null,
  36. filterRules: [],
  37. natRules: [],
  38. mangleRules: [],
  39. addressLists: [],
  40. connections: [],
  41. policyRules: [],
  42. routingTables: [],
  43. routingFilters: [],
  44. filterChainSelected: 'all',
  45. activeToolsSubTab: 'ping',
  46. dhcpClients: [],
  47. dhcpSummary: null,
  48. dhcpServerTab: 'servers',
  49. dhcpServers: [],
  50. dhcpNetworks: [],
  51. dhcpLeases: [],
  52. dhcpOptions: [],
  53. dhcpServerSummary: null
  54. };
  55. const API_BASE = '/api';
  56. function escapeHtml(str) {
  57. if (str === null || str === undefined) return '';
  58. return String(str)
  59. .replace(/&/g, '&')
  60. .replace(/</g, '&lt;')
  61. .replace(/>/g, '&gt;')
  62. .replace(/"/g, '&quot;')
  63. .replace(/'/g, '&#039;');
  64. }
  65. function formatBytes(bytes) {
  66. if (bytes === undefined || bytes === null || isNaN(bytes) || bytes === 0) return '0 B';
  67. const k = 1024;
  68. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  69. const i = Math.floor(Math.log(bytes) / Math.log(k));
  70. if (i < 0 || i >= sizes.length) return `${bytes} B`;
  71. return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
  72. }
  73. // Initialize on page load
  74. document.addEventListener('DOMContentLoaded', () => {
  75. const hash = window.location.hash.replace('#', '') || 'dashboard';
  76. navigate(hash);
  77. initTableSorting();
  78. fetchData();
  79. // Live polling every 2.5 seconds
  80. setInterval(() => {
  81. if (state.isPolling) {
  82. fetchData(false);
  83. }
  84. }, 2500);
  85. });
  86. // Navigation Handler
  87. function navigate(tabName) {
  88. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  89. navigate('bgp');
  90. return;
  91. }
  92. if (tabName === 'vlans') {
  93. navigate('interfaces');
  94. return;
  95. }
  96. state.activeTab = tabName;
  97. window.location.hash = tabName;
  98. // Update nav links styling
  99. document.querySelectorAll('.nav-link').forEach(link => {
  100. 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';
  101. });
  102. const activeNav = document.getElementById(`nav-${tabName}`);
  103. if (activeNav) {
  104. 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';
  105. }
  106. // Update page headers
  107. const titles = {
  108. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  109. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  110. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  111. 'dhcp-server': { title: 'DHCP Server & Subnets', sub: 'DHCP Server instances, subnet networks (NTP, TFTP, DNS), dynamic leases & static reservations' },
  112. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  113. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  114. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  115. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  116. bgp: { title: 'BGP Dynamic Routing', sub: 'BGP multi-instance peering sessions, advertised networks, and routing table (RIB)' },
  117. ospf: { title: 'OSPF Dynamic Routing', sub: 'OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  118. 'routing-filters': { title: 'Routing Policy Filters', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  119. 'dynamic-routing': { title: 'BGP Dynamic Routing', sub: 'Dynamic routing engine and peering sessions' },
  120. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  121. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  122. aerotun: { title: 'AeroTUN High-Speed VPN', sub: 'Ultra-fast Layer 3 encrypted tunnel with ChaCha20-Poly1305 and live Adaptive LZ4 compression' },
  123. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  124. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  125. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  126. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  127. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  128. vrrp: { title: 'VRRP High Availability', sub: 'Virtual Router Redundancy Protocol, active-backup gateway failover & Virtual IP (VIP) routing' },
  129. bwtest: { title: 'Bandwidth Test Benchmark', sub: 'High-speed line-rate throughput benchmark, token-bucket rate limiting, loss & jitter telemetry' },
  130. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  131. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' }
  132. };
  133. const header = titles[tabName] || titles.dashboard;
  134. const pTitle = document.getElementById('page-title');
  135. if (pTitle) pTitle.innerText = header.title;
  136. const pSub = document.getElementById('page-subtitle');
  137. if (pSub) pSub.innerText = header.sub;
  138. // Toggle sections dynamically for all section elements
  139. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  140. if (el.id === `section-${tabName}`) {
  141. el.classList.remove('hidden');
  142. } else {
  143. el.classList.add('hidden');
  144. }
  145. });
  146. if (tabName === 'bridge') loadBridge();
  147. if (tabName === 'firewall') loadFirewall();
  148. if (tabName === 'routes') loadRoutes();
  149. if (tabName === 'bgp') {
  150. loadDynamicRouting();
  151. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  152. }
  153. if (tabName === 'ospf') {
  154. loadDynamicRouting();
  155. switchOspfTab(state.activeOspfTab || 'instances');
  156. }
  157. if (tabName === 'routing-filters') loadDynamicRouting();
  158. if (tabName === 'dynamic-routing') loadDynamicRouting();
  159. if (tabName === 'ppp') loadPPP();
  160. if (tabName === 'eoip') loadEoIP();
  161. if (tabName === 'aerotun') loadAeroTUN();
  162. if (tabName === 'persistence') loadDebianConfig();
  163. if (tabName === 'pppoe') loadPPPoE();
  164. if (tabName === 'wireguard') loadWireGuard();
  165. if (tabName === 'ipsec') loadIPSec();
  166. if (tabName === 'l2tp') loadL2TP();
  167. if (tabName === 'pptp') loadPPTP();
  168. if (tabName === 'tools') loadToolsView();
  169. if (tabName === 'dhcp-client') loadDHCPClients();
  170. if (tabName === 'dhcp-server') loadDHCPServer();
  171. if (tabName === 'vrrp') loadVRRP();
  172. if (tabName === 'bwtest') loadBwTestView();
  173. setTimeout(initTableSorting, 50);
  174. }
  175. // Fetch all core system, network and VPN telemetry
  176. async function fetchData(isManual = false) {
  177. const spinner = document.getElementById('refresh-spinner');
  178. if (isManual && spinner) spinner.classList.add('animate-spin');
  179. try {
  180. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes] = await Promise.all([
  181. fetch(`${API_BASE}/system/status`),
  182. fetch(`${API_BASE}/interfaces`),
  183. fetch(`${API_BASE}/vlans`),
  184. fetch(`${API_BASE}/vpn/status`),
  185. fetch(`${API_BASE}/firewall/summary`),
  186. fetch(`${API_BASE}/routing/dynamic/summary`),
  187. fetch(`${API_BASE}/bridge/summary`),
  188. fetch(`${API_BASE}/dhcp/clients/summary`),
  189. fetch(`${API_BASE}/dhcp/clients`),
  190. fetch(`${API_BASE}/vrrp/summary`).catch(() => null)
  191. ]);
  192. if (vrrpSumRes && vrrpSumRes.ok) {
  193. state.vrrpSummary = await vrrpSumRes.json();
  194. renderVRRPSummary();
  195. }
  196. if (dhcpSumRes && dhcpSumRes.ok) {
  197. state.dhcpSummary = await dhcpSumRes.json();
  198. const bDhcp = document.getElementById('badge-dhcp-client-count');
  199. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  200. }
  201. if (dhcpClientsRes && dhcpClientsRes.ok) {
  202. state.dhcpClients = await dhcpClientsRes.json();
  203. }
  204. if (brSummaryRes.ok) {
  205. state.bridgeSummary = await brSummaryRes.json();
  206. const bBridge = document.getElementById('badge-bridge-count');
  207. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  208. const sBr = document.getElementById('bridge-stat-bridges');
  209. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  210. const sPorts = document.getElementById('bridge-stat-ports');
  211. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  212. const sHosts = document.getElementById('bridge-stat-hosts');
  213. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  214. }
  215. if (statusRes.ok) state.systemStatus = await statusRes.json();
  216. if (ifacesRes.ok) {
  217. const ifacesData = await ifacesRes.json();
  218. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  219. state.interfaces = rawIfaces.filter(i => {
  220. if (!i.name) return false;
  221. if (i.name.startsWith('ep_')) return false;
  222. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  223. });
  224. try { populateToolsInterfaces(); } catch (e) {}
  225. }
  226. if (vlansRes.ok) {
  227. const vlansData = await vlansRes.json();
  228. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  229. }
  230. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  231. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  232. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  233. updateSystemMetrics();
  234. updateBadges();
  235. if (state.activeTab === 'dashboard') renderDashboard();
  236. if (state.activeTab === 'interfaces') renderInterfacesList();
  237. if (state.activeTab === 'vlans') renderVlansList();
  238. if (state.activeTab === 'firewall') loadFirewall(false);
  239. if (state.activeTab === 'routes') loadRoutes(false);
  240. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  241. if (state.activeTab === 'ppp') loadPPP(false);
  242. if (state.activeTab === 'eoip') loadEoIP(false);
  243. if (state.activeTab === 'aerotun') loadAeroTUN(false);
  244. if (state.activeTab === 'pppoe') loadPPPoE(false);
  245. if (state.activeTab === 'wireguard') loadWireGuard(false);
  246. if (state.activeTab === 'ipsec') loadIPSec(false);
  247. if (state.activeTab === 'l2tp') loadL2TP(false);
  248. if (state.activeTab === 'pptp') loadPPTP(false);
  249. if (state.activeTab === 'dhcp-client') loadDHCPClients(false);
  250. if (state.activeTab === 'dhcp-server') loadDHCPServer(false);
  251. if (state.activeTab === 'vrrp') loadVRRP(false);
  252. fetchBwTestServerStatus();
  253. } catch (err) {
  254. console.error('Failed to fetch router state:', err);
  255. } finally {
  256. if (isManual && spinner) {
  257. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  258. }
  259. }
  260. }
  261. // Update Top KPI and Sidebar Telemetry
  262. function updateSystemMetrics() {
  263. const s = state.systemStatus;
  264. const v = state.vpnStatus;
  265. if (!s) return;
  266. // Sidebar Host & Uptime
  267. const sideHost = document.getElementById('side-hostname');
  268. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  269. const sideUp = document.getElementById('side-uptime');
  270. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  271. const sideGw = document.getElementById('side-gateway-ip');
  272. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  273. // Compute CPU Metrics
  274. let cpuPct = 0;
  275. if (s.cpu_pct !== undefined) {
  276. cpuPct = s.cpu_pct;
  277. } else if (s.cpu_load && s.cpu_load.length > 0) {
  278. const cores = s.cpu_cores || 1;
  279. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  280. }
  281. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  282. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  283. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  284. // Sidebar CPU
  285. const sideCpuVal = document.getElementById('side-cpu-val');
  286. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  287. const sideCpuBar = document.getElementById('side-cpu-bar');
  288. if (sideCpuBar) {
  289. sideCpuBar.style.width = cpuWidth;
  290. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  291. }
  292. // Dashboard CPU Card
  293. const dashCpuVal = document.getElementById('dash-cpu-val');
  294. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  295. const dashCpuBar = document.getElementById('dash-cpu-bar');
  296. if (dashCpuBar) {
  297. dashCpuBar.style.width = cpuWidth;
  298. if (cpuPct > 85) {
  299. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  300. } else if (cpuPct > 65) {
  301. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  302. } else {
  303. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  304. }
  305. }
  306. const dashCpuCores = document.getElementById('dash-cpu-cores');
  307. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  308. const dashCpuLoad = document.getElementById('dash-cpu-load');
  309. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  310. const dashCpuStatus = document.getElementById('dash-cpu-status');
  311. if (dashCpuStatus) {
  312. if (cpuPct > 85) {
  313. dashCpuStatus.innerText = 'High';
  314. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  315. } else if (cpuPct > 65) {
  316. dashCpuStatus.innerText = 'Heavy';
  317. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  318. } else {
  319. dashCpuStatus.innerText = 'Normal';
  320. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  321. }
  322. }
  323. // Compute RAM Metrics
  324. const memPct = Math.round(s.mem_usage_pct || 0);
  325. const memPctStr = `${memPct}%`;
  326. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  327. const usedMB = s.mem_used_mb || 0;
  328. const totalMB = s.mem_total_mb || 0;
  329. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  330. function fmtMemMB(mb) {
  331. if (mb >= 1024) {
  332. return `${(mb / 1024).toFixed(1)} GB`;
  333. }
  334. return `${mb} MB`;
  335. }
  336. // Sidebar RAM
  337. const sideRamVal = document.getElementById('side-ram-val');
  338. if (sideRamVal) sideRamVal.innerText = memPctStr;
  339. const sideRamBar = document.getElementById('side-ram-bar');
  340. if (sideRamBar) sideRamBar.style.width = memWidth;
  341. // Dashboard RAM Card
  342. const dashRamVal = document.getElementById('dash-ram-val');
  343. if (dashRamVal) dashRamVal.innerText = memPctStr;
  344. const dashRamBar = document.getElementById('dash-ram-bar');
  345. if (dashRamBar) {
  346. dashRamBar.style.width = memWidth;
  347. if (memPct > 85) {
  348. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  349. } else if (memPct > 70) {
  350. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  351. } else {
  352. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  353. }
  354. }
  355. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  356. if (dashRamUsedTotal) {
  357. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  358. }
  359. const dashRamFree = document.getElementById('dash-ram-free');
  360. if (dashRamFree) {
  361. dashRamFree.innerText = fmtMemMB(freeMB);
  362. }
  363. const dashRamStatus = document.getElementById('dash-ram-status');
  364. if (dashRamStatus) {
  365. if (memPct > 85) {
  366. dashRamStatus.innerText = 'High';
  367. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  368. } else {
  369. dashRamStatus.innerText = 'Active';
  370. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  371. }
  372. }
  373. // Legacy Dashboard Stats (Safe checks)
  374. const elIfacesUp = document.getElementById('stat-ifaces-up');
  375. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  376. const elIfacesTot = document.getElementById('stat-ifaces-total');
  377. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  378. const elIfacesDown = document.getElementById('stat-ifaces-down');
  379. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  380. const elVlans = document.getElementById('stat-vlans-count');
  381. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  382. // VPN Status Indicators
  383. if (v) {
  384. const totalActive = v.total_active_tunnels || 0;
  385. const statVpnActive = document.getElementById('stat-vpn-active');
  386. if (statVpnActive) statVpnActive.innerText = totalActive;
  387. const tunnelsDot = document.getElementById('tunnels-dot');
  388. const tunnelsLabel = document.getElementById('tunnels-label');
  389. if (tunnelsDot && tunnelsLabel) {
  390. if (totalActive > 0) {
  391. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  392. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  393. } else {
  394. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  395. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  396. }
  397. }
  398. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  399. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  400. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  401. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  402. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  403. }
  404. // Total Live Bandwidth Rate
  405. let totalRx = 0;
  406. let totalTx = 0;
  407. (state.interfaces || []).forEach(i => {
  408. if (i.rate) {
  409. totalRx += i.rate.rx_bytes_sec || 0;
  410. totalTx += i.rate.tx_bytes_sec || 0;
  411. }
  412. });
  413. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  414. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  415. }
  416. function setDotBadge(id, active) {
  417. const el = document.getElementById(id);
  418. if (!el) return;
  419. if (active) {
  420. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  421. } else {
  422. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  423. }
  424. }
  425. function updateBadges() {
  426. const bIfaces = document.getElementById('badge-ifaces-count');
  427. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  428. const bVlans = document.getElementById('badge-vlans-count');
  429. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  430. if (state.fwSummary) {
  431. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  432. const badgeFw = document.getElementById('badge-firewall-count');
  433. if (badgeFw) badgeFw.innerText = totalFwRules;
  434. }
  435. if (state.vpnStatus) {
  436. const v = state.vpnStatus;
  437. const bEoIP = document.getElementById('badge-eoip-count');
  438. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  439. const bAero = document.getElementById('badge-aerotun-count');
  440. if (bAero) bAero.innerText = v.total_aerotun || 0;
  441. const bPPPSess = document.getElementById('badge-ppp-sessions');
  442. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  443. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  444. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  445. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  446. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  447. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  448. }
  449. if (state.dynSummary) {
  450. const d = state.dynSummary;
  451. setDotBadge('badge-bgp-dot', d.bgp_running);
  452. setDotBadge('badge-ospf-dot', d.ospf_running);
  453. const bBgp = document.getElementById('badge-bgp-count');
  454. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  455. const bOspf = document.getElementById('badge-ospf-count');
  456. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  457. const bFilters = document.getElementById('badge-filters-count');
  458. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  459. }
  460. const bDhcpServer = document.getElementById('badge-dhcp-server-count');
  461. if (bDhcpServer) {
  462. bDhcpServer.innerText = state.dhcpServerSummary ? (state.dhcpServerSummary.active_leases || state.dhcpServerSummary.total_servers || 0) : (state.dhcpServers || []).length;
  463. }
  464. }
  465. // Render Dashboard View
  466. function renderDashboard() {
  467. const matrix = document.getElementById('port-matrix');
  468. matrix.innerHTML = '';
  469. (state.interfaces || []).forEach(iface => {
  470. const isUp = iface.state === 'UP';
  471. const isVlan = iface.is_vlan;
  472. const portCard = document.createElement('div');
  473. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  474. isUp
  475. ? (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')
  476. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  477. }`;
  478. portCard.onclick = () => openIfaceModal(iface.name);
  479. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  480. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  481. portCard.innerHTML = `
  482. <div class="flex items-center justify-between mb-2">
  483. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  484. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  485. </div>
  486. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  487. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  488. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  489. <span>${iface.rate?.rx_human || '0 B/s'}</span>
  490. </div>
  491. `;
  492. matrix.appendChild(portCard);
  493. });
  494. const ifaceTbody = document.getElementById('quick-interfaces-table');
  495. if (ifaceTbody) {
  496. ifaceTbody.innerHTML = '';
  497. (state.interfaces || []).forEach(i => {
  498. const isUp = i.state === 'UP';
  499. const tr = document.createElement('tr');
  500. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  501. tr.onclick = () => openIfaceModal(i.name);
  502. const rxStr = i.rate?.rx_human || '0 B/s';
  503. const txStr = i.rate?.tx_human || '0 B/s';
  504. tr.innerHTML = `
  505. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  506. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  507. <span>${i.name}</span>
  508. </td>
  509. <td class="py-2.5 text-slate-300 font-sans">
  510. <span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 font-medium">${i.role || i.type || 'Ethernet'}</span>
  511. </td>
  512. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  513. <td class="py-2.5 text-slate-200 font-semibold">${i.ipv4 && i.ipv4.length > 0 ? i.ipv4.join(', ') : '<span class="text-slate-600 font-normal">Unassigned</span>'}</td>
  514. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  515. <span class="text-emerald-400">↓ ${rxStr}</span> <span class="text-slate-600">•</span> <span class="text-cyan-400">↑ ${txStr}</span>
  516. </td>
  517. <td class="py-2.5 text-right font-sans font-semibold">
  518. <span class="px-2 py-0.5 rounded text-[10px] ${isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20' : 'bg-rose-500/10 text-rose-400 border border-rose-500/20'}">${i.state}</span>
  519. </td>
  520. `;
  521. ifaceTbody.appendChild(tr);
  522. });
  523. }
  524. const vlanTbody = document.getElementById('quick-vlans-table');
  525. if (vlanTbody) {
  526. vlanTbody.innerHTML = '';
  527. }
  528. }
  529. // Expand / Collapse Handlers
  530. function toggleExpand(parentName) {
  531. if (state.expandedParents.has(parentName)) {
  532. state.expandedParents.delete(parentName);
  533. } else {
  534. state.expandedParents.add(parentName);
  535. }
  536. renderInterfacesList();
  537. }
  538. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  539. function supportsVLAN(iface) {
  540. if (!iface) return false;
  541. if (iface.is_vlan) return false;
  542. const name = (iface.name || '').toLowerCase();
  543. const type = (iface.type || '').toLowerCase();
  544. const role = (iface.role || '').toLowerCase();
  545. // Exclude loopback
  546. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  547. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  548. if (type === 'wireguard' || name.startsWith('wg')) return false;
  549. // Exclude PPP / PPPoE
  550. if (type === 'ppp' || name.startsWith('ppp')) return false;
  551. // Exclude other Layer 3 tunnels and dummy devices
  552. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  553. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  554. return false;
  555. }
  556. // If name already contains a dot, it's already a sub-interface
  557. if (name.includes('.')) return false;
  558. return true;
  559. }
  560. // Expand / Collapse Handlers
  561. function toggleExpand(parentName) {
  562. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  563. if (childVlans.length === 0) {
  564. // Cannot expand an interface with no VLANs
  565. state.expandedParents.delete(parentName);
  566. return;
  567. }
  568. if (state.expandedParents.has(parentName)) {
  569. state.expandedParents.delete(parentName);
  570. } else {
  571. state.expandedParents.add(parentName);
  572. }
  573. renderInterfacesList();
  574. }
  575. function expandAllIfaces(expand) {
  576. if (expand) {
  577. (state.interfaces || []).forEach(i => {
  578. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  579. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  580. });
  581. } else {
  582. state.expandedParents.clear();
  583. }
  584. renderInterfacesList();
  585. }
  586. // Filter and Render Hierarchical Interfaces List
  587. function filterIfaces(filter) {
  588. state.ifaceFilter = filter || 'all';
  589. renderInterfacesList();
  590. }
  591. function renderInterfacesList() {
  592. const tbody = document.getElementById('interfaces-tree-tbody');
  593. const emptyState = document.getElementById('interfaces-empty-state');
  594. const summary = document.getElementById('ifaces-list-summary');
  595. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  596. tbody.innerHTML = '';
  597. const allIfaces = state.interfaces || [];
  598. const allVlans = state.vlans || [];
  599. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  600. const filteredParents = parentIfaces.filter(parent => {
  601. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  602. if (query) {
  603. const matchName = parent.name.toLowerCase().includes(query);
  604. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  605. const matchRole = (parent.role || '').toLowerCase().includes(query);
  606. const matchType = (parent.type || '').toLowerCase().includes(query);
  607. const matchVlan = childVlans.some(v =>
  608. v.name.toLowerCase().includes(query) ||
  609. String(v.vlan_id).includes(query) ||
  610. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  611. (v.description || '').toLowerCase().includes(query)
  612. );
  613. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  614. }
  615. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  616. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  617. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  618. return true;
  619. });
  620. if (summary) {
  621. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  622. }
  623. if (filteredParents.length === 0) {
  624. emptyState?.classList.remove('hidden');
  625. return;
  626. }
  627. emptyState?.classList.add('hidden');
  628. filteredParents.forEach(parent => {
  629. const isUp = parent.state === 'UP';
  630. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  631. const hasVlans = childVlans.length > 0;
  632. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  633. const canHaveVlan = supportsVLAN(parent);
  634. const parentRow = document.createElement('tr');
  635. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  636. parentRow.innerHTML = `
  637. <td class="py-3 px-3 text-center">
  638. ${hasVlans ? `
  639. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  640. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  641. <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">
  642. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  643. </svg>
  644. </button>
  645. ` : `
  646. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  647. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  648. </div>
  649. `}
  650. </td>
  651. <td class="py-3 px-4">
  652. <div class="flex items-center space-x-2.5">
  653. <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">
  654. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  655. </div>
  656. <div>
  657. <div class="flex items-center gap-2">
  658. ${hasVlans ? `
  659. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400" onclick="toggleExpand('${parent.name}')">${parent.name}</span>
  660. <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>
  661. ` : `
  662. <span class="font-bold text-white text-sm">${parent.name}</span>
  663. <span class="text-[10px] bg-slate-800/40 text-slate-500 px-1.5 py-0.5 rounded font-mono select-none">0 VLANs</span>
  664. `}
  665. </div>
  666. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  667. </div>
  668. </div>
  669. </td>
  670. <td class="py-3 px-4 font-sans">
  671. <div class="flex items-center gap-1.5">
  672. <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>
  673. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  674. </div>
  675. </td>
  676. <td class="py-3 px-4">
  677. ${parent.ipv4 && parent.ipv4.length > 0
  678. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  679. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  680. }
  681. ${(() => {
  682. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  683. if (!c) return '';
  684. const statusCls = c.status === 'bound' ? 'bg-amber-500/20 text-amber-300 border-amber-500/30' : (c.status === 'searching' ? 'bg-sky-500/20 text-sky-300 border-sky-500/30' : 'bg-slate-800 text-slate-400 border-slate-700');
  685. return `<div class="mt-1"><span class="px-1.5 py-0.5 rounded text-[10px] font-mono border ${statusCls} cursor-pointer hover:underline" onclick="navigate('dhcp-client')" title="DHCP Client: ${c.status.toUpperCase()} (${c.ip_address || 'requesting...'})">⚡ DHCP: ${c.status.toUpperCase()}</span></div>`;
  686. })()}
  687. </td>
  688. <td class="py-3 px-4 text-slate-400 text-[11px]">
  689. <div>${parent.mac || 'N/A'}</div>
  690. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  691. </td>
  692. <td class="py-3 px-4 text-[11px]">
  693. <div class="flex items-center space-x-2">
  694. <span class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  695. <span class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  696. </div>
  697. </td>
  698. <td class="py-3 px-4 font-sans">
  699. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  700. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  701. 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'
  702. }" title="Click to toggle link status">
  703. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  704. <span>${parent.state}</span>
  705. </button>
  706. </td>
  707. <td class="py-3 px-4 text-right space-x-2 font-sans">
  708. ${(() => {
  709. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  710. if (c) {
  711. return `<button onclick="navigate('dhcp-client')" title="Manage DHCP Client (${c.status})" class="text-xs bg-amber-500/10 hover:bg-amber-500/20 text-amber-400 font-medium px-2.5 py-1 rounded-lg border border-amber-500/30 transition">⚡ DHCP</button>`;
  712. }
  713. return `<button onclick="openDHCPClientModalForIface('${parent.name}')" title="Add DHCP Client on ${parent.name}" class="text-xs bg-slate-800/80 hover:bg-slate-700 text-slate-300 hover:text-amber-400 font-medium px-2 py-1 rounded-lg border border-slate-700 transition">+ DHCP</button>`;
  714. })()}
  715. ${canHaveVlan ? `
  716. <button onclick="openVlanModal('${parent.name}')"
  717. 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">
  718. + Add VLAN
  719. </button>
  720. ` : ''}
  721. <button onclick="openIfaceModal('${parent.name}')"
  722. 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">
  723. Configure
  724. </button>
  725. </td>
  726. `;
  727. tbody.appendChild(parentRow);
  728. if (isExpanded) {
  729. const drawerRow = document.createElement('tr');
  730. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  731. const drawerCell = document.createElement('td');
  732. drawerCell.colSpan = 8;
  733. drawerCell.className = 'p-0';
  734. drawerCell.innerHTML = `
  735. <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">
  736. <div class="flex items-center justify-between mb-3">
  737. <div class="flex items-center space-x-3">
  738. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  739. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  740. </span>
  741. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  742. ${childVlans.length} Attached
  743. </span>
  744. </div>
  745. <button onclick="openVlanModal('${parent.name}')"
  746. 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">
  747. <span>+ Create VLAN on ${parent.name}</span>
  748. </button>
  749. </div>
  750. ${childVlans.length === 0 ? `
  751. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  752. <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>
  753. <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">
  754. <span>+ Create Your First VLAN on ${parent.name}</span>
  755. </button>
  756. </div>
  757. ` : `
  758. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  759. <table class="w-full text-left text-xs font-mono">
  760. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  761. <tr>
  762. <th class="py-2.5 px-4">VLAN ID</th>
  763. <th class="py-2.5 px-4">Interface Device</th>
  764. <th class="py-2.5 px-4">Subnet Gateway</th>
  765. <th class="py-2.5 px-4">Role / Alias</th>
  766. <th class="py-2.5 px-4">MTU</th>
  767. <th class="py-2.5 px-4">Throughput</th>
  768. <th class="py-2.5 px-4">Status</th>
  769. <th class="py-2.5 px-4 text-right">Actions</th>
  770. </tr>
  771. </thead>
  772. <tbody class="divide-y divide-slate-800/70">
  773. ${childVlans.map(v => {
  774. const isVlanUp = v.state === 'UP';
  775. return `
  776. <tr class="hover:bg-slate-800/40 transition">
  777. <td class="py-2.5 px-4">
  778. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  779. VLAN ${v.vlan_id}
  780. </span>
  781. </td>
  782. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  783. <span class="text-cyan-500">└─</span>
  784. <span>${v.name}</span>
  785. </td>
  786. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  787. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  788. ${(() => {
  789. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  790. if (!c) return '';
  791. const statusCls = c.status === 'bound' ? 'bg-amber-500/20 text-amber-300 border-amber-500/30' : 'bg-slate-800 text-slate-400 border-slate-700';
  792. return `<div class="mt-0.5"><span class="px-1.5 py-0.2 rounded text-[9px] font-mono border ${statusCls} cursor-pointer hover:underline" onclick="navigate('dhcp-client')" title="DHCP Client: ${c.status.toUpperCase()}">⚡ DHCP: ${c.status.toUpperCase()}</span></div>`;
  793. })()}
  794. </td>
  795. <td class="py-2.5 px-4 font-sans text-slate-300">
  796. <span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 mr-1.5">${v.role || 'VLAN'}</span>
  797. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  798. </td>
  799. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  800. <td class="py-2.5 px-4 text-[11px]">
  801. <span class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  802. <span class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  803. </td>
  804. <td class="py-2.5 px-4 font-sans">
  805. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  806. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  807. 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'
  808. }">
  809. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  810. <span>${v.state}</span>
  811. </button>
  812. </td>
  813. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  814. ${(() => {
  815. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  816. if (c) {
  817. return `<button onclick="navigate('dhcp-client')" class="text-xs text-amber-400 hover:text-amber-300 px-2 py-0.5 rounded bg-amber-950/40 border border-amber-800/50">⚡ DHCP</button>`;
  818. }
  819. return `<button onclick="openDHCPClientModalForIface('${v.name}')" class="text-xs text-slate-400 hover:text-amber-400 px-1.5 py-0.5 rounded border border-slate-700">+ DHCP</button>`;
  820. })()}
  821. <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>
  822. <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>
  823. </td>
  824. </tr>
  825. `;
  826. }).join('')}
  827. </tbody>
  828. </table>
  829. </div>
  830. `}
  831. </div>
  832. `;
  833. drawerRow.appendChild(drawerCell);
  834. tbody.appendChild(drawerRow);
  835. }
  836. });
  837. }
  838. // Render VLANs Dedicated View
  839. function renderVlansList() {
  840. const tbody = document.getElementById('vlans-table-body');
  841. if (!tbody) return;
  842. const emptyState = document.getElementById('vlans-empty-state');
  843. const countBadge = document.getElementById('vlans-table-count');
  844. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  845. tbody.innerHTML = '';
  846. const allVlans = state.vlans || [];
  847. if (countBadge) countBadge.innerText = allVlans.length;
  848. const filtered = allVlans.filter(v => {
  849. if (!query) return true;
  850. return v.name.toLowerCase().includes(query) ||
  851. String(v.vlan_id).includes(query) ||
  852. (v.description || '').toLowerCase().includes(query) ||
  853. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  854. });
  855. if (allVlans.length === 0) {
  856. emptyState.classList.remove('hidden');
  857. return;
  858. }
  859. emptyState.classList.add('hidden');
  860. filtered.forEach(v => {
  861. const isUp = v.state === 'UP';
  862. const tr = document.createElement('tr');
  863. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  864. tr.innerHTML = `
  865. <td class="py-3 px-4">
  866. <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">
  867. VLAN ${v.vlan_id}
  868. </span>
  869. </td>
  870. <td class="py-3 px-4 font-bold text-white">${v.name}</td>
  871. <td class="py-3 px-4 text-slate-300">
  872. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  873. </td>
  874. <td class="py-3 px-4 text-emerald-400 font-medium">
  875. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  876. </td>
  877. <td class="py-3 px-4 text-slate-300 font-sans">
  878. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  879. </td>
  880. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  881. <td class="py-3 px-4 font-sans">
  882. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  883. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  884. 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'
  885. }">
  886. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  887. <span>${v.state}</span>
  888. </button>
  889. </td>
  890. <td class="py-3 px-4 text-right space-x-2 font-sans">
  891. <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>
  892. <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>
  893. </td>
  894. `;
  895. tbody.appendChild(tr);
  896. });
  897. }
  898. // Toggle interface UP / DOWN
  899. async function toggleInterfaceState(name, newState) {
  900. try {
  901. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  902. method: 'POST',
  903. headers: { 'Content-Type': 'application/json' },
  904. body: JSON.stringify({ state: newState })
  905. });
  906. const data = await res.json();
  907. if (res.ok) {
  908. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  909. fetchData(false);
  910. } else {
  911. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  912. }
  913. } catch (err) {
  914. showToast('Error', err.message, 'error');
  915. }
  916. }
  917. // ---------------- MikroTik Flag & Utilities ----------------
  918. function renderMikroTikFlag(running, disabled) {
  919. if (running) {
  920. 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>`;
  921. }
  922. if (disabled) {
  923. 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>`;
  924. }
  925. 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>`;
  926. }
  927. function copyToClipboard(text, label = 'Text') {
  928. navigator.clipboard.writeText(text).then(() => {
  929. showToast('Copied', `${label} copied to clipboard`, 'success');
  930. }).catch(() => {
  931. prompt('Copy value:', text);
  932. });
  933. }
  934. // ======================== PPP Profiles Shared Helper ========================
  935. async function fetchPPPProfilesList() {
  936. try {
  937. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  938. if (res.ok) {
  939. state.pppProfiles = await res.json();
  940. }
  941. } catch (err) {
  942. console.error('Failed to load PPP profiles:', err);
  943. }
  944. }
  945. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  946. const sel = document.getElementById(selectId);
  947. if (!sel) return;
  948. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  949. { name: 'default', use_encryption: 'no' },
  950. { name: 'default-encryption', use_encryption: 'required' }
  951. ];
  952. sel.innerHTML = '';
  953. profiles.forEach(p => {
  954. const opt = document.createElement('option');
  955. opt.value = p.name;
  956. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  957. opt.innerText = `${p.name}${encBadge}`;
  958. sel.appendChild(opt);
  959. });
  960. if (selectedVal) {
  961. sel.value = selectedVal;
  962. } else {
  963. sel.value = defaultVal;
  964. }
  965. if (!sel.value && sel.options.length > 0) {
  966. sel.selectedIndex = 0;
  967. }
  968. }
  969. // ======================== PPPoE Multi-Instance ========================
  970. async function loadPPPoE(populateInputs = true) {
  971. try {
  972. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  973. await fetchPPPProfilesList();
  974. }
  975. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  976. const list = await res.json();
  977. state.pppoeList = Array.isArray(list) ? list : [];
  978. const badge = document.getElementById('pppoe-count-badge');
  979. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  980. const tbody = document.getElementById('pppoe-table-body');
  981. const empty = document.getElementById('pppoe-empty');
  982. if (!tbody) return;
  983. tbody.innerHTML = '';
  984. if (state.pppoeList.length === 0) {
  985. if (empty) empty.classList.remove('hidden');
  986. } else {
  987. if (empty) empty.classList.add('hidden');
  988. state.pppoeList.forEach(inst => {
  989. const tr = document.createElement('tr');
  990. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  991. tr.innerHTML = `
  992. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  993. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  994. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  995. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  996. <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default')}</span></td>
  997. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  998. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  999. <td class="py-2.5 px-3 text-center">
  1000. <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'}">
  1001. ${inst.default_route ? 'Yes' : 'No'}
  1002. </span>
  1003. </td>
  1004. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1005. ${inst.running ? `
  1006. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1007. ` : `
  1008. <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>
  1009. `}
  1010. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1011. ${inst.disabled ? 'Enable' : 'Disable'}
  1012. </button>
  1013. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1014. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1015. </td>
  1016. `;
  1017. tbody.appendChild(tr);
  1018. });
  1019. }
  1020. } catch (err) {
  1021. console.error('Failed to load PPPoE:', err);
  1022. }
  1023. }
  1024. function openAddPPPoEModal() {
  1025. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  1026. document.getElementById('pppoe-modal-edit-orig').value = '';
  1027. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  1028. document.getElementById('pppoe-modal-name').readOnly = false;
  1029. document.getElementById('pppoe-modal-user').value = '';
  1030. document.getElementById('pppoe-modal-pass').value = '';
  1031. document.getElementById('pppoe-modal-service').value = '';
  1032. document.getElementById('pppoe-modal-mtu').value = '1492';
  1033. document.getElementById('pppoe-modal-defroute').checked = true;
  1034. document.getElementById('pppoe-modal-reconnect').checked = true;
  1035. document.getElementById('pppoe-modal-disabled').checked = false;
  1036. // Populate profiles
  1037. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1038. // Populate interfaces
  1039. const sel = document.getElementById('pppoe-modal-iface');
  1040. sel.innerHTML = '';
  1041. (state.interfaces || []).forEach(i => {
  1042. if (i.name === 'lo') return;
  1043. const opt = document.createElement('option');
  1044. opt.value = i.name;
  1045. opt.innerText = `${i.name} (${i.role || i.type})`;
  1046. sel.appendChild(opt);
  1047. });
  1048. document.getElementById('pppoe-modal').classList.remove('hidden');
  1049. }
  1050. function openEditPPPoEModal(name) {
  1051. const inst = (state.pppoeList || []).find(i => i.name === name);
  1052. if (!inst) return;
  1053. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1054. document.getElementById('pppoe-modal-edit-orig').value = name;
  1055. document.getElementById('pppoe-modal-name').value = inst.name;
  1056. document.getElementById('pppoe-modal-name').readOnly = true;
  1057. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1058. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1059. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1060. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1061. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1062. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1063. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1064. // Populate profiles
  1065. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1066. const sel = document.getElementById('pppoe-modal-iface');
  1067. sel.innerHTML = '';
  1068. (state.interfaces || []).forEach(i => {
  1069. if (i.name === 'lo') return;
  1070. const opt = document.createElement('option');
  1071. opt.value = i.name;
  1072. opt.innerText = `${i.name} (${i.role || i.type})`;
  1073. if (i.name === inst.interface) opt.selected = true;
  1074. sel.appendChild(opt);
  1075. });
  1076. document.getElementById('pppoe-modal').classList.remove('hidden');
  1077. }
  1078. function closePPPoEModal() {
  1079. document.getElementById('pppoe-modal').classList.add('hidden');
  1080. }
  1081. async function submitSavePPPoE(e) {
  1082. e.preventDefault();
  1083. const name = document.getElementById('pppoe-modal-name').value.trim();
  1084. const iface = document.getElementById('pppoe-modal-iface').value;
  1085. const user = document.getElementById('pppoe-modal-user').value.trim();
  1086. const pass = document.getElementById('pppoe-modal-pass').value;
  1087. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1088. const service = document.getElementById('pppoe-modal-service').value.trim();
  1089. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1090. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1091. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1092. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1093. try {
  1094. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1095. method: 'POST',
  1096. headers: { 'Content-Type': 'application/json' },
  1097. body: JSON.stringify({
  1098. name,
  1099. interface: iface,
  1100. username: user,
  1101. password: pass,
  1102. profile: profile,
  1103. service_name: service,
  1104. mtu,
  1105. default_route: defRoute,
  1106. auto_reconnect: reconnect,
  1107. disabled
  1108. })
  1109. });
  1110. if (res.ok) {
  1111. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1112. closePPPoEModal();
  1113. loadPPPoE(false);
  1114. fetchData(false);
  1115. } else {
  1116. const err = await res.json();
  1117. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1118. }
  1119. } catch (err) {
  1120. showToast('Error', err.message, 'error');
  1121. }
  1122. }
  1123. async function connectPPPoEInstance(name) {
  1124. try {
  1125. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1126. if (res.ok) {
  1127. showToast('Connecting', `Dialing ${name}...`, 'info');
  1128. setTimeout(() => loadPPPoE(false), 2000);
  1129. }
  1130. } catch (err) {
  1131. showToast('Error', err.message, 'error');
  1132. }
  1133. }
  1134. async function disconnectPPPoEInstance(name) {
  1135. try {
  1136. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1137. if (res.ok) {
  1138. showToast('Disconnected', `${name} session terminated`, 'info');
  1139. setTimeout(() => loadPPPoE(false), 1000);
  1140. }
  1141. } catch (err) {
  1142. showToast('Error', err.message, 'error');
  1143. }
  1144. }
  1145. async function togglePPPoEState(name, enable) {
  1146. try {
  1147. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1148. method: 'POST',
  1149. headers: { 'Content-Type': 'application/json' },
  1150. body: JSON.stringify({ enabled: enable })
  1151. });
  1152. if (res.ok) {
  1153. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1154. loadPPPoE(false);
  1155. }
  1156. } catch (err) {
  1157. showToast('Error', err.message, 'error');
  1158. }
  1159. }
  1160. async function deletePPPoEInstance(name) {
  1161. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1162. try {
  1163. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1164. if (res.ok) {
  1165. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1166. loadPPPoE(false);
  1167. fetchData(false);
  1168. }
  1169. } catch (err) {
  1170. showToast('Error', err.message, 'error');
  1171. }
  1172. }
  1173. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1174. state.wgSubTab = 'ifaces';
  1175. function switchWGSubTab(tab) {
  1176. state.wgSubTab = tab;
  1177. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1178. const peersPanel = document.getElementById('wg-subtab-peers');
  1179. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1180. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1181. if (tab === 'ifaces') {
  1182. ifacesPanel?.classList.remove('hidden');
  1183. peersPanel?.classList.add('hidden');
  1184. 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';
  1185. 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';
  1186. } else {
  1187. ifacesPanel?.classList.add('hidden');
  1188. peersPanel?.classList.remove('hidden');
  1189. 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';
  1190. 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';
  1191. renderWGPeers();
  1192. }
  1193. }
  1194. async function loadWireGuard(populateInputs = true) {
  1195. try {
  1196. const [ifacesRes, peersRes] = await Promise.all([
  1197. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1198. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1199. ]);
  1200. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1201. const peers = peersRes.ok ? await peersRes.json() : [];
  1202. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1203. state.wgPeers = Array.isArray(peers) ? peers : [];
  1204. // Badges
  1205. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1206. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1207. const peersCountBadge = document.getElementById('wg-peers-count');
  1208. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1209. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1210. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1211. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1212. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1213. // Render Interfaces
  1214. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1215. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1216. if (ifacesTbody) {
  1217. ifacesTbody.innerHTML = '';
  1218. if (state.wgInterfaces.length === 0) {
  1219. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1220. } else {
  1221. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1222. state.wgInterfaces.forEach(iface => {
  1223. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1224. const tr = document.createElement('tr');
  1225. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1226. tr.innerHTML = `
  1227. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1228. <td class="py-2.5 px-3">
  1229. <div class="flex items-center gap-1.5">
  1230. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1231. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1232. </div>
  1233. </td>
  1234. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1235. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1236. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1237. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1238. ${(iface.public_key || '').substring(0, 10)}... 📋
  1239. </span>
  1240. </td>
  1241. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1242. <td class="py-2.5 px-3 text-center">
  1243. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1244. </td>
  1245. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1246. ${iface.running ? `
  1247. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1248. ` : `
  1249. <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 font-medium">Start</button>
  1250. `}
  1251. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1252. ${iface.disabled ? 'Enable' : 'Disable'}
  1253. </button>
  1254. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1255. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1256. </td>
  1257. `;
  1258. ifacesTbody.appendChild(tr);
  1259. });
  1260. }
  1261. }
  1262. // Populate filter dropdown in peers tab
  1263. const filterSel = document.getElementById('wg-peers-filter-iface');
  1264. if (filterSel) {
  1265. const currentVal = filterSel.value;
  1266. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1267. state.wgInterfaces.forEach(i => {
  1268. const opt = document.createElement('option');
  1269. opt.value = i.name;
  1270. opt.innerText = i.name;
  1271. if (i.name === currentVal) opt.selected = true;
  1272. filterSel.appendChild(opt);
  1273. });
  1274. }
  1275. renderWGPeers();
  1276. } catch (err) {
  1277. console.error('Failed to load WireGuard:', err);
  1278. }
  1279. }
  1280. function renderWGPeers() {
  1281. const filterSel = document.getElementById('wg-peers-filter-iface');
  1282. const selectedIface = filterSel ? filterSel.value : '';
  1283. const tbody = document.getElementById('wg-peers-table-body');
  1284. const empty = document.getElementById('wg-peers-empty');
  1285. if (!tbody) return;
  1286. tbody.innerHTML = '';
  1287. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1288. if (filtered.length === 0) {
  1289. if (empty) empty.classList.remove('hidden');
  1290. } else {
  1291. if (empty) empty.classList.add('hidden');
  1292. filtered.forEach(p => {
  1293. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1294. const tr = document.createElement('tr');
  1295. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1296. tr.innerHTML = `
  1297. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1298. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1299. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1300. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1301. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1302. ${(p.public_key || '').substring(0, 10)}... 📋
  1303. </span>
  1304. </td>
  1305. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1306. <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>
  1307. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1308. <td class="py-2.5 px-3 font-mono text-[11px]">
  1309. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1310. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1311. </td>
  1312. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1313. <button onclick="toggleWGPeerState('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}', ${p.disabled ? 'true' : 'false'})" class="text-xs ${p.disabled ? 'text-emerald-400 hover:text-emerald-300' : 'text-slate-400 hover:text-white'} font-medium">
  1314. ${p.disabled ? 'Enable' : 'Disable'}
  1315. </button>
  1316. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1317. <button onclick="openWGClientConfModal('${escapeHtml(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>
  1318. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1319. </td>
  1320. `;
  1321. tbody.appendChild(tr);
  1322. });
  1323. }
  1324. }
  1325. function openAddWGInterfaceModal() {
  1326. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1327. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1328. const nameEl = document.getElementById('wg-iface-modal-name');
  1329. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1330. nameEl.readOnly = false;
  1331. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1332. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1333. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1334. document.getElementById('wg-iface-modal-comment').value = '';
  1335. document.getElementById('wg-iface-modal-pubkey').value = '';
  1336. document.getElementById('wg-iface-modal-privkey').value = '';
  1337. document.getElementById('wg-iface-modal-disabled').checked = false;
  1338. generateWGInterfaceKeys();
  1339. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1340. }
  1341. function openEditWGInterfaceModal(name) {
  1342. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1343. if (!iface) return;
  1344. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1345. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1346. const nameEl = document.getElementById('wg-iface-modal-name');
  1347. nameEl.value = iface.name;
  1348. nameEl.readOnly = false; // ALLOW RENAMING
  1349. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1350. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1351. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1352. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1353. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1354. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1355. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1356. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1357. }
  1358. function closeAddWGInterfaceModal() {
  1359. document.getElementById('wg-iface-modal').classList.add('hidden');
  1360. }
  1361. async function generateWGInterfaceKeys() {
  1362. try {
  1363. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1364. const keys = await res.json();
  1365. if (res.ok) {
  1366. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1367. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1368. }
  1369. } catch (err) {
  1370. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1371. }
  1372. }
  1373. async function onWGInterfacePrivKeyInput() {
  1374. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1375. if (!privKey) return;
  1376. try {
  1377. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1378. method: 'POST',
  1379. headers: { 'Content-Type': 'application/json' },
  1380. body: JSON.stringify({ private_key: privKey })
  1381. });
  1382. if (res.ok) {
  1383. const data = await res.json();
  1384. if (data.public_key) {
  1385. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1386. }
  1387. }
  1388. } catch (err) {
  1389. // Ignore while typing
  1390. }
  1391. }
  1392. function toggleWGPrivKeyVisibility() {
  1393. const el = document.getElementById('wg-iface-modal-privkey');
  1394. const btn = document.getElementById('btn-toggle-wg-privkey');
  1395. if (el.type === 'password') {
  1396. el.type = 'text';
  1397. btn.innerText = '🙈 Hide';
  1398. } else {
  1399. el.type = 'password';
  1400. btn.innerText = '👁️ Show';
  1401. }
  1402. }
  1403. function copyWGInterfacePubKey() {
  1404. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1405. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1406. }
  1407. async function submitSaveWGInterface(e) {
  1408. e.preventDefault();
  1409. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1410. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1411. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1412. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1413. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1414. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1415. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1416. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1417. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1418. try {
  1419. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1420. method: 'POST',
  1421. headers: { 'Content-Type': 'application/json' },
  1422. body: JSON.stringify({
  1423. orig_name: origName,
  1424. name,
  1425. listen_port: port,
  1426. address: addr,
  1427. mtu,
  1428. comment,
  1429. public_key: pub,
  1430. private_key: priv,
  1431. disabled
  1432. })
  1433. });
  1434. const data = await res.json();
  1435. if (res.ok) {
  1436. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1437. closeAddWGInterfaceModal();
  1438. loadWireGuard(false);
  1439. fetchData(false);
  1440. } else {
  1441. showToast('Error', data.error || 'Failed to save interface', 'error');
  1442. }
  1443. } catch (err) {
  1444. showToast('Error', err.message, 'error');
  1445. }
  1446. }
  1447. async function startWGInterface(name) {
  1448. try {
  1449. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1450. if (res.ok) {
  1451. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1452. loadWireGuard(false);
  1453. fetchData(false);
  1454. }
  1455. } catch (err) {
  1456. showToast('Error', err.message, 'error');
  1457. }
  1458. }
  1459. async function stopWGInterface(name) {
  1460. try {
  1461. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1462. if (res.ok) {
  1463. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1464. loadWireGuard(false);
  1465. fetchData(false);
  1466. }
  1467. } catch (err) {
  1468. showToast('Error', err.message, 'error');
  1469. }
  1470. }
  1471. async function toggleWGInterfaceState(name, enable) {
  1472. try {
  1473. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1474. method: 'POST',
  1475. headers: { 'Content-Type': 'application/json' },
  1476. body: JSON.stringify({ enabled: enable })
  1477. });
  1478. if (res.ok) {
  1479. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1480. loadWireGuard(false);
  1481. fetchData(false);
  1482. }
  1483. } catch (err) {
  1484. showToast('Error', err.message, 'error');
  1485. }
  1486. }
  1487. async function deleteWGInterface(name) {
  1488. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1489. try {
  1490. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1491. if (res.ok) {
  1492. showToast('Deleted', `Interface ${name} removed`, 'success');
  1493. loadWireGuard(false);
  1494. fetchData(false);
  1495. }
  1496. } catch (err) {
  1497. showToast('Error', err.message, 'error');
  1498. }
  1499. }
  1500. function populateWGPeerIfaceSelect(selectedIface = '') {
  1501. const sel = document.getElementById('wg-peer-modal-iface');
  1502. if (!sel) return;
  1503. sel.innerHTML = '';
  1504. (state.wgInterfaces || []).forEach(i => {
  1505. const opt = document.createElement('option');
  1506. opt.value = i.name;
  1507. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1508. if (i.name === selectedIface) opt.selected = true;
  1509. sel.appendChild(opt);
  1510. });
  1511. }
  1512. function openAddWGPeerModal() {
  1513. if ((state.wgInterfaces || []).length === 0) {
  1514. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1515. openAddWGInterfaceModal();
  1516. return;
  1517. }
  1518. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  1519. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  1520. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  1521. populateWGPeerIfaceSelect();
  1522. document.getElementById('wg-peer-modal-name').value = '';
  1523. document.getElementById('wg-peer-modal-pubkey').value = '';
  1524. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1525. document.getElementById('wg-peer-modal-endpoint').value = '';
  1526. document.getElementById('wg-peer-modal-port').value = '';
  1527. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1528. document.getElementById('wg-peer-modal-preshared').value = '';
  1529. document.getElementById('wg-peer-modal-disabled').checked = false;
  1530. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1531. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1532. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1533. }
  1534. function openEditWGPeerModal(ifaceName, pubKey) {
  1535. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  1536. if (!peer) {
  1537. showToast('Not Found', 'Peer not found', 'warning');
  1538. return;
  1539. }
  1540. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  1541. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  1542. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  1543. populateWGPeerIfaceSelect(peer.interface);
  1544. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  1545. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  1546. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  1547. document.getElementById('wg-peer-modal-endpoint').value = peer.endpoint_address || '';
  1548. document.getElementById('wg-peer-modal-port').value = peer.endpoint_port || '';
  1549. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  1550. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  1551. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  1552. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1553. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1554. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1555. }
  1556. function closeAddWGPeerModal() {
  1557. document.getElementById('wg-peer-modal').classList.add('hidden');
  1558. }
  1559. async function generatePeerKeypairHelper() {
  1560. try {
  1561. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1562. const keys = await res.json();
  1563. if (res.ok) {
  1564. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  1565. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  1566. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  1567. checkWGPeerKeyValidity();
  1568. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  1569. }
  1570. } catch (err) {
  1571. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1572. }
  1573. }
  1574. function copyGeneratedPeerPrivKey() {
  1575. const priv = document.getElementById('wg-peer-gen-privkey').value;
  1576. if (priv) copyToClipboard(priv, 'Client Private Key');
  1577. }
  1578. async function generatePeerPSK() {
  1579. try {
  1580. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1581. const keys = await res.json();
  1582. if (res.ok && keys.private_key) {
  1583. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  1584. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  1585. }
  1586. } catch (err) {
  1587. showToast('Error', err.message, 'error');
  1588. }
  1589. }
  1590. function checkWGPeerKeyValidity() {
  1591. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  1592. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1593. const warningEl = document.getElementById('wg-peer-key-warning');
  1594. if (!warningEl) return;
  1595. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  1596. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  1597. warningEl.classList.remove('hidden');
  1598. } else {
  1599. warningEl.classList.add('hidden');
  1600. }
  1601. }
  1602. async function submitSaveWGPeer(e) {
  1603. e.preventDefault();
  1604. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  1605. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  1606. const iface = document.getElementById('wg-peer-modal-iface').value;
  1607. const name = document.getElementById('wg-peer-modal-name').value.trim();
  1608. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1609. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  1610. .split(',')
  1611. .map(s => s.trim())
  1612. .filter(s => s.length > 0);
  1613. const epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  1614. const epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  1615. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  1616. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  1617. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  1618. // Validation
  1619. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  1620. if (targetIface && targetIface.public_key === pub) {
  1621. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  1622. return;
  1623. }
  1624. try {
  1625. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  1626. method: 'POST',
  1627. headers: { 'Content-Type': 'application/json' },
  1628. body: JSON.stringify({
  1629. orig_interface: origIface,
  1630. orig_public_key: origPubKey,
  1631. interface: iface,
  1632. name,
  1633. public_key: pub,
  1634. allowed_ips: allowed,
  1635. endpoint_address: epHost,
  1636. endpoint_port: epPort,
  1637. persistent_keepalive: keepalive,
  1638. preshared_key: psk,
  1639. disabled
  1640. })
  1641. });
  1642. const data = await res.json();
  1643. if (res.ok) {
  1644. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  1645. closeAddWGPeerModal();
  1646. loadWireGuard(false);
  1647. } else {
  1648. showToast('Error', data.error || 'Failed to save peer', 'error');
  1649. }
  1650. } catch (err) {
  1651. showToast('Error', err.message, 'error');
  1652. }
  1653. }
  1654. async function toggleWGPeerState(iface, pubkey, enable) {
  1655. try {
  1656. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  1657. method: 'POST',
  1658. headers: { 'Content-Type': 'application/json' },
  1659. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  1660. });
  1661. const data = await res.json();
  1662. if (res.ok) {
  1663. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  1664. loadWireGuard(false);
  1665. } else {
  1666. showToast('Error', data.error || 'Failed to update peer state', 'error');
  1667. }
  1668. } catch (err) {
  1669. showToast('Error', err.message, 'error');
  1670. }
  1671. }
  1672. async function deleteWGPeer(iface, pubkey) {
  1673. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  1674. try {
  1675. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  1676. method: 'POST',
  1677. headers: { 'Content-Type': 'application/json' },
  1678. body: JSON.stringify({ interface: iface, public_key: pubkey })
  1679. });
  1680. const data = await res.json();
  1681. if (res.ok) {
  1682. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  1683. loadWireGuard(false);
  1684. } else {
  1685. showToast('Error', data.error || 'Failed to remove peer', 'error');
  1686. }
  1687. } catch (err) {
  1688. showToast('Error', err.message, 'error');
  1689. }
  1690. }
  1691. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  1692. function switchIpsecModalTab(tab) {
  1693. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  1694. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  1695. const p1Content = document.getElementById('ipsec-tab-content-p1');
  1696. const p2Content = document.getElementById('ipsec-tab-content-p2');
  1697. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  1698. if (tab === 'p1') {
  1699. if (p1Tab) {
  1700. p1Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-amber-500 text-amber-300 transition flex items-center gap-2';
  1701. }
  1702. if (p2Tab) {
  1703. p2Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  1704. }
  1705. if (p1Content) p1Content.classList.remove('hidden');
  1706. if (p2Content) p2Content.classList.add('hidden');
  1707. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  1708. } else {
  1709. if (p1Tab) {
  1710. p1Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  1711. }
  1712. if (p2Tab) {
  1713. p2Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-cyan-300 transition flex items-center gap-2';
  1714. }
  1715. if (p1Content) p1Content.classList.add('hidden');
  1716. if (p2Content) p2Content.classList.remove('hidden');
  1717. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  1718. }
  1719. }
  1720. function toggleIpsecPhaseStep() {
  1721. const p1Content = document.getElementById('ipsec-tab-content-p1');
  1722. if (p1Content && !p1Content.classList.contains('hidden')) {
  1723. switchIpsecModalTab('p2');
  1724. } else {
  1725. switchIpsecModalTab('p1');
  1726. }
  1727. }
  1728. function toggleIpsecPskVisibility() {
  1729. const pskInput = document.getElementById('ipsec-modal-psk');
  1730. if (!pskInput) return;
  1731. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  1732. }
  1733. function addIpsecLocalSubnet(val = '') {
  1734. const container = document.getElementById('ipsec-modal-local-subnets-container');
  1735. if (!container) return;
  1736. const row = document.createElement('div');
  1737. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  1738. row.innerHTML = `
  1739. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 192.168.10.0/24 or 10.0.1.0/24" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-cyan-500">
  1740. <button type="button" onclick="this.closest('.ipsec-subnet-row').remove()" class="w-7 h-7 flex items-center justify-center bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-400 border border-slate-700 rounded-lg text-base font-bold transition" title="Remove local subnet">-</button>
  1741. `;
  1742. container.appendChild(row);
  1743. }
  1744. function addIpsecRemoteSubnet(val = '') {
  1745. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  1746. if (!container) return;
  1747. const row = document.createElement('div');
  1748. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  1749. row.innerHTML = `
  1750. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 192.168.20.0/24 or 10.0.2.0/24" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-purple-500">
  1751. <button type="button" onclick="this.closest('.ipsec-subnet-row').remove()" class="w-7 h-7 flex items-center justify-center bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-400 border border-slate-700 rounded-lg text-base font-bold transition" title="Remove remote subnet">-</button>
  1752. `;
  1753. container.appendChild(row);
  1754. }
  1755. function updateIpsecEspProposalFromPFS(val) {
  1756. const prop = document.getElementById('ipsec-modal-espprop');
  1757. if (!prop) return;
  1758. if (val === 'none') {
  1759. prop.value = 'aes256-sha256,aes128-sha256,default';
  1760. } else {
  1761. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  1762. }
  1763. }
  1764. function updateIpsecIkeProposalFromDH(dh) {
  1765. const el = document.getElementById('ipsec-modal-ikeprop');
  1766. if (el) {
  1767. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  1768. }
  1769. }
  1770. function safeSetVal(id, val) {
  1771. const el = document.getElementById(id);
  1772. if (el) el.value = val;
  1773. }
  1774. function safeSetChecked(id, val) {
  1775. const el = document.getElementById(id);
  1776. if (el) el.checked = !!val;
  1777. }
  1778. function safeGetVal(id, def = '') {
  1779. const el = document.getElementById(id);
  1780. return el ? el.value : def;
  1781. }
  1782. async function loadIPSec(populateInputs = true) {
  1783. try {
  1784. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1785. const list = await res.json();
  1786. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1787. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1788. const badge = document.getElementById('ipsec-sas-badge');
  1789. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1790. const tbody = document.getElementById('ipsec-table-body');
  1791. const empty = document.getElementById('ipsec-empty');
  1792. if (!tbody) return;
  1793. tbody.innerHTML = '';
  1794. if (state.ipsecTunnels.length === 0) {
  1795. if (empty) empty.classList.remove('hidden');
  1796. } else {
  1797. if (empty) empty.classList.add('hidden');
  1798. state.ipsecTunnels.forEach(c => {
  1799. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1800. const tr = document.createElement('tr');
  1801. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  1802. // Local subnets tags
  1803. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  1804. const localBadges = localList.map(s => `<span class="px-1.5 py-0.5 rounded bg-cyan-950/60 border border-cyan-800/60 text-cyan-300 font-mono text-[10px] mr-1">${escapeHtml(s)}</span>`).join('');
  1805. // Remote subnets tags
  1806. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  1807. const remoteBadges = remoteList.map(s => `<span class="px-1.5 py-0.5 rounded bg-purple-950/60 border border-purple-800/60 text-purple-300 font-mono text-[10px] mr-1">${escapeHtml(s)}</span>`).join('');
  1808. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  1809. const p2Name = c.phase2_name || `${c.name}_p2`;
  1810. tr.innerHTML = `
  1811. <td class="py-2.5 px-3 text-center">
  1812. ${isEstablished ? `
  1813. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  1814. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  1815. <span>UP</span>
  1816. </span>
  1817. ` : (c.disabled ? `
  1818. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  1819. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  1820. <span>DOWN</span>
  1821. </span>
  1822. ` : `
  1823. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  1824. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  1825. <span>IDLE</span>
  1826. </span>
  1827. `)}
  1828. </td>
  1829. <td class="py-2.5 px-4 font-bold text-white">
  1830. <div class="flex items-center gap-2">
  1831. <span class="text-amber-400">🛡</span>
  1832. <div>
  1833. <div>${escapeHtml(c.name)}</div>
  1834. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  1835. </div>
  1836. </div>
  1837. </td>
  1838. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  1839. <td class="py-2.5 px-4 font-sans">
  1840. <div class="flex items-center gap-1.5">
  1841. <span class="px-1.5 py-0.5 rounded bg-amber-500/10 text-amber-300 border border-amber-500/30 font-mono text-[10px] font-semibold">${ikeVersionBadge}</span>
  1842. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  1843. </div>
  1844. </td>
  1845. <td class="py-2.5 px-4">
  1846. <div class="space-y-1">
  1847. <div class="flex items-center flex-wrap gap-1">
  1848. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  1849. ${localBadges}
  1850. </div>
  1851. <div class="flex items-center flex-wrap gap-1">
  1852. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  1853. ${remoteBadges}
  1854. </div>
  1855. </div>
  1856. </td>
  1857. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  1858. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  1859. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  1860. </div>
  1861. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  1862. </td>
  1863. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  1864. ${isEstablished ? `
  1865. <button onclick="stopIPSecTunnel('${c.name}')" class="px-2 py-0.5 text-xs bg-rose-500/20 text-rose-400 hover:bg-rose-500/30 rounded border border-rose-500/30 font-medium">Bring Down</button>
  1866. ` : `
  1867. <button onclick="startIPSecTunnel('${c.name}')" class="px-2 py-0.5 text-xs bg-emerald-500/20 text-emerald-400 hover:bg-emerald-500/30 rounded border border-emerald-500/30 font-semibold">Bring Up</button>
  1868. `}
  1869. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1870. ${c.disabled ? 'Enable' : 'Disable'}
  1871. </button>
  1872. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  1873. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1874. </td>
  1875. `;
  1876. tbody.appendChild(tr);
  1877. });
  1878. }
  1879. } catch (err) {
  1880. console.error('Failed to load IPSec:', err);
  1881. }
  1882. }
  1883. function openAddIPSecModal() {
  1884. const modal = document.getElementById('ipsec-modal');
  1885. if (!modal) return;
  1886. const title = document.getElementById('ipsec-modal-title');
  1887. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  1888. // Phase 1 Fields
  1889. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  1890. const nameEl = document.getElementById('ipsec-modal-name');
  1891. if (nameEl) nameEl.readOnly = false;
  1892. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  1893. safeSetVal('ipsec-modal-ikever', 'ikev2');
  1894. safeSetVal('ipsec-modal-remotegw', '');
  1895. safeSetVal('ipsec-modal-localaddrs', '');
  1896. safeSetVal('ipsec-modal-comments', '');
  1897. safeSetVal('ipsec-modal-psk', '');
  1898. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  1899. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  1900. safeSetVal('ipsec-modal-ikekeylife', '86400');
  1901. safeSetVal('ipsec-modal-localid', '');
  1902. safeSetVal('ipsec-modal-remoteid', '');
  1903. safeSetVal('ipsec-modal-dpd', 'on-demand');
  1904. // Phase 2 Fields
  1905. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  1906. safeSetVal('ipsec-modal-espkeylife', '28800');
  1907. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  1908. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  1909. safeSetChecked('ipsec-modal-autostart', true);
  1910. safeSetChecked('ipsec-modal-disabled', false);
  1911. // Clear & Populate default dynamic subnets
  1912. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  1913. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  1914. if (localContainer) {
  1915. localContainer.innerHTML = '';
  1916. addIpsecLocalSubnet('192.168.10.0/24');
  1917. }
  1918. if (remoteContainer) {
  1919. remoteContainer.innerHTML = '';
  1920. addIpsecRemoteSubnet('192.168.20.0/24');
  1921. }
  1922. switchIpsecModalTab('p1');
  1923. modal.classList.remove('hidden');
  1924. }
  1925. function openEditIPSecModal(name) {
  1926. const modal = document.getElementById('ipsec-modal');
  1927. if (!modal) return;
  1928. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  1929. if (!conn) return;
  1930. const title = document.getElementById('ipsec-modal-title');
  1931. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  1932. // Phase 1 Fields
  1933. safeSetVal('ipsec-modal-name', conn.name);
  1934. const nameEl = document.getElementById('ipsec-modal-name');
  1935. if (nameEl) nameEl.readOnly = true;
  1936. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  1937. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  1938. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  1939. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  1940. safeSetVal('ipsec-modal-comments', conn.comment || '');
  1941. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  1942. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  1943. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  1944. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  1945. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  1946. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  1947. // Phase 2 Fields
  1948. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  1949. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  1950. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  1951. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  1952. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  1953. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  1954. // Populate dynamic subnets
  1955. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  1956. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  1957. if (localContainer) {
  1958. localContainer.innerHTML = '';
  1959. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  1960. locals.forEach(s => addIpsecLocalSubnet(s));
  1961. }
  1962. if (remoteContainer) {
  1963. remoteContainer.innerHTML = '';
  1964. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  1965. remotes.forEach(s => addIpsecRemoteSubnet(s));
  1966. }
  1967. switchIpsecModalTab('p1');
  1968. modal.classList.remove('hidden');
  1969. }
  1970. function closeAddIPSecModal() {
  1971. const modal = document.getElementById('ipsec-modal');
  1972. if (modal) modal.classList.add('hidden');
  1973. }
  1974. async function submitSaveIPSec(e) {
  1975. if (e) e.preventDefault();
  1976. const name = safeGetVal('ipsec-modal-name').trim();
  1977. if (!name) {
  1978. showToast('Error', 'Tunnel name is required', 'error');
  1979. return;
  1980. }
  1981. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  1982. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  1983. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  1984. const comments = safeGetVal('ipsec-modal-comments').trim();
  1985. const psk = safeGetVal('ipsec-modal-psk');
  1986. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  1987. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  1988. const localId = safeGetVal('ipsec-modal-localid').trim();
  1989. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  1990. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  1991. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  1992. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  1993. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  1994. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  1995. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  1996. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  1997. // Scrape dynamic local and remote subnets
  1998. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  1999. const localSubnets = [];
  2000. localInputs.forEach(inp => {
  2001. const v = inp.value.trim();
  2002. if (v) localSubnets.push(v);
  2003. });
  2004. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  2005. const remoteSubnets = [];
  2006. remoteInputs.forEach(inp => {
  2007. const v = inp.value.trim();
  2008. if (v) remoteSubnets.push(v);
  2009. });
  2010. try {
  2011. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  2012. method: 'POST',
  2013. headers: { 'Content-Type': 'application/json' },
  2014. body: JSON.stringify({
  2015. name,
  2016. comment: comments,
  2017. ike_version: ikeVersion,
  2018. local_addrs: localAddrs,
  2019. remote_addrs: remotegw,
  2020. preshared_key: psk,
  2021. ike_proposals: ikeProposals,
  2022. ike_keylife: ikeKeylife,
  2023. local_id: localId,
  2024. remote_id: remoteId,
  2025. dpd: dpd,
  2026. phase2_name: phase2Name,
  2027. esp_proposals: espProposals,
  2028. esp_keylife: espKeylife,
  2029. pfs_group: pfsGroup,
  2030. pfs: pfsGroup !== 'none',
  2031. local_subnets: localSubnets,
  2032. remote_subnets: remoteSubnets,
  2033. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2034. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2035. auto_start: autostart,
  2036. disabled
  2037. })
  2038. });
  2039. if (res.ok) {
  2040. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2041. closeAddIPSecModal();
  2042. loadIPSec(false);
  2043. } else {
  2044. const err = await res.json();
  2045. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2046. }
  2047. } catch (err) {
  2048. showToast('Error', err.message, 'error');
  2049. }
  2050. }
  2051. async function startIPSecTunnel(name) {
  2052. try {
  2053. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2054. if (res.ok) {
  2055. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2056. setTimeout(() => loadIPSec(false), 2000);
  2057. }
  2058. } catch (err) {
  2059. showToast('Error', err.message, 'error');
  2060. }
  2061. }
  2062. async function stopIPSecTunnel(name) {
  2063. try {
  2064. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2065. if (res.ok) {
  2066. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2067. loadIPSec(false);
  2068. }
  2069. } catch (err) {
  2070. showToast('Error', err.message, 'error');
  2071. }
  2072. }
  2073. async function toggleIPSecState(name, enable) {
  2074. try {
  2075. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2076. method: 'POST',
  2077. headers: { 'Content-Type': 'application/json' },
  2078. body: JSON.stringify({ enabled: enable })
  2079. });
  2080. if (res.ok) {
  2081. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2082. loadIPSec(false);
  2083. }
  2084. } catch (err) {
  2085. showToast('Error', err.message, 'error');
  2086. }
  2087. }
  2088. async function deleteIPSecConn(name) {
  2089. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2090. try {
  2091. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2092. if (res.ok) {
  2093. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2094. loadIPSec(false);
  2095. fetchData(false);
  2096. }
  2097. } catch (err) {
  2098. showToast('Error', err.message, 'error');
  2099. }
  2100. }
  2101. // ======================== L2TP Multi-Instance ========================
  2102. async function loadL2TP(populateInputs = true) {
  2103. try {
  2104. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2105. await fetchPPPProfilesList();
  2106. }
  2107. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2108. const list = await res.json();
  2109. state.l2tpList = Array.isArray(list) ? list : [];
  2110. const badge = document.getElementById('l2tp-count-badge');
  2111. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2112. const tbody = document.getElementById('l2tp-table-body');
  2113. const empty = document.getElementById('l2tp-empty');
  2114. if (!tbody) return;
  2115. tbody.innerHTML = '';
  2116. if (state.l2tpList.length === 0) {
  2117. if (empty) empty.classList.remove('hidden');
  2118. } else {
  2119. if (empty) empty.classList.add('hidden');
  2120. state.l2tpList.forEach(inst => {
  2121. const tr = document.createElement('tr');
  2122. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2123. tr.innerHTML = `
  2124. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2125. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2126. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2127. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2128. <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default-encryption')}</span></td>
  2129. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  2130. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2131. <td class="py-2.5 px-3 text-center">
  2132. <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'}">
  2133. ${inst.default_route ? 'Yes' : 'No'}
  2134. </span>
  2135. </td>
  2136. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2137. ${inst.running ? `
  2138. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2139. ` : `
  2140. <button onclick="connectL2TPInstance('${escapeHtml(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>
  2141. `}
  2142. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2143. ${inst.disabled ? 'Enable' : 'Disable'}
  2144. </button>
  2145. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2146. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2147. </td>
  2148. `;
  2149. tbody.appendChild(tr);
  2150. });
  2151. }
  2152. } catch (err) {
  2153. console.error('Failed to load L2TP:', err);
  2154. }
  2155. }
  2156. async function openAddL2TPModal() {
  2157. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2158. await fetchPPPProfilesList();
  2159. }
  2160. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2161. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2162. document.getElementById('l2tp-modal-name').readOnly = false;
  2163. document.getElementById('l2tp-modal-server').value = '';
  2164. document.getElementById('l2tp-modal-user').value = '';
  2165. document.getElementById('l2tp-modal-pass').value = '';
  2166. document.getElementById('l2tp-modal-ipsec').value = '';
  2167. document.getElementById('l2tp-modal-defroute').checked = true;
  2168. document.getElementById('l2tp-modal-disabled').checked = false;
  2169. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2170. document.getElementById('l2tp-modal').classList.remove('hidden');
  2171. }
  2172. async function openEditL2TPModal(name) {
  2173. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2174. await fetchPPPProfilesList();
  2175. }
  2176. const inst = (state.l2tpList || []).find(i => i.name === name);
  2177. if (!inst) return;
  2178. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2179. document.getElementById('l2tp-modal-name').value = inst.name;
  2180. document.getElementById('l2tp-modal-name').readOnly = true;
  2181. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2182. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2183. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2184. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2185. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2186. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2187. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2188. document.getElementById('l2tp-modal').classList.remove('hidden');
  2189. }
  2190. function closeL2TPModal() {
  2191. document.getElementById('l2tp-modal').classList.add('hidden');
  2192. }
  2193. async function submitSaveL2TP(e) {
  2194. e.preventDefault();
  2195. const name = document.getElementById('l2tp-modal-name').value.trim();
  2196. const server = document.getElementById('l2tp-modal-server').value.trim();
  2197. const user = document.getElementById('l2tp-modal-user').value.trim();
  2198. const pass = document.getElementById('l2tp-modal-pass').value;
  2199. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2200. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2201. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2202. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2203. try {
  2204. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2205. method: 'POST',
  2206. headers: { 'Content-Type': 'application/json' },
  2207. body: JSON.stringify({
  2208. name,
  2209. connect_to: server,
  2210. username: user,
  2211. password: pass,
  2212. profile: profile,
  2213. ipsec_secret: ipsec,
  2214. default_route: defRoute,
  2215. disabled
  2216. })
  2217. });
  2218. if (res.ok) {
  2219. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2220. closeL2TPModal();
  2221. loadL2TP(false);
  2222. fetchData(false);
  2223. }
  2224. } catch (err) {
  2225. showToast('Error', err.message, 'error');
  2226. }
  2227. }
  2228. async function connectL2TPInstance(name) {
  2229. try {
  2230. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2231. if (res.ok) {
  2232. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2233. setTimeout(() => loadL2TP(false), 2000);
  2234. }
  2235. } catch (err) {
  2236. showToast('Error', err.message, 'error');
  2237. }
  2238. }
  2239. async function disconnectL2TPInstance(name) {
  2240. try {
  2241. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2242. if (res.ok) {
  2243. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2244. loadL2TP(false);
  2245. }
  2246. } catch (err) {
  2247. showToast('Error', err.message, 'error');
  2248. }
  2249. }
  2250. async function toggleL2TPState(name, enable) {
  2251. try {
  2252. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2253. method: 'POST',
  2254. headers: { 'Content-Type': 'application/json' },
  2255. body: JSON.stringify({ enabled: enable })
  2256. });
  2257. if (res.ok) {
  2258. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2259. loadL2TP(false);
  2260. }
  2261. } catch (err) {
  2262. showToast('Error', err.message, 'error');
  2263. }
  2264. }
  2265. async function deleteL2TPInstance(name) {
  2266. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2267. try {
  2268. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2269. if (res.ok) {
  2270. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2271. loadL2TP(false);
  2272. fetchData(false);
  2273. }
  2274. } catch (err) {
  2275. showToast('Error', err.message, 'error');
  2276. }
  2277. }
  2278. // ======================== PPTP Multi-Instance ========================
  2279. async function loadPPTP(populateInputs = true) {
  2280. try {
  2281. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2282. await fetchPPPProfilesList();
  2283. }
  2284. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2285. const list = await res.json();
  2286. state.pptpList = Array.isArray(list) ? list : [];
  2287. const badge = document.getElementById('pptp-count-badge');
  2288. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2289. const tbody = document.getElementById('pptp-table-body');
  2290. const empty = document.getElementById('pptp-empty');
  2291. if (!tbody) return;
  2292. tbody.innerHTML = '';
  2293. if (state.pptpList.length === 0) {
  2294. if (empty) empty.classList.remove('hidden');
  2295. } else {
  2296. if (empty) empty.classList.add('hidden');
  2297. state.pptpList.forEach(inst => {
  2298. const tr = document.createElement('tr');
  2299. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2300. tr.innerHTML = `
  2301. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2302. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2303. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2304. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2305. <td class="py-2.5 px-3 font-mono text-purple-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default-encryption')}</span></td>
  2306. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  2307. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2308. <td class="py-2.5 px-3 text-center">
  2309. <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'}">
  2310. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2311. </span>
  2312. </td>
  2313. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2314. ${inst.running ? `
  2315. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2316. ` : `
  2317. <button onclick="connectPPTPInstance('${escapeHtml(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>
  2318. `}
  2319. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2320. ${inst.disabled ? 'Enable' : 'Disable'}
  2321. </button>
  2322. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2323. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2324. </td>
  2325. `;
  2326. tbody.appendChild(tr);
  2327. });
  2328. }
  2329. } catch (err) {
  2330. console.error('Failed to load PPTP:', err);
  2331. }
  2332. }
  2333. async function openAddPPTPModal() {
  2334. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2335. await fetchPPPProfilesList();
  2336. }
  2337. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2338. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2339. document.getElementById('pptp-modal-name').readOnly = false;
  2340. document.getElementById('pptp-modal-server').value = '';
  2341. document.getElementById('pptp-modal-user').value = '';
  2342. document.getElementById('pptp-modal-pass').value = '';
  2343. document.getElementById('pptp-modal-mppe').checked = true;
  2344. document.getElementById('pptp-modal-defroute').checked = true;
  2345. document.getElementById('pptp-modal-disabled').checked = false;
  2346. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2347. document.getElementById('pptp-modal').classList.remove('hidden');
  2348. }
  2349. async function openEditPPTPModal(name) {
  2350. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2351. await fetchPPPProfilesList();
  2352. }
  2353. const inst = (state.pptpList || []).find(i => i.name === name);
  2354. if (!inst) return;
  2355. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2356. document.getElementById('pptp-modal-name').value = inst.name;
  2357. document.getElementById('pptp-modal-name').readOnly = true;
  2358. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2359. document.getElementById('pptp-modal-user').value = inst.username || '';
  2360. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2361. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2362. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2363. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2364. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2365. document.getElementById('pptp-modal').classList.remove('hidden');
  2366. }
  2367. function closePPTPModal() {
  2368. document.getElementById('pptp-modal').classList.add('hidden');
  2369. }
  2370. async function submitSavePPTP(e) {
  2371. e.preventDefault();
  2372. const name = document.getElementById('pptp-modal-name').value.trim();
  2373. const server = document.getElementById('pptp-modal-server').value.trim();
  2374. const user = document.getElementById('pptp-modal-user').value.trim();
  2375. const pass = document.getElementById('pptp-modal-pass').value;
  2376. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  2377. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2378. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2379. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2380. try {
  2381. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2382. method: 'POST',
  2383. headers: { 'Content-Type': 'application/json' },
  2384. body: JSON.stringify({
  2385. name,
  2386. connect_to: server,
  2387. username: user,
  2388. password: pass,
  2389. profile: profile,
  2390. require_mppe: mppe,
  2391. default_route: defRoute,
  2392. auto_reconnect: true,
  2393. disabled
  2394. })
  2395. });
  2396. if (res.ok) {
  2397. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2398. closePPTPModal();
  2399. loadPPTP(false);
  2400. fetchData(false);
  2401. }
  2402. } catch (err) {
  2403. showToast('Error', err.message, 'error');
  2404. }
  2405. }
  2406. async function connectPPTPInstance(name) {
  2407. try {
  2408. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2409. if (res.ok) {
  2410. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2411. setTimeout(() => loadPPTP(false), 2000);
  2412. }
  2413. } catch (err) {
  2414. showToast('Error', err.message, 'error');
  2415. }
  2416. }
  2417. async function disconnectPPTPInstance(name) {
  2418. try {
  2419. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2420. if (res.ok) {
  2421. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2422. loadPPTP(false);
  2423. }
  2424. } catch (err) {
  2425. showToast('Error', err.message, 'error');
  2426. }
  2427. }
  2428. async function togglePPTPState(name, enable) {
  2429. try {
  2430. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2431. method: 'POST',
  2432. headers: { 'Content-Type': 'application/json' },
  2433. body: JSON.stringify({ enabled: enable })
  2434. });
  2435. if (res.ok) {
  2436. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2437. loadPPTP(false);
  2438. }
  2439. } catch (err) {
  2440. showToast('Error', err.message, 'error');
  2441. }
  2442. }
  2443. async function deletePPTPInstance(name) {
  2444. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2445. try {
  2446. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2447. if (res.ok) {
  2448. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2449. loadPPTP(false);
  2450. fetchData(false);
  2451. }
  2452. } catch (err) {
  2453. showToast('Error', err.message, 'error');
  2454. }
  2455. }
  2456. // ---------------- Modal & Helper Functions ----------------
  2457. function openVlanModal(defaultParent = '') {
  2458. const select = document.getElementById('vlan-parent');
  2459. select.innerHTML = '';
  2460. const allIfaces = state.interfaces || [];
  2461. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2462. if (eligible.length === 0) {
  2463. const opt = document.createElement('option');
  2464. opt.value = '';
  2465. opt.innerText = 'No VLAN-capable interfaces available';
  2466. select.appendChild(opt);
  2467. } else {
  2468. eligible.forEach(i => {
  2469. const opt = document.createElement('option');
  2470. opt.value = i.name;
  2471. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2472. if (i.name === defaultParent) opt.selected = true;
  2473. select.appendChild(opt);
  2474. });
  2475. }
  2476. document.getElementById('vlan-id').value = '';
  2477. document.getElementById('vlan-name').value = '';
  2478. document.getElementById('vlan-ip').value = '';
  2479. document.getElementById('vlan-desc').value = '';
  2480. autoSuggestVlanName();
  2481. document.getElementById('vlan-modal').classList.remove('hidden');
  2482. }
  2483. function closeVlanModal() {
  2484. document.getElementById('vlan-modal').classList.add('hidden');
  2485. }
  2486. function autoSuggestVlanName() {
  2487. const parent = document.getElementById('vlan-parent').value;
  2488. if (!parent) return;
  2489. const id = document.getElementById('vlan-id').value;
  2490. const nameInput = document.getElementById('vlan-name');
  2491. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  2492. }
  2493. function setSubnetPreset(cidr) {
  2494. const ipInput = document.getElementById('vlan-ip');
  2495. const id = document.getElementById('vlan-id').value || '10';
  2496. ipInput.value = `192.168.${id}.1${cidr}`;
  2497. }
  2498. async function submitCreateVlan(e) {
  2499. e.preventDefault();
  2500. const btn = document.getElementById('vlan-submit-btn');
  2501. btn.disabled = true;
  2502. btn.innerText = 'Creating...';
  2503. const parent = document.getElementById('vlan-parent').value;
  2504. if (!parent) {
  2505. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  2506. btn.disabled = false;
  2507. btn.innerText = 'Create VLAN';
  2508. return;
  2509. }
  2510. const id = parseInt(document.getElementById('vlan-id').value, 10);
  2511. const name = document.getElementById('vlan-name').value.trim();
  2512. const ip = document.getElementById('vlan-ip').value.trim();
  2513. const role = document.getElementById('vlan-role').value;
  2514. const desc = document.getElementById('vlan-desc').value.trim();
  2515. try {
  2516. const res = await fetch(`${API_BASE}/vlans`, {
  2517. method: 'POST',
  2518. headers: { 'Content-Type': 'application/json' },
  2519. body: JSON.stringify({
  2520. parent_name: parent,
  2521. vlan_id: id,
  2522. name: name,
  2523. ip_address: ip,
  2524. role: role,
  2525. description: desc,
  2526. mtu: 1500,
  2527. auto_up: true
  2528. })
  2529. });
  2530. const data = await res.json();
  2531. if (res.ok) {
  2532. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  2533. state.expandedParents.add(parent);
  2534. closeVlanModal();
  2535. await fetchData(true);
  2536. if (state.activeTab !== 'interfaces') navigate('interfaces');
  2537. } else {
  2538. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  2539. }
  2540. } catch (err) {
  2541. showToast('Error', err.message, 'error');
  2542. } finally {
  2543. btn.disabled = false;
  2544. btn.innerText = 'Create VLAN';
  2545. }
  2546. }
  2547. async function confirmDeleteVlan(name) {
  2548. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  2549. try {
  2550. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2551. if (res.ok) {
  2552. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  2553. closeIfaceModal();
  2554. fetchData(true);
  2555. }
  2556. } catch (err) {
  2557. showToast('Error', err.message, 'error');
  2558. }
  2559. }
  2560. function openIfaceModal(name) {
  2561. const iface = (state.interfaces || []).find(i => i.name === name);
  2562. if (!iface) return;
  2563. state.currentModalIface = iface.name;
  2564. document.getElementById('modal-iface-name').innerText = iface.name;
  2565. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  2566. document.getElementById('modal-iface-mtu').value = iface.mtu;
  2567. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  2568. document.getElementById('modal-iface-desc').value = iface.description || '';
  2569. const delBtn = document.getElementById('modal-delete-vlan-btn');
  2570. if (iface.is_vlan) {
  2571. delBtn.classList.remove('hidden');
  2572. } else {
  2573. delBtn.classList.add('hidden');
  2574. }
  2575. renderModalIPs(iface);
  2576. document.getElementById('iface-modal').classList.remove('hidden');
  2577. }
  2578. function renderModalIPs(iface) {
  2579. const container = document.getElementById('modal-ip-list');
  2580. container.innerHTML = '';
  2581. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  2582. if (addrs.length === 0) {
  2583. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  2584. return;
  2585. }
  2586. addrs.forEach(addr => {
  2587. const row = document.createElement('div');
  2588. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  2589. row.innerHTML = `
  2590. <span class="text-white">${addr}</span>
  2591. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  2592. `;
  2593. container.appendChild(row);
  2594. });
  2595. }
  2596. function closeIfaceModal() {
  2597. document.getElementById('iface-modal').classList.add('hidden');
  2598. state.currentModalIface = null;
  2599. }
  2600. async function setIfaceState(name, newState) {
  2601. await toggleInterfaceState(name, newState);
  2602. const updated = (state.interfaces || []).find(i => i.name === name);
  2603. if (updated) openIfaceModal(name);
  2604. }
  2605. async function applyMTU() {
  2606. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  2607. try {
  2608. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  2609. method: 'POST',
  2610. headers: { 'Content-Type': 'application/json' },
  2611. body: JSON.stringify({ mtu })
  2612. });
  2613. if (res.ok) {
  2614. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  2615. fetchData(false);
  2616. }
  2617. } catch (err) {
  2618. showToast('Error', err.message, 'error');
  2619. }
  2620. }
  2621. async function addInterfaceIP() {
  2622. const ip = document.getElementById('modal-new-ip').value.trim();
  2623. if (!ip) return;
  2624. try {
  2625. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2626. method: 'POST',
  2627. headers: { 'Content-Type': 'application/json' },
  2628. body: JSON.stringify({ ip })
  2629. });
  2630. if (res.ok) {
  2631. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  2632. document.getElementById('modal-new-ip').value = '';
  2633. await fetchData(false);
  2634. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2635. if (iface) renderModalIPs(iface);
  2636. } else {
  2637. const err = await res.json();
  2638. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  2639. }
  2640. } catch (err) {
  2641. showToast('Error', err.message, 'error');
  2642. }
  2643. }
  2644. async function removeInterfaceIP(ip) {
  2645. if (!confirm(`Remove IP ${ip}?`)) return;
  2646. try {
  2647. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2648. method: 'DELETE',
  2649. headers: { 'Content-Type': 'application/json' },
  2650. body: JSON.stringify({ ip })
  2651. });
  2652. if (res.ok) {
  2653. showToast('IP Removed', `Removed ${ip}`, 'success');
  2654. await fetchData(false);
  2655. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2656. if (iface) renderModalIPs(iface);
  2657. }
  2658. } catch (err) {
  2659. showToast('Error', err.message, 'error');
  2660. }
  2661. }
  2662. async function saveInterfaceMetadata() {
  2663. const role = document.getElementById('modal-iface-role').value;
  2664. const desc = document.getElementById('modal-iface-desc').value.trim();
  2665. try {
  2666. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/metadata`, {
  2667. method: 'POST',
  2668. headers: { 'Content-Type': 'application/json' },
  2669. body: JSON.stringify({ role, description: desc })
  2670. });
  2671. if (res.ok) {
  2672. showToast('Saved', 'Metadata updated', 'success');
  2673. closeIfaceModal();
  2674. fetchData(false);
  2675. }
  2676. } catch (err) {
  2677. showToast('Error', err.message, 'error');
  2678. }
  2679. }
  2680. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  2681. state.fwSubTab = 'filter';
  2682. state.routesSubTab = 'routes';
  2683. function renderRuleFlag(disabled, hasComment) {
  2684. let flags = '';
  2685. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  2686. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  2687. return flags || '<span class="text-slate-600">-</span>';
  2688. }
  2689. function renderActionBadge(action) {
  2690. const act = (action || '').toLowerCase();
  2691. let color = 'bg-slate-800 text-slate-300';
  2692. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  2693. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  2694. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  2695. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  2696. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  2697. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  2698. }
  2699. function switchFWSubTab(tab) {
  2700. state.fwSubTab = tab;
  2701. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  2702. tabs.forEach(t => {
  2703. const panel = document.getElementById(`fw-subtab-${t}`);
  2704. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  2705. if (panel) {
  2706. if (t === tab) panel.classList.remove('hidden');
  2707. else panel.classList.add('hidden');
  2708. }
  2709. if (btn) {
  2710. if (t === tab) {
  2711. 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';
  2712. } else {
  2713. 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';
  2714. }
  2715. }
  2716. });
  2717. const addBtn = document.getElementById('fw-primary-add-btn');
  2718. if (addBtn) {
  2719. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  2720. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  2721. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  2722. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  2723. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  2724. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  2725. }
  2726. if (tab === 'geo') loadGeoIP();
  2727. if (tab === 'connections') loadConnections();
  2728. setTimeout(initTableSorting, 50);
  2729. }
  2730. function openCurrentFWModal() {
  2731. if (state.fwSubTab === 'filter') openAddFilterModal();
  2732. else if (state.fwSubTab === 'nat') openAddNATModal();
  2733. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  2734. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  2735. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  2736. else if (state.fwSubTab === 'connections') loadConnections();
  2737. }
  2738. async function loadFirewall(populateDropdowns = true) {
  2739. try {
  2740. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  2741. fetch(`${API_BASE}/firewall/summary`),
  2742. fetch(`${API_BASE}/firewall/filter`),
  2743. fetch(`${API_BASE}/firewall/nat`),
  2744. fetch(`${API_BASE}/firewall/mangle`),
  2745. fetch(`${API_BASE}/firewall/address-lists`),
  2746. fetch(`${API_BASE}/firewall/geoip/status`),
  2747. fetch(`${API_BASE}/firewall/geoip/countries`)
  2748. ]);
  2749. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  2750. if (filterRes.ok) state.filterRules = await filterRes.json();
  2751. if (natRes.ok) state.natRules = await natRes.json();
  2752. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  2753. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  2754. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  2755. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  2756. // Badges
  2757. const bFilter = document.getElementById('fw-badge-filter');
  2758. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  2759. const bNat = document.getElementById('fw-badge-nat');
  2760. if (bNat) bNat.innerText = (state.natRules || []).length;
  2761. const bMangle = document.getElementById('fw-badge-mangle');
  2762. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  2763. const bAddr = document.getElementById('fw-badge-addrlist');
  2764. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  2765. const bGeo = document.getElementById('fw-badge-geo');
  2766. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  2767. renderFilterRules();
  2768. renderNATRules();
  2769. renderMangleRules();
  2770. renderAddressLists();
  2771. renderGeoCountries();
  2772. if (state.fwSubTab === 'connections') {
  2773. loadConnections();
  2774. }
  2775. } catch (err) {
  2776. console.error('Failed to load firewall:', err);
  2777. }
  2778. }
  2779. // ----------------- Filter Rules -----------------
  2780. function renderFilterRules() {
  2781. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  2782. const tbody = document.getElementById('filter-table-body');
  2783. const empty = document.getElementById('filter-empty');
  2784. if (!tbody) return;
  2785. tbody.innerHTML = '';
  2786. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2787. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2788. if (rules.length === 0) {
  2789. empty?.classList.remove('hidden');
  2790. return;
  2791. }
  2792. empty?.classList.add('hidden');
  2793. rules.forEach((r, idx) => {
  2794. const tr = document.createElement('tr');
  2795. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2796. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2797. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2798. let actionExtra = '';
  2799. if (r.action === 'reject') {
  2800. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  2801. } else if (r.action === 'jump') {
  2802. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  2803. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  2804. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  2805. } else if (r.action === 'log' && r.log_prefix) {
  2806. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  2807. }
  2808. tr.innerHTML = `
  2809. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2810. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2811. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2812. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2813. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2814. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2815. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2816. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2817. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  2818. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2819. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2820. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2821. </td>
  2822. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2823. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2824. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2825. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2826. <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>
  2827. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2828. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2829. </td>
  2830. `;
  2831. tbody.appendChild(tr);
  2832. });
  2833. }
  2834. function formatTarget(addr, list, geo) {
  2835. const parts = [];
  2836. if (addr) parts.push(`<span>${addr}</span>`);
  2837. if (list) {
  2838. const inv = list.startsWith('!') ? '!' : '';
  2839. const clean = list.replace(/^!/, '');
  2840. 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>`);
  2841. }
  2842. if (geo) {
  2843. const inv = geo.startsWith('!') ? '!' : '';
  2844. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  2845. 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>`);
  2846. }
  2847. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  2848. return parts.join(' ');
  2849. }
  2850. function populateInterfaceSelect(selectId, currentVal = '') {
  2851. const sel = document.getElementById(selectId);
  2852. if (!sel) return;
  2853. sel.innerHTML = '<option value="">(Any Interface)</option>';
  2854. (state.interfaces || []).forEach(i => {
  2855. const opt = document.createElement('option');
  2856. opt.value = i.name;
  2857. opt.innerText = `${i.name} (${i.role || i.type})`;
  2858. if (i.name === currentVal) opt.selected = true;
  2859. sel.appendChild(opt);
  2860. });
  2861. }
  2862. function populateAddressListSelect(selectId, currentVal = '') {
  2863. const sel = document.getElementById(selectId);
  2864. if (!sel) return;
  2865. sel.innerHTML = '<option value="">(None)</option>';
  2866. const cleanVal = (currentVal || '').replace(/^!/, '');
  2867. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  2868. customNames.forEach(name => {
  2869. const count = (state.addressLists || []).filter(a => a.name === name).length;
  2870. const opt = document.createElement('option');
  2871. opt.value = name;
  2872. opt.innerText = `${name} (${count} entries)`;
  2873. if (name === cleanVal) opt.selected = true;
  2874. sel.appendChild(opt);
  2875. });
  2876. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  2877. const opt = document.createElement('option');
  2878. opt.value = cleanVal;
  2879. opt.innerText = cleanVal;
  2880. opt.selected = true;
  2881. sel.appendChild(opt);
  2882. }
  2883. populateCommonAddrListDatalist();
  2884. }
  2885. function populateCommonAddrListDatalist() {
  2886. const dl = document.getElementById('fw-addrlist-datalist');
  2887. if (!dl) return;
  2888. dl.innerHTML = '';
  2889. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  2890. names.forEach(name => {
  2891. const opt = document.createElement('option');
  2892. opt.value = name;
  2893. dl.appendChild(opt);
  2894. });
  2895. }
  2896. function populateGeoIPSelect(selectId, currentVal = '') {
  2897. const sel = document.getElementById(selectId);
  2898. if (!sel) return;
  2899. sel.innerHTML = '<option value="">(None)</option>';
  2900. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  2901. // Presets optgroup
  2902. const grpPresets = document.createElement('optgroup');
  2903. grpPresets.label = '⚡ Regional Presets';
  2904. const presets = [
  2905. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  2906. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  2907. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  2908. ];
  2909. presets.forEach(p => {
  2910. const opt = document.createElement('option');
  2911. opt.value = p.code;
  2912. opt.innerText = p.label;
  2913. if (p.code === cleanVal) opt.selected = true;
  2914. grpPresets.appendChild(opt);
  2915. });
  2916. sel.appendChild(grpPresets);
  2917. // All Countries optgroup
  2918. const grpCountries = document.createElement('optgroup');
  2919. grpCountries.label = '🌍 All Countries';
  2920. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  2921. countries.forEach(c => {
  2922. const opt = document.createElement('option');
  2923. opt.value = c.code;
  2924. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  2925. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  2926. if (c.code === cleanVal) opt.selected = true;
  2927. grpCountries.appendChild(opt);
  2928. });
  2929. sel.appendChild(grpCountries);
  2930. }
  2931. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  2932. function switchFwRuleTab(tab) {
  2933. state.activeFwRuleTab = tab;
  2934. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  2935. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  2936. btn.classList.add('text-slate-400', 'border-transparent');
  2937. });
  2938. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  2939. if (activeBtn) {
  2940. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  2941. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  2942. }
  2943. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  2944. const activePane = document.getElementById(`fw-pane-${tab}`);
  2945. if (activePane) activePane.classList.remove('hidden');
  2946. if (tab === 'statistics') {
  2947. startFwStatPolling();
  2948. } else {
  2949. stopFwStatPolling();
  2950. }
  2951. }
  2952. function toggleFwField(fieldKey, expand) {
  2953. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  2954. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  2955. if (!plusBtn || !fieldBox) return;
  2956. if (expand) {
  2957. plusBtn.classList.add('hidden');
  2958. fieldBox.classList.remove('hidden');
  2959. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2960. if (valInput) valInput.focus();
  2961. } else {
  2962. fieldBox.classList.add('hidden');
  2963. plusBtn.classList.remove('hidden');
  2964. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2965. if (valInput) {
  2966. if (valInput.tagName === 'SELECT') {
  2967. valInput.selectedIndex = 0;
  2968. } else {
  2969. valInput.value = '';
  2970. }
  2971. }
  2972. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  2973. if (invInput) invInput.checked = false;
  2974. if (fieldKey === 'cs') {
  2975. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  2976. const el = document.getElementById(id);
  2977. if (el) el.checked = false;
  2978. });
  2979. }
  2980. if (fieldKey === 'natstate') {
  2981. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  2982. const el = document.getElementById(id);
  2983. if (el) el.checked = false;
  2984. });
  2985. }
  2986. if (fieldKey === 'days') {
  2987. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  2988. const el = document.getElementById(`fw-day-${d}`);
  2989. if (el) el.checked = true;
  2990. });
  2991. }
  2992. }
  2993. }
  2994. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  2995. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  2996. toggleFwField(fieldKey, true);
  2997. let strVal = String(value);
  2998. if (hasInvert) {
  2999. const inv = strVal.startsWith('!');
  3000. if (inv) strVal = strVal.slice(1);
  3001. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3002. if (invEl) invEl.checked = inv;
  3003. }
  3004. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3005. if (valEl) valEl.value = strVal;
  3006. } else {
  3007. toggleFwField(fieldKey, false);
  3008. }
  3009. }
  3010. function getFwFieldVal(fieldKey, hasInvert = false) {
  3011. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3012. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3013. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3014. let v = valEl ? valEl.value.trim() : '';
  3015. if (!v) return '';
  3016. if (hasInvert) {
  3017. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3018. if (invEl && invEl.checked) {
  3019. v = '!' + v.replace(/^!/, '');
  3020. }
  3021. }
  3022. return v;
  3023. }
  3024. function toggleMaximizeFilterModal() {
  3025. const win = document.getElementById('filter-modal-window');
  3026. if (!win) return;
  3027. if (win.classList.contains('max-w-[720px]')) {
  3028. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3029. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3030. } else {
  3031. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3032. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3033. }
  3034. }
  3035. function openAddFilterModal() {
  3036. switchFwRuleTab('general');
  3037. const badge = document.getElementById('fw-modal-badge');
  3038. if (badge) badge.innerText = 'New...';
  3039. document.getElementById('filter-modal-id').value = '';
  3040. document.getElementById('filter-modal-enabled').checked = true;
  3041. document.getElementById('filter-modal-comment').value = '';
  3042. document.getElementById('filter-modal-chain').value = 'forward';
  3043. document.getElementById('filter-modal-action').value = 'accept';
  3044. document.getElementById('filter-modal-log').checked = false;
  3045. populateInterfaceSelect('fw-val-iniface');
  3046. populateInterfaceSelect('fw-val-outiface');
  3047. populateAddressListSelect('fw-val-srclist');
  3048. populateAddressListSelect('fw-val-dstlist');
  3049. populateGeoIPSelect('fw-val-srcgeo');
  3050. populateGeoIPSelect('fw-val-dstgeo');
  3051. const allFieldKeys = [
  3052. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3053. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3054. 'routingmark', 'conntype', 'cs', 'natstate',
  3055. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3056. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3057. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3058. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3059. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3060. ];
  3061. allFieldKeys.forEach(k => toggleFwField(k, false));
  3062. resetCurrentRuleCounters();
  3063. toggleFilterActionFields();
  3064. document.getElementById('filter-modal').classList.remove('hidden');
  3065. }
  3066. function openEditFilterModal(id) {
  3067. const r = (state.filterRules || []).find(rule => rule.id === id);
  3068. if (!r) return;
  3069. switchFwRuleTab('general');
  3070. const badge = document.getElementById('fw-modal-badge');
  3071. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3072. document.getElementById('filter-modal-id').value = r.id;
  3073. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  3074. document.getElementById('filter-modal-comment').value = r.comment || '';
  3075. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  3076. document.getElementById('filter-modal-action').value = r.action || 'accept';
  3077. document.getElementById('filter-modal-log').checked = !!r.log;
  3078. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3079. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3080. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3081. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3082. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  3083. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  3084. setFwFieldVal('src', r.src_address, true);
  3085. setFwFieldVal('dst', r.dst_address, true);
  3086. setFwFieldVal('srclist', r.src_address_list, true);
  3087. setFwFieldVal('dstlist', r.dst_address_list, true);
  3088. setFwFieldVal('srcgeo', r.src_geoip, true);
  3089. setFwFieldVal('dstgeo', r.dst_geoip, true);
  3090. if (r.protocol && r.protocol !== 'all') {
  3091. setFwFieldVal('proto', r.protocol, true);
  3092. } else {
  3093. toggleFwField('proto', false);
  3094. }
  3095. setFwFieldVal('sport', r.src_port, true);
  3096. setFwFieldVal('dport', r.dst_port, true);
  3097. setFwFieldVal('anyport', r.any_port, true);
  3098. setFwFieldVal('iniface', r.in_interface, true);
  3099. setFwFieldVal('outiface', r.out_interface, true);
  3100. setFwFieldVal('inifacelist', r.in_interface_list, true);
  3101. setFwFieldVal('outifacelist', r.out_interface_list, true);
  3102. setFwFieldVal('pktmark', r.packet_mark, true);
  3103. setFwFieldVal('connmark', r.connection_mark, true);
  3104. setFwFieldVal('routingmark', r.routing_mark, true);
  3105. setFwFieldVal('conntype', r.connection_type, false);
  3106. const states = r.connection_state || [];
  3107. if (states.length > 0) {
  3108. toggleFwField('cs', true);
  3109. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  3110. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  3111. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  3112. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  3113. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  3114. } else {
  3115. toggleFwField('cs', false);
  3116. }
  3117. const natStates = r.connection_nat_state || [];
  3118. if (natStates.length > 0) {
  3119. toggleFwField('natstate', true);
  3120. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  3121. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  3122. } else {
  3123. toggleFwField('natstate', false);
  3124. }
  3125. // Advanced tab fields
  3126. setFwFieldVal('layer7', r.layer7_protocol, false);
  3127. setFwFieldVal('content', r.content, false);
  3128. setFwFieldVal('connbytes', r.connection_bytes, false);
  3129. setFwFieldVal('connrate', r.connection_rate, false);
  3130. setFwFieldVal('pcc', r.pcc, false);
  3131. setFwFieldVal('srcmac', r.src_mac_address, true);
  3132. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  3133. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  3134. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3135. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3136. setFwFieldVal('ipsec', r.ipsec_policy, false);
  3137. setFwFieldVal('tlshost', r.tls_host, false);
  3138. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  3139. setFwFieldVal('priority', r.priority, false);
  3140. setFwFieldVal('dscp', r.dscp, false);
  3141. setFwFieldVal('tcpmss', r.tcp_mss, false);
  3142. if (r.tos) {
  3143. const tosEl = document.getElementById('fw-val-tos');
  3144. if (tosEl) tosEl.value = r.tos;
  3145. }
  3146. setFwFieldVal('pktsize', r.packet_size, false);
  3147. setFwFieldVal('random', r.random, false);
  3148. setFwFieldVal('tcpflags', r.tcp_flags, false);
  3149. setFwFieldVal('icmpoptions', r.icmp_options, false);
  3150. setFwFieldVal('ipv4options', r.ipv4_options, false);
  3151. setFwFieldVal('ttl', r.ttl, false);
  3152. // Extra tab fields
  3153. setFwFieldVal('time', r.time, false);
  3154. if (r.days) {
  3155. toggleFwField('days', true);
  3156. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3157. const chk = document.getElementById(`fw-day-${d}`);
  3158. if (chk) chk.checked = r.days.includes(d);
  3159. });
  3160. } else {
  3161. toggleFwField('days', false);
  3162. }
  3163. setFwFieldVal('limit', r.limit, false);
  3164. setFwFieldVal('dstlimit', r.dst_limit, false);
  3165. setFwFieldVal('psd', r.psd, false);
  3166. // Action fields
  3167. if (r.reject_with) {
  3168. const rwEl = document.getElementById('filter-modal-rejectwith');
  3169. if (rwEl) rwEl.value = r.reject_with;
  3170. }
  3171. if (r.jump_target) {
  3172. const jtEl = document.getElementById('filter-modal-jumptarget');
  3173. if (jtEl) jtEl.value = r.jump_target;
  3174. }
  3175. if (r.address_list) {
  3176. const alEl = document.getElementById('filter-modal-action-addrlist');
  3177. if (alEl) alEl.value = r.address_list;
  3178. }
  3179. if (r.address_list_timeout) {
  3180. const toEl = document.getElementById('filter-modal-action-timeout');
  3181. if (toEl) toEl.value = r.address_list_timeout;
  3182. }
  3183. setFwFieldVal('logprefix', r.log_prefix, false);
  3184. // Statistics
  3185. const bEl = document.getElementById('fw-stat-bytes');
  3186. const pEl = document.getElementById('fw-stat-packets');
  3187. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3188. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3189. state.fwLastBytes = r.bytes || 0;
  3190. state.fwLastPackets = r.packets || 0;
  3191. state.fwLastTimestamp = Date.now();
  3192. state.fwStatRateHistory = new Array(30).fill(0);
  3193. state.fwStatPktHistory = new Array(30).fill(0);
  3194. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3195. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3196. toggleFilterActionFields();
  3197. document.getElementById('filter-modal').classList.remove('hidden');
  3198. }
  3199. function closeFilterModal() {
  3200. stopFwStatPolling();
  3201. document.getElementById('filter-modal').classList.add('hidden');
  3202. }
  3203. function toggleFilterActionFields() {
  3204. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  3205. const rejectBox = document.getElementById('filter-action-reject-box');
  3206. const jumpBox = document.getElementById('filter-action-jump-box');
  3207. const addrBox = document.getElementById('filter-action-addrlist-box');
  3208. if (rejectBox) {
  3209. if (act === 'reject') rejectBox.classList.remove('hidden');
  3210. else rejectBox.classList.add('hidden');
  3211. }
  3212. if (jumpBox) {
  3213. if (act === 'jump') jumpBox.classList.remove('hidden');
  3214. else jumpBox.classList.add('hidden');
  3215. }
  3216. if (addrBox) {
  3217. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  3218. addrBox.classList.remove('hidden');
  3219. } else {
  3220. addrBox.classList.add('hidden');
  3221. }
  3222. }
  3223. if (act === 'log') {
  3224. const logEl = document.getElementById('filter-modal-log');
  3225. if (logEl) logEl.checked = true;
  3226. toggleFwField('logprefix', true);
  3227. }
  3228. }
  3229. function toggleFwLogPrefix() {
  3230. const isLog = document.getElementById('filter-modal-log')?.checked;
  3231. toggleFwField('logprefix', !!isLog);
  3232. }
  3233. function copyFilterRule() {
  3234. document.getElementById('filter-modal-id').value = '';
  3235. const badge = document.getElementById('fw-modal-badge');
  3236. if (badge) badge.innerText = 'New...';
  3237. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  3238. }
  3239. function resetCurrentRuleCounters() {
  3240. state.fwStatRateHistory = new Array(30).fill(0);
  3241. state.fwStatPktHistory = new Array(30).fill(0);
  3242. state.fwLastBytes = 0;
  3243. state.fwLastPackets = 0;
  3244. state.fwLastTimestamp = Date.now();
  3245. const bEl = document.getElementById('fw-stat-bytes');
  3246. const pEl = document.getElementById('fw-stat-packets');
  3247. const rEl = document.getElementById('fw-stat-rate');
  3248. const prEl = document.getElementById('fw-stat-pktrate');
  3249. if (bEl) bEl.value = '0 B';
  3250. if (pEl) pEl.value = '0';
  3251. if (rEl) rEl.value = '0 bps';
  3252. if (prEl) prEl.value = '0 p/s';
  3253. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3254. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3255. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  3256. }
  3257. async function resetAllFwCounters() {
  3258. try {
  3259. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3260. if (res.ok) {
  3261. resetCurrentRuleCounters();
  3262. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  3263. loadFirewall(false);
  3264. }
  3265. } catch (err) {
  3266. showToast('Error', err.message, 'error');
  3267. }
  3268. }
  3269. async function applyFilterRule(closeAfter = false) {
  3270. const id = document.getElementById('filter-modal-id').value;
  3271. const chain = document.getElementById('filter-modal-chain').value;
  3272. const action = document.getElementById('filter-modal-action').value;
  3273. const comment = document.getElementById('filter-modal-comment').value.trim();
  3274. const enabled = document.getElementById('filter-modal-enabled').checked;
  3275. const src = getFwFieldVal('src', true);
  3276. const dst = getFwFieldVal('dst', true);
  3277. const srclist = getFwFieldVal('srclist', true);
  3278. const dstlist = getFwFieldVal('dstlist', true);
  3279. const srcgeo = getFwFieldVal('srcgeo', true);
  3280. const dstgeo = getFwFieldVal('dstgeo', true);
  3281. const proto = getFwFieldVal('proto', true);
  3282. const sport = getFwFieldVal('sport', true);
  3283. const dport = getFwFieldVal('dport', true);
  3284. const anyport = getFwFieldVal('anyport', true);
  3285. const iniface = getFwFieldVal('iniface', true);
  3286. const outiface = getFwFieldVal('outiface', true);
  3287. const inifacelist = getFwFieldVal('inifacelist', true);
  3288. const outifacelist = getFwFieldVal('outifacelist', true);
  3289. const pktmark = getFwFieldVal('pktmark', true);
  3290. const connmark = getFwFieldVal('connmark', true);
  3291. const routingmark = getFwFieldVal('routingmark', true);
  3292. const conntype = getFwFieldVal('conntype', false);
  3293. const states = [];
  3294. const csBox = document.getElementById('fw-field-cs');
  3295. if (csBox && !csBox.classList.contains('hidden')) {
  3296. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  3297. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  3298. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  3299. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  3300. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  3301. }
  3302. const natStates = [];
  3303. const natBox = document.getElementById('fw-field-natstate');
  3304. if (natBox && !natBox.classList.contains('hidden')) {
  3305. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  3306. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  3307. }
  3308. const payload = {
  3309. id,
  3310. chain,
  3311. action,
  3312. protocol: proto || 'all',
  3313. src_address: src,
  3314. dst_address: dst,
  3315. src_port: sport,
  3316. dst_port: dport,
  3317. any_port: anyport,
  3318. in_interface: iniface,
  3319. out_interface: outiface,
  3320. in_interface_list: inifacelist,
  3321. out_interface_list: outifacelist,
  3322. packet_mark: pktmark,
  3323. connection_mark: connmark,
  3324. routing_mark: routingmark,
  3325. connection_type: conntype,
  3326. connection_state: states,
  3327. connection_nat_state: natStates,
  3328. src_address_list: srclist,
  3329. dst_address_list: dstlist,
  3330. src_geoip: srcgeo,
  3331. dst_geoip: dstgeo,
  3332. comment,
  3333. disabled: !enabled,
  3334. // Advanced tab
  3335. layer7_protocol: getFwFieldVal('layer7', false),
  3336. content: getFwFieldVal('content', false),
  3337. connection_bytes: getFwFieldVal('connbytes', false),
  3338. connection_rate: getFwFieldVal('connrate', false),
  3339. pcc: getFwFieldVal('pcc', false),
  3340. src_mac_address: getFwFieldVal('srcmac', true),
  3341. out_bridge_port: getFwFieldVal('outbridgeport', false),
  3342. in_bridge_port: getFwFieldVal('inbridgeport', false),
  3343. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  3344. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  3345. ipsec_policy: getFwFieldVal('ipsec', false),
  3346. tls_host: getFwFieldVal('tlshost', false),
  3347. ingress_priority: getFwFieldVal('ingresspriority', false),
  3348. priority: getFwFieldVal('priority', false),
  3349. dscp: getFwFieldVal('dscp', false),
  3350. tcp_mss: getFwFieldVal('tcpmss', false),
  3351. tos: document.getElementById('fw-val-tos')?.value || '',
  3352. packet_size: getFwFieldVal('pktsize', false),
  3353. random: getFwFieldVal('random', false),
  3354. tcp_flags: getFwFieldVal('tcpflags', false),
  3355. icmp_options: getFwFieldVal('icmpoptions', false),
  3356. ipv4_options: getFwFieldVal('ipv4options', false),
  3357. ttl: getFwFieldVal('ttl', false),
  3358. // Extra tab
  3359. time: getFwFieldVal('time', false),
  3360. limit: getFwFieldVal('limit', false),
  3361. dst_limit: getFwFieldVal('dstlimit', false),
  3362. psd: getFwFieldVal('psd', false),
  3363. // Action tab
  3364. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  3365. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  3366. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  3367. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  3368. log: document.getElementById('filter-modal-log')?.checked || false,
  3369. log_prefix: getFwFieldVal('logprefix', false)
  3370. };
  3371. try {
  3372. const res = await fetch(`${API_BASE}/firewall/filter`, {
  3373. method: 'POST',
  3374. headers: { 'Content-Type': 'application/json' },
  3375. body: JSON.stringify(payload)
  3376. });
  3377. if (res.ok) {
  3378. const data = await res.json();
  3379. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  3380. loadFirewall(false);
  3381. if (closeAfter) {
  3382. closeFilterModal();
  3383. } else {
  3384. if (data.id) {
  3385. document.getElementById('filter-modal-id').value = data.id;
  3386. const badge = document.getElementById('fw-modal-badge');
  3387. if (badge) badge.innerText = `#${data.id}`;
  3388. }
  3389. }
  3390. } else {
  3391. const err = await res.json();
  3392. showToast('Error', err.message || 'Failed to save rule', 'error');
  3393. }
  3394. } catch (err) {
  3395. showToast('Error', err.message, 'error');
  3396. }
  3397. }
  3398. function submitSaveFilterRule(e) {
  3399. if (e && e.preventDefault) e.preventDefault();
  3400. return applyFilterRule(true);
  3401. }
  3402. function startFwStatPolling() {
  3403. stopFwStatPolling();
  3404. pollRuleStats();
  3405. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  3406. }
  3407. function stopFwStatPolling() {
  3408. if (state.fwStatInterval) {
  3409. clearInterval(state.fwStatInterval);
  3410. state.fwStatInterval = null;
  3411. }
  3412. }
  3413. async function pollRuleStats() {
  3414. const id = document.getElementById('filter-modal-id')?.value;
  3415. if (!id) {
  3416. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  3417. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  3418. return;
  3419. }
  3420. try {
  3421. const res = await fetch(`${API_BASE}/firewall/filter`);
  3422. if (!res.ok) return;
  3423. const rules = await res.json();
  3424. const r = rules.find(x => x.id === id);
  3425. if (!r) return;
  3426. const now = Date.now();
  3427. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  3428. state.fwLastTimestamp = now;
  3429. const curBytes = r.bytes || 0;
  3430. const curPackets = r.packets || 0;
  3431. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  3432. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  3433. state.fwLastBytes = curBytes;
  3434. state.fwLastPackets = curPackets;
  3435. const rateBps = Math.round((deltaBytes * 8) / dt);
  3436. const ratePkt = Math.round(deltaPkts / dt);
  3437. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  3438. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  3439. state.fwStatRateHistory.push(rateBps);
  3440. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  3441. state.fwStatPktHistory.push(ratePkt);
  3442. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  3443. const bEl = document.getElementById('fw-stat-bytes');
  3444. const pEl = document.getElementById('fw-stat-packets');
  3445. const rEl = document.getElementById('fw-stat-rate');
  3446. const prEl = document.getElementById('fw-stat-pktrate');
  3447. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  3448. if (pEl) pEl.value = curPackets.toLocaleString();
  3449. if (rEl) rEl.value = formatBps(rateBps);
  3450. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  3451. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3452. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3453. } catch (e) {
  3454. console.error('Error polling rule stats', e);
  3455. }
  3456. }
  3457. function formatBps(bps) {
  3458. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  3459. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  3460. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  3461. return bps + ' bps';
  3462. }
  3463. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  3464. const svg = document.getElementById(svgId);
  3465. if (!svg) return;
  3466. const w = 500;
  3467. const h = 100;
  3468. const paddingRight = 45;
  3469. const graphWidth = w - paddingRight;
  3470. const maxVal = Math.max(5, ...dataArray);
  3471. const currentVal = dataArray[dataArray.length - 1] || 0;
  3472. const leg = document.getElementById(legendId);
  3473. if (leg) {
  3474. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  3475. }
  3476. let gridLines = '';
  3477. for (let i = 0; i <= 5; i++) {
  3478. const y = 8 + (i * (h - 18) / 5);
  3479. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  3480. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  3481. gridLines += `
  3482. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  3483. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  3484. `;
  3485. }
  3486. const step = graphWidth / (dataArray.length - 1);
  3487. const points = dataArray.map((val, idx) => {
  3488. const x = idx * step;
  3489. const y = (h - 10) - (val / maxVal) * (h - 20);
  3490. return `${x.toFixed(1)},${y.toFixed(1)}`;
  3491. });
  3492. const polylineStr = points.join(' ');
  3493. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  3494. svg.innerHTML = `
  3495. ${gridLines}
  3496. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  3497. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  3498. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  3499. `;
  3500. }
  3501. async function moveFilterRule(id, dir) {
  3502. try {
  3503. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  3504. method: 'POST',
  3505. headers: { 'Content-Type': 'application/json' },
  3506. body: JSON.stringify({ direction: dir })
  3507. });
  3508. if (res.ok) loadFirewall(false);
  3509. } catch (err) {
  3510. showToast('Error', err.message, 'error');
  3511. }
  3512. }
  3513. async function toggleFilterRuleState(id, disabled) {
  3514. try {
  3515. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  3516. method: 'POST',
  3517. headers: { 'Content-Type': 'application/json' },
  3518. body: JSON.stringify({ disabled })
  3519. });
  3520. if (res.ok) loadFirewall(false);
  3521. } catch (err) {
  3522. showToast('Error', err.message, 'error');
  3523. }
  3524. }
  3525. async function deleteFilterRule(id) {
  3526. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  3527. try {
  3528. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3529. if (res.ok) {
  3530. showToast('Deleted', 'Filter rule removed', 'success');
  3531. loadFirewall(false);
  3532. }
  3533. } catch (err) {
  3534. showToast('Error', err.message, 'error');
  3535. }
  3536. }
  3537. // ----------------- NAT Rules -----------------
  3538. function renderNATRules() {
  3539. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  3540. const tbody = document.getElementById('nat-table-body');
  3541. const empty = document.getElementById('nat-empty');
  3542. if (!tbody) return;
  3543. tbody.innerHTML = '';
  3544. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3545. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  3546. if (rules.length === 0) {
  3547. empty?.classList.remove('hidden');
  3548. return;
  3549. }
  3550. empty?.classList.add('hidden');
  3551. rules.forEach((r, idx) => {
  3552. const tr = document.createElement('tr');
  3553. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3554. let toTarget = '-';
  3555. if (r.action === 'jump') {
  3556. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  3557. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3558. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  3559. } else if (r.action === 'redirect') {
  3560. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  3561. } else if (r.action === 'masquerade') {
  3562. toTarget = r.to_ports ? `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports}</span>` : `<span class="text-slate-500 font-mono">-</span>`;
  3563. } else if (r.action === 'log') {
  3564. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  3565. } else {
  3566. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  3567. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  3568. }
  3569. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  3570. tr.innerHTML = `
  3571. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3572. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3573. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  3574. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3575. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3576. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  3577. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3578. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  3579. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  3580. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3581. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3582. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3583. </td>
  3584. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3585. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3586. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3587. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3588. <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>
  3589. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3590. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3591. </td>
  3592. `;
  3593. tbody.appendChild(tr);
  3594. });
  3595. }
  3596. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3597. function switchNATRuleTab(tab) {
  3598. state.activeNATRuleTab = tab;
  3599. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  3600. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3601. btn.classList.add('text-slate-400', 'border-transparent');
  3602. });
  3603. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  3604. if (activeBtn) {
  3605. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3606. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3607. }
  3608. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  3609. const activePane = document.getElementById(`nat-pane-${tab}`);
  3610. if (activePane) activePane.classList.remove('hidden');
  3611. if (tab === 'statistics') {
  3612. startNATStatPolling();
  3613. } else {
  3614. stopNATStatPolling();
  3615. }
  3616. }
  3617. function toggleNATField(fieldKey, expand) {
  3618. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  3619. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3620. if (!plusBtn || !fieldBox) return;
  3621. if (expand) {
  3622. plusBtn.classList.add('hidden');
  3623. fieldBox.classList.remove('hidden');
  3624. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3625. if (valInput) valInput.focus();
  3626. } else {
  3627. fieldBox.classList.add('hidden');
  3628. plusBtn.classList.remove('hidden');
  3629. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3630. if (valInput) {
  3631. if (valInput.tagName === 'SELECT') {
  3632. valInput.selectedIndex = 0;
  3633. } else {
  3634. valInput.value = '';
  3635. }
  3636. }
  3637. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  3638. if (invInput) invInput.checked = false;
  3639. if (fieldKey === 'days') {
  3640. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3641. const el = document.getElementById(`nat-day-${d}`);
  3642. if (el) el.checked = true;
  3643. });
  3644. }
  3645. }
  3646. }
  3647. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  3648. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3649. toggleNATField(fieldKey, true);
  3650. let strVal = String(value);
  3651. if (hasInvert) {
  3652. const inv = strVal.startsWith('!');
  3653. if (inv) strVal = strVal.slice(1);
  3654. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3655. if (invEl) invEl.checked = inv;
  3656. }
  3657. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3658. if (valEl) valEl.value = strVal;
  3659. } else {
  3660. toggleNATField(fieldKey, false);
  3661. }
  3662. }
  3663. function getNATFieldVal(fieldKey, hasInvert = false) {
  3664. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3665. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3666. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3667. let v = valEl ? valEl.value.trim() : '';
  3668. if (!v) return '';
  3669. if (hasInvert) {
  3670. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3671. if (invEl && invEl.checked) {
  3672. v = '!' + v.replace(/^!/, '');
  3673. }
  3674. }
  3675. return v;
  3676. }
  3677. function toggleMaximizeNATModal() {
  3678. const win = document.getElementById('nat-modal-window');
  3679. if (!win) return;
  3680. if (win.classList.contains('max-w-[720px]')) {
  3681. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3682. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3683. } else {
  3684. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3685. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3686. }
  3687. }
  3688. function handleNATChainChange() {
  3689. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  3690. const actSel = document.getElementById('nat-modal-action');
  3691. if (actSel) {
  3692. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  3693. actSel.value = 'masquerade';
  3694. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  3695. actSel.value = 'dst-nat';
  3696. }
  3697. }
  3698. toggleNATActionFields();
  3699. }
  3700. function toggleNATActionFields() {
  3701. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  3702. const rowAddr = document.getElementById('nat-row-toaddr');
  3703. const rowPort = document.getElementById('nat-row-toport');
  3704. const jumpBox = document.getElementById('nat-action-jump-box');
  3705. const addrBox = document.getElementById('nat-action-addrlist-box');
  3706. // Hide all dynamic rows first
  3707. if (rowAddr) rowAddr.classList.add('hidden');
  3708. if (rowPort) rowPort.classList.add('hidden');
  3709. if (jumpBox) jumpBox.classList.add('hidden');
  3710. if (addrBox) addrBox.classList.add('hidden');
  3711. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  3712. if (rowAddr) rowAddr.classList.remove('hidden');
  3713. if (rowPort) rowPort.classList.remove('hidden');
  3714. } else if (act === 'redirect' || act === 'masquerade') {
  3715. if (rowPort) rowPort.classList.remove('hidden');
  3716. } else if (act === 'jump') {
  3717. if (jumpBox) jumpBox.classList.remove('hidden');
  3718. } else if (act.includes('address-list') || act.includes('address list')) {
  3719. if (addrBox) addrBox.classList.remove('hidden');
  3720. }
  3721. if (act === 'log') {
  3722. const logEl = document.getElementById('nat-modal-log');
  3723. if (logEl) logEl.checked = true;
  3724. toggleNATField('logprefix', true);
  3725. }
  3726. }
  3727. function toggleNATLogPrefix() {
  3728. const isLog = document.getElementById('nat-modal-log')?.checked;
  3729. toggleNATField('logprefix', !!isLog);
  3730. }
  3731. function openAddNATModal() {
  3732. switchNATRuleTab('general');
  3733. const badge = document.getElementById('nat-modal-badge');
  3734. if (badge) badge.innerText = 'New...';
  3735. document.getElementById('nat-modal-id').value = '';
  3736. document.getElementById('nat-modal-enabled').checked = true;
  3737. document.getElementById('nat-modal-comment').value = '';
  3738. document.getElementById('nat-modal-chain').value = 'srcnat';
  3739. document.getElementById('nat-modal-action').value = 'masquerade';
  3740. document.getElementById('nat-modal-toaddr').value = '';
  3741. document.getElementById('nat-modal-toport').value = '';
  3742. document.getElementById('nat-modal-log').checked = false;
  3743. populateInterfaceSelect('nat-val-iniface');
  3744. populateInterfaceSelect('nat-val-outiface');
  3745. populateAddressListSelect('nat-val-srclist');
  3746. populateAddressListSelect('nat-val-dstlist');
  3747. populateGeoIPSelect('nat-val-srcgeo');
  3748. populateGeoIPSelect('nat-val-dstgeo');
  3749. const allFieldKeys = [
  3750. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3751. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3752. 'routingmark', 'conntype',
  3753. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3754. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3755. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3756. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  3757. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3758. ];
  3759. allFieldKeys.forEach(k => toggleNATField(k, false));
  3760. resetCurrentNATRuleCounters();
  3761. toggleNATActionFields();
  3762. document.getElementById('nat-modal').classList.remove('hidden');
  3763. }
  3764. function openEditNATModal(id) {
  3765. const r = (state.natRules || []).find(rule => rule.id === id);
  3766. if (!r) return;
  3767. switchNATRuleTab('general');
  3768. const badge = document.getElementById('nat-modal-badge');
  3769. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3770. document.getElementById('nat-modal-id').value = r.id;
  3771. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  3772. document.getElementById('nat-modal-comment').value = r.comment || '';
  3773. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  3774. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  3775. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  3776. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  3777. document.getElementById('nat-modal-log').checked = !!r.log;
  3778. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3779. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3780. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3781. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3782. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  3783. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  3784. setNATFieldVal('src', r.src_address, true);
  3785. setNATFieldVal('dst', r.dst_address, true);
  3786. setNATFieldVal('srclist', r.src_address_list, true);
  3787. setNATFieldVal('dstlist', r.dst_address_list, true);
  3788. setNATFieldVal('srcgeo', r.src_geoip, true);
  3789. setNATFieldVal('dstgeo', r.dst_geoip, true);
  3790. if (r.protocol && r.protocol !== 'all') {
  3791. setNATFieldVal('proto', r.protocol, true);
  3792. } else {
  3793. toggleNATField('proto', false);
  3794. }
  3795. setNATFieldVal('sport', r.src_port, true);
  3796. setNATFieldVal('dport', r.dst_port, true);
  3797. setNATFieldVal('anyport', r.any_port, true);
  3798. setNATFieldVal('iniface', r.in_interface, true);
  3799. setNATFieldVal('outiface', r.out_interface, true);
  3800. setNATFieldVal('inifacelist', r.in_interface_list, true);
  3801. setNATFieldVal('outifacelist', r.out_interface_list, true);
  3802. setNATFieldVal('pktmark', r.packet_mark, true);
  3803. setNATFieldVal('connmark', r.connection_mark, true);
  3804. setNATFieldVal('routingmark', r.routing_mark, true);
  3805. setNATFieldVal('conntype', r.connection_type, false);
  3806. // Advanced tab fields
  3807. setNATFieldVal('layer7', r.layer7_protocol, false);
  3808. setNATFieldVal('content', r.content, false);
  3809. setNATFieldVal('connbytes', r.connection_bytes, false);
  3810. setNATFieldVal('connrate', r.connection_rate, false);
  3811. setNATFieldVal('pcc', r.pcc, false);
  3812. setNATFieldVal('srcmac', r.src_mac_address, true);
  3813. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  3814. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  3815. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3816. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3817. setNATFieldVal('ipsec', r.ipsec_policy, false);
  3818. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  3819. setNATFieldVal('priority', r.priority, false);
  3820. setNATFieldVal('dscp', r.dscp, false);
  3821. setNATFieldVal('tcpmss', r.tcp_mss, false);
  3822. if (r.tos) {
  3823. const tosEl = document.getElementById('nat-val-tos');
  3824. if (tosEl) tosEl.value = r.tos;
  3825. }
  3826. setNATFieldVal('pktsize', r.packet_size, false);
  3827. setNATFieldVal('random', r.random, false);
  3828. setNATFieldVal('icmpoptions', r.icmp_options, false);
  3829. setNATFieldVal('ipv4options', r.ipv4_options, false);
  3830. setNATFieldVal('ttl', r.ttl, false);
  3831. // Extra tab fields
  3832. setNATFieldVal('time', r.time, false);
  3833. if (r.days) {
  3834. toggleNATField('days', true);
  3835. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3836. const chk = document.getElementById(`nat-day-${d}`);
  3837. if (chk) chk.checked = r.days.includes(d);
  3838. });
  3839. } else {
  3840. toggleNATField('days', false);
  3841. }
  3842. setNATFieldVal('limit', r.limit, false);
  3843. setNATFieldVal('dstlimit', r.dst_limit, false);
  3844. setNATFieldVal('psd', r.psd, false);
  3845. // Action fields
  3846. if (r.jump_target) {
  3847. const jtEl = document.getElementById('nat-modal-jumptarget');
  3848. if (jtEl) jtEl.value = r.jump_target;
  3849. }
  3850. if (r.address_list) {
  3851. const alEl = document.getElementById('nat-modal-action-addrlist');
  3852. if (alEl) alEl.value = r.address_list;
  3853. }
  3854. if (r.address_list_timeout) {
  3855. const toEl = document.getElementById('nat-modal-action-timeout');
  3856. if (toEl) toEl.value = r.address_list_timeout;
  3857. }
  3858. setNATFieldVal('logprefix', r.log_prefix, false);
  3859. // Statistics
  3860. const bEl = document.getElementById('nat-stat-bytes');
  3861. const pEl = document.getElementById('nat-stat-packets');
  3862. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3863. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3864. state.natLastBytes = r.bytes || 0;
  3865. state.natLastPackets = r.packets || 0;
  3866. state.natLastTimestamp = Date.now();
  3867. state.natStatRateHistory = new Array(30).fill(0);
  3868. state.natStatPktHistory = new Array(30).fill(0);
  3869. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3870. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3871. toggleNATActionFields();
  3872. document.getElementById('nat-modal').classList.remove('hidden');
  3873. }
  3874. function closeNATModal() {
  3875. stopNATStatPolling();
  3876. document.getElementById('nat-modal').classList.add('hidden');
  3877. }
  3878. function copyNATRule() {
  3879. document.getElementById('nat-modal-id').value = '';
  3880. const badge = document.getElementById('nat-modal-badge');
  3881. if (badge) badge.innerText = 'New...';
  3882. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  3883. }
  3884. function resetCurrentNATRuleCounters() {
  3885. state.natStatRateHistory = new Array(30).fill(0);
  3886. state.natStatPktHistory = new Array(30).fill(0);
  3887. state.natLastBytes = 0;
  3888. state.natLastPackets = 0;
  3889. state.natLastTimestamp = Date.now();
  3890. const bEl = document.getElementById('nat-stat-bytes');
  3891. const pEl = document.getElementById('nat-stat-packets');
  3892. const rEl = document.getElementById('nat-stat-rate');
  3893. const prEl = document.getElementById('nat-stat-pktrate');
  3894. if (bEl) bEl.value = '0 B';
  3895. if (pEl) pEl.value = '0';
  3896. if (rEl) rEl.value = '0 bps';
  3897. if (prEl) prEl.value = '0 p/s';
  3898. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3899. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3900. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  3901. }
  3902. async function applyNATRule(closeAfter = false) {
  3903. const id = document.getElementById('nat-modal-id').value;
  3904. const chain = document.getElementById('nat-modal-chain').value;
  3905. const action = document.getElementById('nat-modal-action').value;
  3906. const comment = document.getElementById('nat-modal-comment').value.trim();
  3907. const enabled = document.getElementById('nat-modal-enabled').checked;
  3908. const src = getNATFieldVal('src', true);
  3909. const dst = getNATFieldVal('dst', true);
  3910. const srclist = getNATFieldVal('srclist', true);
  3911. const dstlist = getNATFieldVal('dstlist', true);
  3912. const srcgeo = getNATFieldVal('srcgeo', true);
  3913. const dstgeo = getNATFieldVal('dstgeo', true);
  3914. const proto = getNATFieldVal('proto', true);
  3915. const sport = getNATFieldVal('sport', true);
  3916. const dport = getNATFieldVal('dport', true);
  3917. const anyport = getNATFieldVal('anyport', true);
  3918. const iniface = getNATFieldVal('iniface', true);
  3919. const outiface = getNATFieldVal('outiface', true);
  3920. const inifacelist = getNATFieldVal('inifacelist', true);
  3921. const outifacelist = getNATFieldVal('outifacelist', true);
  3922. const pktmark = getNATFieldVal('pktmark', true);
  3923. const connmark = getNATFieldVal('connmark', true);
  3924. const routingmark = getNATFieldVal('routingmark', true);
  3925. const conntype = getNATFieldVal('conntype', false);
  3926. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  3927. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  3928. const payload = {
  3929. id,
  3930. chain,
  3931. action,
  3932. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  3933. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  3934. protocol: proto || 'all',
  3935. src_address: src,
  3936. dst_address: dst,
  3937. src_port: sport,
  3938. dst_port: dport,
  3939. any_port: anyport,
  3940. in_interface: iniface,
  3941. out_interface: outiface,
  3942. in_interface_list: inifacelist,
  3943. out_interface_list: outifacelist,
  3944. packet_mark: pktmark,
  3945. connection_mark: connmark,
  3946. routing_mark: routingmark,
  3947. connection_type: conntype,
  3948. src_address_list: srclist,
  3949. dst_address_list: dstlist,
  3950. src_geoip: srcgeo,
  3951. dst_geoip: dstgeo,
  3952. comment,
  3953. disabled: !enabled,
  3954. // Advanced tab
  3955. layer7_protocol: getNATFieldVal('layer7', false),
  3956. content: getNATFieldVal('content', false),
  3957. connection_bytes: getNATFieldVal('connbytes', false),
  3958. connection_rate: getNATFieldVal('connrate', false),
  3959. pcc: getNATFieldVal('pcc', false),
  3960. src_mac_address: getNATFieldVal('srcmac', true),
  3961. out_bridge_port: getNATFieldVal('outbridgeport', false),
  3962. in_bridge_port: getNATFieldVal('inbridgeport', false),
  3963. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  3964. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  3965. ipsec_policy: getNATFieldVal('ipsec', false),
  3966. ingress_priority: getNATFieldVal('ingresspriority', false),
  3967. priority: getNATFieldVal('priority', false),
  3968. dscp: getNATFieldVal('dscp', false),
  3969. tcp_mss: getNATFieldVal('tcpmss', false),
  3970. tos: document.getElementById('nat-val-tos')?.value || '',
  3971. packet_size: getNATFieldVal('pktsize', false),
  3972. random: getNATFieldVal('random', false),
  3973. icmp_options: getNATFieldVal('icmpoptions', false),
  3974. ipv4_options: getNATFieldVal('ipv4options', false),
  3975. ttl: getNATFieldVal('ttl', false),
  3976. // Extra tab
  3977. time: getNATFieldVal('time', false),
  3978. limit: getNATFieldVal('limit', false),
  3979. dst_limit: getNATFieldVal('dstlimit', false),
  3980. psd: getNATFieldVal('psd', false),
  3981. // Action tab
  3982. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  3983. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  3984. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  3985. log: document.getElementById('nat-modal-log')?.checked || false,
  3986. log_prefix: getNATFieldVal('logprefix', false)
  3987. };
  3988. try {
  3989. const res = await fetch(`${API_BASE}/firewall/nat`, {
  3990. method: 'POST',
  3991. headers: { 'Content-Type': 'application/json' },
  3992. body: JSON.stringify(payload)
  3993. });
  3994. if (res.ok) {
  3995. const data = await res.json();
  3996. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  3997. loadFirewall(false);
  3998. if (closeAfter) {
  3999. closeNATModal();
  4000. } else {
  4001. if (data.id) {
  4002. document.getElementById('nat-modal-id').value = data.id;
  4003. const badge = document.getElementById('nat-modal-badge');
  4004. if (badge) badge.innerText = `#${data.id}`;
  4005. }
  4006. }
  4007. } else {
  4008. const err = await res.json();
  4009. showToast('Error', err.message || 'Failed to save rule', 'error');
  4010. }
  4011. } catch (err) {
  4012. showToast('Error', err.message, 'error');
  4013. }
  4014. }
  4015. function submitSaveNATRule(e) {
  4016. if (e && e.preventDefault) e.preventDefault();
  4017. return applyNATRule(true);
  4018. }
  4019. function startNATStatPolling() {
  4020. stopNATStatPolling();
  4021. pollNATRuleStats();
  4022. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  4023. }
  4024. function stopNATStatPolling() {
  4025. if (state.natStatInterval) {
  4026. clearInterval(state.natStatInterval);
  4027. state.natStatInterval = null;
  4028. }
  4029. }
  4030. async function pollNATRuleStats() {
  4031. const id = document.getElementById('nat-modal-id')?.value;
  4032. if (!id) {
  4033. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  4034. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  4035. return;
  4036. }
  4037. try {
  4038. const res = await fetch(`${API_BASE}/firewall/nat`);
  4039. if (!res.ok) return;
  4040. const rules = await res.json();
  4041. const r = rules.find(x => x.id === id);
  4042. if (!r) return;
  4043. const now = Date.now();
  4044. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  4045. state.natLastTimestamp = now;
  4046. const curBytes = r.bytes || 0;
  4047. const curPackets = r.packets || 0;
  4048. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  4049. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  4050. state.natLastBytes = curBytes;
  4051. state.natLastPackets = curPackets;
  4052. const rateBps = Math.round((deltaBytes * 8) / dt);
  4053. const ratePkt = Math.round(deltaPkts / dt);
  4054. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  4055. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  4056. state.natStatRateHistory.push(rateBps);
  4057. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  4058. state.natStatPktHistory.push(ratePkt);
  4059. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  4060. const bEl = document.getElementById('nat-stat-bytes');
  4061. const pEl = document.getElementById('nat-stat-packets');
  4062. const rEl = document.getElementById('nat-stat-rate');
  4063. const prEl = document.getElementById('nat-stat-pktrate');
  4064. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4065. if (pEl) pEl.value = curPackets.toLocaleString();
  4066. if (rEl) rEl.value = formatBps(rateBps);
  4067. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4068. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4069. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4070. } catch (e) {
  4071. console.error('Error polling NAT rule stats', e);
  4072. }
  4073. }
  4074. async function moveNATRule(id, dir) {
  4075. try {
  4076. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  4077. method: 'POST',
  4078. headers: { 'Content-Type': 'application/json' },
  4079. body: JSON.stringify({ direction: dir })
  4080. });
  4081. if (res.ok) loadFirewall(false);
  4082. } catch (err) {
  4083. showToast('Error', err.message, 'error');
  4084. }
  4085. }
  4086. async function toggleNATRuleState(id, disabled) {
  4087. try {
  4088. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  4089. method: 'POST',
  4090. headers: { 'Content-Type': 'application/json' },
  4091. body: JSON.stringify({ disabled })
  4092. });
  4093. if (res.ok) loadFirewall(false);
  4094. } catch (err) {
  4095. showToast('Error', err.message, 'error');
  4096. }
  4097. }
  4098. async function deleteNATRule(id) {
  4099. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  4100. try {
  4101. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4102. if (res.ok) {
  4103. showToast('Deleted', 'NAT rule removed', 'success');
  4104. loadFirewall(false);
  4105. }
  4106. } catch (err) {
  4107. showToast('Error', err.message, 'error');
  4108. }
  4109. }
  4110. // ----------------- Mangle Rules -----------------
  4111. function renderMangleRules() {
  4112. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  4113. const tbody = document.getElementById('mangle-table-body');
  4114. const empty = document.getElementById('mangle-empty');
  4115. if (!tbody) return;
  4116. tbody.innerHTML = '';
  4117. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4118. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  4119. if (rules.length === 0) {
  4120. empty?.classList.remove('hidden');
  4121. return;
  4122. }
  4123. empty?.classList.add('hidden');
  4124. rules.forEach((r, idx) => {
  4125. const tr = document.createElement('tr');
  4126. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4127. let markVal = '<span class="text-slate-500">-</span>';
  4128. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  4129. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  4130. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  4131. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  4132. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  4133. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  4134. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  4135. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  4136. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  4137. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4138. else if (r.action.includes('address-list') || r.action.includes('address list')) markVal = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  4139. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4140. tr.innerHTML = `
  4141. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4142. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4143. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  4144. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4145. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4146. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4147. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  4148. <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>
  4149. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4150. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  4151. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4152. </td>
  4153. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4154. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4155. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4156. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4157. <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>
  4158. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4159. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4160. </td>
  4161. `;
  4162. tbody.appendChild(tr);
  4163. });
  4164. }
  4165. // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4166. function switchMangleRuleTab(tab) {
  4167. state.activeMangleRuleTab = tab;
  4168. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4169. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4170. btn.classList.add('text-slate-400', 'border-transparent');
  4171. });
  4172. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4173. if (activeBtn) {
  4174. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4175. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4176. }
  4177. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4178. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4179. if (activePane) activePane.classList.remove('hidden');
  4180. if (tab === 'statistics') {
  4181. startMangleStatPolling();
  4182. } else {
  4183. stopMangleStatPolling();
  4184. }
  4185. }
  4186. function toggleMangleField(fieldKey, expand) {
  4187. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4188. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4189. if (!plusBtn || !fieldBox) return;
  4190. if (expand) {
  4191. plusBtn.classList.add('hidden');
  4192. fieldBox.classList.remove('hidden');
  4193. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4194. if (valInput) valInput.focus();
  4195. } else {
  4196. fieldBox.classList.add('hidden');
  4197. plusBtn.classList.remove('hidden');
  4198. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4199. if (valInput) {
  4200. if (valInput.tagName === 'SELECT') {
  4201. valInput.selectedIndex = 0;
  4202. } else {
  4203. valInput.value = '';
  4204. }
  4205. }
  4206. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4207. if (invInput) invInput.checked = false;
  4208. if (fieldKey === 'cs') {
  4209. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4210. const el = document.getElementById(id);
  4211. if (el) el.checked = false;
  4212. });
  4213. }
  4214. if (fieldKey === 'natstate') {
  4215. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4216. const el = document.getElementById(id);
  4217. if (el) el.checked = false;
  4218. });
  4219. }
  4220. }
  4221. }
  4222. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4223. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4224. toggleMangleField(fieldKey, true);
  4225. let strVal = String(value);
  4226. if (hasInvert) {
  4227. const inv = strVal.startsWith('!');
  4228. if (inv) strVal = strVal.slice(1);
  4229. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4230. if (invEl) invEl.checked = inv;
  4231. }
  4232. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4233. if (valEl) valEl.value = strVal;
  4234. } else {
  4235. toggleMangleField(fieldKey, false);
  4236. }
  4237. }
  4238. function getMangleFieldVal(fieldKey, hasInvert = false) {
  4239. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4240. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4241. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4242. let v = valEl ? valEl.value.trim() : '';
  4243. if (!v) return '';
  4244. if (hasInvert) {
  4245. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4246. if (invEl && invEl.checked) {
  4247. v = '!' + v.replace(/^!/, '');
  4248. }
  4249. }
  4250. return v;
  4251. }
  4252. function toggleMaximizeMangleModal() {
  4253. const win = document.getElementById('mangle-modal-window');
  4254. if (!win) return;
  4255. if (win.classList.contains('max-w-[720px]')) {
  4256. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4257. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4258. } else {
  4259. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4260. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4261. }
  4262. }
  4263. function toggleMangleActionFields() {
  4264. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  4265. // Hide all dynamic rows first
  4266. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  4267. const el = document.getElementById(`mangle-row-${id}`);
  4268. if (el) el.classList.add('hidden');
  4269. });
  4270. const jumpBox = document.getElementById('mangle-action-jump-box');
  4271. const addrBox = document.getElementById('mangle-action-addrlist-box');
  4272. if (jumpBox) jumpBox.classList.add('hidden');
  4273. if (addrBox) addrBox.classList.add('hidden');
  4274. // Activate matching rows
  4275. if (act === 'mark-connection') {
  4276. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  4277. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4278. } else if (act === 'mark-routing') {
  4279. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  4280. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4281. } else if (act === 'mark-packet') {
  4282. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  4283. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4284. } else if (act === 'change-mss') {
  4285. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  4286. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4287. } else if (act === 'change-dscp') {
  4288. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  4289. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4290. } else if (act === 'change-ttl') {
  4291. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  4292. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4293. } else if (act === 'set-priority') {
  4294. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  4295. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4296. } else if (act === 'route') {
  4297. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  4298. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4299. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  4300. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  4301. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4302. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  4303. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4304. } else if (act === 'jump') {
  4305. if (jumpBox) jumpBox.classList.remove('hidden');
  4306. } else if (act.includes('address-list') || act.includes('address list')) {
  4307. if (addrBox) addrBox.classList.remove('hidden');
  4308. }
  4309. if (act === 'log') {
  4310. const logEl = document.getElementById('mangle-modal-log');
  4311. if (logEl) logEl.checked = true;
  4312. toggleMangleField('logprefix', true);
  4313. }
  4314. }
  4315. function toggleMangleLogPrefix() {
  4316. const isLog = document.getElementById('mangle-modal-log')?.checked;
  4317. toggleMangleField('logprefix', !!isLog);
  4318. }
  4319. const allMangleFieldKeys = [
  4320. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4321. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4322. 'routingmark', 'conntype', 'cs', 'natstate',
  4323. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4324. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4325. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4326. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  4327. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  4328. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  4329. ];
  4330. function openAddMangleModal() {
  4331. switchMangleRuleTab('general');
  4332. const badge = document.getElementById('mangle-modal-badge');
  4333. if (badge) badge.innerText = 'New...';
  4334. document.getElementById('mangle-modal-id').value = '';
  4335. document.getElementById('mangle-modal-enabled').checked = true;
  4336. document.getElementById('mangle-modal-comment').value = '';
  4337. document.getElementById('mangle-modal-chain').value = 'prerouting';
  4338. document.getElementById('mangle-modal-action').value = 'mark-connection';
  4339. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  4340. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  4341. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  4342. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  4343. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  4344. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  4345. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  4346. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  4347. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  4348. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  4349. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  4350. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  4351. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  4352. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  4353. populateInterfaceSelect('mangle-val-iniface');
  4354. populateInterfaceSelect('mangle-val-outiface');
  4355. populateAddressListSelect('mangle-val-srclist');
  4356. populateAddressListSelect('mangle-val-dstlist');
  4357. populateGeoIPSelect('mangle-val-srcgeo');
  4358. populateGeoIPSelect('mangle-val-dstgeo');
  4359. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  4360. resetCurrentMangleRuleCounters();
  4361. toggleMangleActionFields();
  4362. document.getElementById('mangle-modal').classList.remove('hidden');
  4363. }
  4364. function openEditMangleModal(id) {
  4365. const r = (state.mangleRules || []).find(rule => rule.id === id);
  4366. if (!r) return;
  4367. switchMangleRuleTab('general');
  4368. const badge = document.getElementById('mangle-modal-badge');
  4369. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4370. document.getElementById('mangle-modal-id').value = r.id;
  4371. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  4372. document.getElementById('mangle-modal-comment').value = r.comment || '';
  4373. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  4374. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  4375. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  4376. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  4377. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  4378. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  4379. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  4380. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  4381. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  4382. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  4383. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  4384. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  4385. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  4386. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  4387. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  4388. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  4389. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4390. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4391. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4392. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4393. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  4394. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  4395. setMangleFieldVal('src', r.src_address, true);
  4396. setMangleFieldVal('dst', r.dst_address, true);
  4397. setMangleFieldVal('srclist', r.src_address_list, true);
  4398. setMangleFieldVal('dstlist', r.dst_address_list, true);
  4399. setMangleFieldVal('srcgeo', r.src_geoip, true);
  4400. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  4401. if (r.protocol && r.protocol !== 'all') {
  4402. setMangleFieldVal('proto', r.protocol, true);
  4403. } else {
  4404. toggleMangleField('proto', false);
  4405. }
  4406. setMangleFieldVal('sport', r.src_port, true);
  4407. setMangleFieldVal('dport', r.dst_port, true);
  4408. setMangleFieldVal('anyport', r.any_port, true);
  4409. setMangleFieldVal('iniface', r.in_interface, true);
  4410. setMangleFieldVal('outiface', r.out_interface, true);
  4411. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  4412. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  4413. setMangleFieldVal('pktmark', r.packet_mark, true);
  4414. setMangleFieldVal('connmark', r.connection_mark, true);
  4415. setMangleFieldVal('routingmark', r.routing_mark, true);
  4416. setMangleFieldVal('conntype', r.connection_type, false);
  4417. // Connection State
  4418. const states = r.connection_state || [];
  4419. if (states.length > 0) {
  4420. toggleMangleField('cs', true);
  4421. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4422. const el = document.getElementById(`mangle-modal-cs-${s}`);
  4423. if (el) el.checked = states.includes(s);
  4424. });
  4425. } else {
  4426. toggleMangleField('cs', false);
  4427. }
  4428. // Connection NAT State
  4429. const natStates = r.connection_nat_state || [];
  4430. if (natStates.length > 0) {
  4431. toggleMangleField('natstate', true);
  4432. ['srcnat', 'dstnat'].forEach(s => {
  4433. const el = document.getElementById(`mangle-modal-nat-${s}`);
  4434. if (el) el.checked = natStates.includes(s);
  4435. });
  4436. } else {
  4437. toggleMangleField('natstate', false);
  4438. }
  4439. // Advanced tab fields
  4440. setMangleFieldVal('layer7', r.layer7_protocol, false);
  4441. setMangleFieldVal('content', r.content, false);
  4442. setMangleFieldVal('connbytes', r.connection_bytes, false);
  4443. setMangleFieldVal('connrate', r.connection_rate, false);
  4444. setMangleFieldVal('pcc', r.pcc, false);
  4445. setMangleFieldVal('srcmac', r.src_mac_address, true);
  4446. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  4447. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  4448. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4449. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4450. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  4451. setMangleFieldVal('tlshost', r.tls_host, false);
  4452. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  4453. setMangleFieldVal('priority', r.priority, false);
  4454. setMangleFieldVal('dscp', r.dscp, false);
  4455. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  4456. if (r.tos) {
  4457. const tosEl = document.getElementById('mangle-val-tos');
  4458. if (tosEl) tosEl.value = r.tos;
  4459. }
  4460. setMangleFieldVal('pktsize', r.packet_size, false);
  4461. setMangleFieldVal('random', r.random, false);
  4462. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  4463. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  4464. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  4465. setMangleFieldVal('ttl', r.ttl, false);
  4466. // Extra tab fields
  4467. setMangleFieldVal('nth', r.nth, false);
  4468. setMangleFieldVal('connlimit', r.connection_limit, false);
  4469. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  4470. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  4471. setMangleFieldVal('hotspot', r.hotspot, false);
  4472. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  4473. setMangleFieldVal('limit', r.limit, false);
  4474. setMangleFieldVal('dstlimit', r.dst_limit, false);
  4475. setMangleFieldVal('time', r.time, false);
  4476. setMangleFieldVal('psd', r.psd, false);
  4477. // Action fields
  4478. if (r.jump_target) {
  4479. const jtEl = document.getElementById('mangle-modal-jumptarget');
  4480. if (jtEl) jtEl.value = r.jump_target;
  4481. }
  4482. if (r.address_list) {
  4483. const alEl = document.getElementById('mangle-modal-action-addrlist');
  4484. if (alEl) alEl.value = r.address_list;
  4485. }
  4486. if (r.address_list_timeout) {
  4487. const toEl = document.getElementById('mangle-modal-action-timeout');
  4488. if (toEl) toEl.value = r.address_list_timeout;
  4489. }
  4490. setMangleFieldVal('logprefix', r.log_prefix, false);
  4491. // Statistics
  4492. const bEl = document.getElementById('mangle-stat-bytes');
  4493. const pEl = document.getElementById('mangle-stat-packets');
  4494. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4495. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4496. state.mangleLastBytes = r.bytes || 0;
  4497. state.mangleLastPackets = r.packets || 0;
  4498. state.mangleLastTimestamp = Date.now();
  4499. state.mangleStatRateHistory = new Array(30).fill(0);
  4500. state.mangleStatPktHistory = new Array(30).fill(0);
  4501. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4502. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4503. toggleMangleActionFields();
  4504. document.getElementById('mangle-modal').classList.remove('hidden');
  4505. }
  4506. function closeMangleModal() {
  4507. stopMangleStatPolling();
  4508. document.getElementById('mangle-modal').classList.add('hidden');
  4509. }
  4510. function copyMangleRule() {
  4511. document.getElementById('mangle-modal-id').value = '';
  4512. const badge = document.getElementById('mangle-modal-badge');
  4513. if (badge) badge.innerText = 'New...';
  4514. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  4515. }
  4516. function resetCurrentMangleRuleCounters() {
  4517. state.mangleStatRateHistory = new Array(30).fill(0);
  4518. state.mangleStatPktHistory = new Array(30).fill(0);
  4519. state.mangleLastBytes = 0;
  4520. state.mangleLastPackets = 0;
  4521. state.mangleLastTimestamp = Date.now();
  4522. const bEl = document.getElementById('mangle-stat-bytes');
  4523. const pEl = document.getElementById('mangle-stat-packets');
  4524. const rEl = document.getElementById('mangle-stat-rate');
  4525. const prEl = document.getElementById('mangle-stat-pktrate');
  4526. if (bEl) bEl.value = '0 B';
  4527. if (pEl) pEl.value = '0';
  4528. if (rEl) rEl.value = '0 bps';
  4529. if (prEl) prEl.value = '0 p/s';
  4530. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4531. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4532. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  4533. }
  4534. async function applyMangleRule(closeAfter = false) {
  4535. const id = document.getElementById('mangle-modal-id').value;
  4536. const chain = document.getElementById('mangle-modal-chain').value;
  4537. const action = document.getElementById('mangle-modal-action').value;
  4538. const comment = document.getElementById('mangle-modal-comment').value.trim();
  4539. const enabled = document.getElementById('mangle-modal-enabled').checked;
  4540. const src = getMangleFieldVal('src', true);
  4541. const dst = getMangleFieldVal('dst', true);
  4542. const srclist = getMangleFieldVal('srclist', true);
  4543. const dstlist = getMangleFieldVal('dstlist', true);
  4544. const srcgeo = getMangleFieldVal('srcgeo', true);
  4545. const dstgeo = getMangleFieldVal('dstgeo', true);
  4546. const proto = getMangleFieldVal('proto', true);
  4547. const sport = getMangleFieldVal('sport', true);
  4548. const dport = getMangleFieldVal('dport', true);
  4549. const anyport = getMangleFieldVal('anyport', true);
  4550. const iniface = getMangleFieldVal('iniface', true);
  4551. const outiface = getMangleFieldVal('outiface', true);
  4552. const inifacelist = getMangleFieldVal('inifacelist', true);
  4553. const outifacelist = getMangleFieldVal('outifacelist', true);
  4554. const pktmark = getMangleFieldVal('pktmark', true);
  4555. const connmark = getMangleFieldVal('connmark', true);
  4556. const routingmark = getMangleFieldVal('routingmark', true);
  4557. const conntype = getMangleFieldVal('conntype', false);
  4558. const states = [];
  4559. const csBox = document.getElementById('mangle-field-cs');
  4560. if (csBox && !csBox.classList.contains('hidden')) {
  4561. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4562. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  4563. });
  4564. }
  4565. const natStates = [];
  4566. const natBox = document.getElementById('mangle-field-natstate');
  4567. if (natBox && !natBox.classList.contains('hidden')) {
  4568. ['srcnat', 'dstnat'].forEach(s => {
  4569. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  4570. });
  4571. }
  4572. const payload = {
  4573. id,
  4574. chain,
  4575. action,
  4576. protocol: proto || 'all',
  4577. src_address: src,
  4578. dst_address: dst,
  4579. src_port: sport,
  4580. dst_port: dport,
  4581. any_port: anyport,
  4582. in_interface: iniface,
  4583. out_interface: outiface,
  4584. in_interface_list: inifacelist,
  4585. out_interface_list: outifacelist,
  4586. packet_mark: pktmark,
  4587. connection_mark: connmark,
  4588. routing_mark: routingmark,
  4589. connection_type: conntype,
  4590. connection_state: states,
  4591. connection_nat_state: natStates,
  4592. src_address_list: srclist,
  4593. dst_address_list: dstlist,
  4594. src_geoip: srcgeo,
  4595. dst_geoip: dstgeo,
  4596. comment,
  4597. disabled: !enabled,
  4598. // Advanced tab
  4599. layer7_protocol: getMangleFieldVal('layer7', false),
  4600. content: getMangleFieldVal('content', false),
  4601. connection_bytes: getMangleFieldVal('connbytes', false),
  4602. connection_rate: getMangleFieldVal('connrate', false),
  4603. pcc: getMangleFieldVal('pcc', false),
  4604. src_mac_address: getMangleFieldVal('srcmac', true),
  4605. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  4606. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  4607. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  4608. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  4609. ipsec_policy: getMangleFieldVal('ipsec', false),
  4610. tls_host: getMangleFieldVal('tlshost', false),
  4611. ingress_priority: getMangleFieldVal('ingresspriority', false),
  4612. priority: getMangleFieldVal('priority', false),
  4613. dscp: getMangleFieldVal('dscp', false),
  4614. tcp_mss: getMangleFieldVal('tcpmss', false),
  4615. tos: document.getElementById('mangle-val-tos')?.value || '',
  4616. packet_size: getMangleFieldVal('pktsize', false),
  4617. random: getMangleFieldVal('random', false),
  4618. tcp_flags: getMangleFieldVal('tcpflags', false),
  4619. icmp_options: getMangleFieldVal('icmpoptions', false),
  4620. ipv4_options: getMangleFieldVal('ipv4options', false),
  4621. ttl: getMangleFieldVal('ttl', false),
  4622. // Extra tab
  4623. nth: getMangleFieldVal('nth', false),
  4624. connection_limit: getMangleFieldVal('connlimit', false),
  4625. src_address_type: getMangleFieldVal('srcaddrtype', false),
  4626. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  4627. hotspot: getMangleFieldVal('hotspot', false),
  4628. ip_fragment: getMangleFieldVal('ipfragment', false),
  4629. limit: getMangleFieldVal('limit', false),
  4630. dst_limit: getMangleFieldVal('dstlimit', false),
  4631. time: getMangleFieldVal('time', false),
  4632. psd: getMangleFieldVal('psd', false),
  4633. // Action tab
  4634. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  4635. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  4636. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  4637. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  4638. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  4639. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  4640. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  4641. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  4642. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  4643. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  4644. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  4645. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  4646. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  4647. log: document.getElementById('mangle-modal-log')?.checked || false,
  4648. log_prefix: getMangleFieldVal('logprefix', false)
  4649. };
  4650. try {
  4651. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  4652. method: 'POST',
  4653. headers: { 'Content-Type': 'application/json' },
  4654. body: JSON.stringify(payload)
  4655. });
  4656. if (res.ok) {
  4657. const data = await res.json();
  4658. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  4659. loadFirewall(false);
  4660. if (closeAfter) {
  4661. closeMangleModal();
  4662. } else {
  4663. if (data.id) {
  4664. document.getElementById('mangle-modal-id').value = data.id;
  4665. const badge = document.getElementById('mangle-modal-badge');
  4666. if (badge) badge.innerText = `#${data.id}`;
  4667. }
  4668. }
  4669. } else {
  4670. const err = await res.json();
  4671. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  4672. }
  4673. } catch (err) {
  4674. showToast('Error', err.message, 'error');
  4675. }
  4676. }
  4677. function submitSaveMangleRule(e) {
  4678. if (e && e.preventDefault) e.preventDefault();
  4679. return applyMangleRule(true);
  4680. }
  4681. function startMangleStatPolling() {
  4682. stopMangleStatPolling();
  4683. pollMangleRuleStats();
  4684. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  4685. }
  4686. function stopMangleStatPolling() {
  4687. if (state.mangleStatInterval) {
  4688. clearInterval(state.mangleStatInterval);
  4689. state.mangleStatInterval = null;
  4690. }
  4691. }
  4692. async function pollMangleRuleStats() {
  4693. const id = document.getElementById('mangle-modal-id')?.value;
  4694. if (!id) {
  4695. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  4696. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  4697. return;
  4698. }
  4699. try {
  4700. const res = await fetch(`${API_BASE}/firewall/mangle`);
  4701. if (!res.ok) return;
  4702. const rules = await res.json();
  4703. const r = rules.find(x => x.id === id);
  4704. if (!r) return;
  4705. const now = Date.now();
  4706. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  4707. state.mangleLastTimestamp = now;
  4708. const curBytes = r.bytes || 0;
  4709. const curPackets = r.packets || 0;
  4710. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  4711. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  4712. state.mangleLastBytes = curBytes;
  4713. state.mangleLastPackets = curPackets;
  4714. const rateBps = Math.round((deltaBytes * 8) / dt);
  4715. const ratePkt = Math.round(deltaPkts / dt);
  4716. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  4717. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  4718. state.mangleStatRateHistory.push(rateBps);
  4719. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  4720. state.mangleStatPktHistory.push(ratePkt);
  4721. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  4722. const bEl = document.getElementById('mangle-stat-bytes');
  4723. const pEl = document.getElementById('mangle-stat-packets');
  4724. const rEl = document.getElementById('mangle-stat-rate');
  4725. const prEl = document.getElementById('mangle-stat-pktrate');
  4726. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4727. if (pEl) pEl.value = curPackets.toLocaleString();
  4728. if (rEl) rEl.value = formatBps(rateBps);
  4729. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4730. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4731. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4732. } catch (e) {
  4733. console.error('Error polling Mangle rule stats', e);
  4734. }
  4735. }
  4736. async function moveMangleRule(id, dir) {
  4737. try {
  4738. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  4739. method: 'POST',
  4740. headers: { 'Content-Type': 'application/json' },
  4741. body: JSON.stringify({ direction: dir })
  4742. });
  4743. if (res.ok) loadFirewall(false);
  4744. } catch (err) {
  4745. showToast('Error', err.message, 'error');
  4746. }
  4747. }
  4748. async function toggleMangleRuleState(id, disabled) {
  4749. try {
  4750. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  4751. method: 'POST',
  4752. headers: { 'Content-Type': 'application/json' },
  4753. body: JSON.stringify({ disabled })
  4754. });
  4755. if (res.ok) loadFirewall(false);
  4756. } catch (err) {
  4757. showToast('Error', err.message, 'error');
  4758. }
  4759. }
  4760. async function deleteMangleRule(id) {
  4761. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  4762. try {
  4763. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4764. if (res.ok) {
  4765. showToast('Deleted', 'Mangle rule removed', 'success');
  4766. loadFirewall(false);
  4767. }
  4768. } catch (err) {
  4769. showToast('Error', err.message, 'error');
  4770. }
  4771. }
  4772. // ----------------- Address Lists -----------------
  4773. function renderAddressLists() {
  4774. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  4775. const tbody = document.getElementById('addrlist-table-body');
  4776. const empty = document.getElementById('addrlist-empty');
  4777. if (!tbody) return;
  4778. tbody.innerHTML = '';
  4779. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  4780. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  4781. // Update filter select
  4782. const sel = document.getElementById('addrlist-filter-name');
  4783. if (sel) {
  4784. const cur = sel.value;
  4785. sel.innerHTML = '<option value="">All Lists</option>';
  4786. const set = new Set((state.addressLists || []).map(a => a.name));
  4787. set.forEach(n => {
  4788. const opt = document.createElement('option');
  4789. opt.value = n;
  4790. opt.innerText = n;
  4791. if (n === cur) opt.selected = true;
  4792. sel.appendChild(opt);
  4793. });
  4794. }
  4795. if (entries.length === 0) {
  4796. empty?.classList.remove('hidden');
  4797. return;
  4798. }
  4799. empty?.classList.add('hidden');
  4800. entries.forEach((e, idx) => {
  4801. const tr = document.createElement('tr');
  4802. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  4803. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  4804. tr.innerHTML = `
  4805. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  4806. <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>
  4807. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  4808. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  4809. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  4810. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4811. <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>
  4812. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  4813. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4814. </td>
  4815. `;
  4816. tbody.appendChild(tr);
  4817. });
  4818. populateCommonAddrListDatalist();
  4819. }
  4820. function openAddAddrListModal() {
  4821. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  4822. document.getElementById('addrlist-modal-id').value = '';
  4823. document.getElementById('addrlist-modal-name').value = '';
  4824. document.getElementById('addrlist-modal-addr').value = '';
  4825. document.getElementById('addrlist-modal-comment').value = '';
  4826. document.getElementById('addrlist-modal-disabled').checked = false;
  4827. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4828. if (submitBtn) submitBtn.innerText = 'Add to List';
  4829. document.getElementById('addrlist-modal').classList.remove('hidden');
  4830. }
  4831. function openEditAddrListModal(id) {
  4832. const e = (state.addressLists || []).find(item => item.id === id);
  4833. if (!e) return;
  4834. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  4835. document.getElementById('addrlist-modal-id').value = e.id;
  4836. document.getElementById('addrlist-modal-name').value = e.name;
  4837. document.getElementById('addrlist-modal-addr').value = e.address;
  4838. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  4839. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  4840. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4841. if (submitBtn) submitBtn.innerText = 'Save Changes';
  4842. document.getElementById('addrlist-modal').classList.remove('hidden');
  4843. }
  4844. function closeAddrListModal() {
  4845. document.getElementById('addrlist-modal').classList.add('hidden');
  4846. }
  4847. async function submitSaveAddrList(e) {
  4848. e.preventDefault();
  4849. const id = document.getElementById('addrlist-modal-id').value;
  4850. const name = document.getElementById('addrlist-modal-name').value.trim();
  4851. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  4852. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  4853. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  4854. try {
  4855. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  4856. method: 'POST',
  4857. headers: { 'Content-Type': 'application/json' },
  4858. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  4859. });
  4860. if (res.ok) {
  4861. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  4862. closeAddrListModal();
  4863. loadFirewall(false);
  4864. } else {
  4865. const err = await res.json();
  4866. showToast('Error', err.message || 'Failed to save address list', 'error');
  4867. }
  4868. } catch (err) {
  4869. showToast('Error', err.message, 'error');
  4870. }
  4871. }
  4872. async function toggleAddrListState(id, disabled) {
  4873. try {
  4874. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  4875. method: 'POST',
  4876. headers: { 'Content-Type': 'application/json' },
  4877. body: JSON.stringify({ disabled })
  4878. });
  4879. if (res.ok) {
  4880. loadFirewall(false);
  4881. }
  4882. } catch (err) {
  4883. showToast('Error', err.message, 'error');
  4884. }
  4885. }
  4886. async function deleteAddrList(id) {
  4887. if (!confirm('Are you sure you want to delete this address list item?')) return;
  4888. try {
  4889. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4890. if (res.ok) {
  4891. showToast('Deleted', 'Address list item removed', 'info');
  4892. loadFirewall(false);
  4893. }
  4894. } catch (err) {
  4895. showToast('Error', err.message, 'error');
  4896. }
  4897. }
  4898. // ----------------- Geo-Location IP Management -----------------
  4899. async function loadGeoIP() {
  4900. try {
  4901. const [statusRes, countriesRes] = await Promise.all([
  4902. fetch(`${API_BASE}/firewall/geoip/status`),
  4903. fetch(`${API_BASE}/firewall/geoip/countries`)
  4904. ]);
  4905. if (statusRes.ok) state.geoStatus = await statusRes.json();
  4906. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  4907. updateGeoHeader();
  4908. renderGeoCountries();
  4909. } catch (err) {
  4910. console.error('Failed to load GeoIP:', err);
  4911. }
  4912. }
  4913. function getGeoUsageMap() {
  4914. const usage = {};
  4915. const checkRule = (r, type) => {
  4916. ['src_geoip', 'dst_geoip'].forEach(field => {
  4917. let val = (r && r[field]) || '';
  4918. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  4919. if (code) {
  4920. if (!usage[code]) usage[code] = [];
  4921. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  4922. if (!usage[code].includes(label)) usage[code].push(label);
  4923. }
  4924. });
  4925. };
  4926. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  4927. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  4928. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  4929. return usage;
  4930. }
  4931. function updateGeoHeader() {
  4932. const s = state.geoStatus || {};
  4933. const statusBadge = document.getElementById('geo-status-badge');
  4934. if (statusBadge) {
  4935. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  4936. statusBadge.className = s.auto_update
  4937. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  4938. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  4939. }
  4940. const intervalLabel = document.getElementById('geo-interval-label');
  4941. if (intervalLabel) {
  4942. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  4943. }
  4944. const usageMap = getGeoUsageMap();
  4945. const inUseCount = Object.keys(usageMap).length;
  4946. const activeCountEl = document.getElementById('geo-stat-active-countries');
  4947. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  4948. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  4949. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  4950. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  4951. if (lastSyncEl) {
  4952. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  4953. const d = new Date(s.last_updated);
  4954. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4955. } else {
  4956. lastSyncEl.innerText = 'Never (Sync Pending)';
  4957. }
  4958. }
  4959. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  4960. if (nextSyncEl) {
  4961. if (s.next_update && !s.next_update.startsWith('0001')) {
  4962. const d = new Date(s.next_update);
  4963. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4964. } else {
  4965. nextSyncEl.innerText = '-';
  4966. }
  4967. }
  4968. const badge = document.getElementById('fw-badge-geo');
  4969. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  4970. }
  4971. function renderGeoCountries() {
  4972. const tbody = document.getElementById('geo-table-body');
  4973. const empty = document.getElementById('geo-empty');
  4974. if (!tbody) return;
  4975. tbody.innerHTML = '';
  4976. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  4977. const continent = document.getElementById('geo-continent-filter')?.value || '';
  4978. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  4979. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  4980. const usageMap = getGeoUsageMap();
  4981. const countries = (state.geoCountries || []).filter(c => {
  4982. const isUsed = !!usageMap[c.code];
  4983. if (inUseOnly && !isUsed) return false;
  4984. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  4985. if (continent && c.continent !== continent) return false;
  4986. if (q) {
  4987. const matchCode = c.code.toLowerCase().includes(q);
  4988. const matchName = c.name.toLowerCase().includes(q);
  4989. if (!matchCode && !matchName) return false;
  4990. }
  4991. return true;
  4992. });
  4993. if (countries.length === 0) {
  4994. empty?.classList.remove('hidden');
  4995. return;
  4996. }
  4997. empty?.classList.add('hidden');
  4998. countries.forEach(c => {
  4999. const tr = document.createElement('tr');
  5000. const isUsed = !!usageMap[c.code];
  5001. const rulesUsing = usageMap[c.code] || [];
  5002. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  5003. let statusHtml = '';
  5004. if (isUsed) {
  5005. 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>`;
  5006. } else if (c.subnet_count > 0) {
  5007. 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>';
  5008. } else {
  5009. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  5010. }
  5011. tr.innerHTML = `
  5012. <td class="py-2.5 px-3 text-center">
  5013. <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'}">
  5014. ${c.code}
  5015. </span>
  5016. </td>
  5017. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  5018. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  5019. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  5020. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  5021. </td>
  5022. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  5023. <td class="py-2.5 px-3">
  5024. ${statusHtml}
  5025. </td>
  5026. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5027. <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>
  5028. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  5029. </td>
  5030. `;
  5031. tbody.appendChild(tr);
  5032. });
  5033. }
  5034. function quickFilterGeo(preset) {
  5035. const searchInput = document.getElementById('geo-search-input');
  5036. const continentSel = document.getElementById('geo-continent-filter');
  5037. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  5038. const cachedCheck = document.getElementById('geo-filter-cached-only');
  5039. if (searchInput) searchInput.value = '';
  5040. if (continentSel) continentSel.value = '';
  5041. if (inUseCheck) inUseCheck.checked = false;
  5042. if (cachedCheck) cachedCheck.checked = false;
  5043. if (preset === 'GR') {
  5044. if (searchInput) searchInput.value = 'Greece';
  5045. } else if (preset === 'Europe') {
  5046. if (continentSel) continentSel.value = 'Europe';
  5047. } else if (preset === 'HIGHRISK') {
  5048. if (searchInput) searchInput.value = 'China';
  5049. }
  5050. renderGeoCountries();
  5051. }
  5052. async function toggleGeoCountry(code, enabled) {
  5053. try {
  5054. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  5055. method: 'POST',
  5056. headers: { 'Content-Type': 'application/json' },
  5057. body: JSON.stringify({ enabled })
  5058. });
  5059. if (res.ok) {
  5060. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  5061. loadGeoIP();
  5062. } else {
  5063. const err = await res.json();
  5064. showToast('Error', err.message || 'Failed to toggle country', 'error');
  5065. }
  5066. } catch (err) {
  5067. showToast('Error', err.message, 'error');
  5068. }
  5069. }
  5070. async function updateGeoCountry(code) {
  5071. try {
  5072. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  5073. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  5074. if (res.ok) {
  5075. const data = await res.json();
  5076. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  5077. loadGeoIP();
  5078. } else {
  5079. const err = await res.json();
  5080. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  5081. }
  5082. } catch (err) {
  5083. showToast('Error', err.message, 'error');
  5084. }
  5085. }
  5086. async function triggerGeoUpdateNow() {
  5087. const spinner = document.getElementById('geo-update-spinner');
  5088. if (spinner) spinner.classList.remove('hidden');
  5089. try {
  5090. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  5091. if (res.ok) {
  5092. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  5093. setTimeout(() => {
  5094. loadGeoIP();
  5095. if (spinner) spinner.classList.add('hidden');
  5096. }, 2500);
  5097. } else {
  5098. const err = await res.json();
  5099. showToast('Notice', err.message || 'Update in progress', 'info');
  5100. if (spinner) spinner.classList.add('hidden');
  5101. }
  5102. } catch (err) {
  5103. showToast('Error', err.message, 'error');
  5104. if (spinner) spinner.classList.add('hidden');
  5105. }
  5106. }
  5107. async function applyGeoPreset(preset) {
  5108. try {
  5109. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  5110. method: 'POST',
  5111. headers: { 'Content-Type': 'application/json' },
  5112. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  5113. });
  5114. if (res.ok) {
  5115. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  5116. loadGeoIP();
  5117. }
  5118. } catch (err) {
  5119. showToast('Error', err.message, 'error');
  5120. }
  5121. }
  5122. function openGeoIntervalModal() {
  5123. const s = state.geoStatus || {};
  5124. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  5125. const sel = document.getElementById('geo-cfg-interval');
  5126. const customBox = document.getElementById('geo-cfg-custom-box');
  5127. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  5128. const curHours = s.interval_hours || 24;
  5129. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  5130. if (matchOption) {
  5131. sel.value = String(curHours);
  5132. customBox.classList.add('hidden');
  5133. } else {
  5134. sel.value = 'custom';
  5135. customHoursInput.value = curHours;
  5136. customBox.classList.remove('hidden');
  5137. }
  5138. document.getElementById('geo-interval-modal').classList.remove('hidden');
  5139. }
  5140. function closeGeoIntervalModal() {
  5141. document.getElementById('geo-interval-modal').classList.add('hidden');
  5142. }
  5143. function toggleCustomGeoInterval() {
  5144. const val = document.getElementById('geo-cfg-interval').value;
  5145. const customBox = document.getElementById('geo-cfg-custom-box');
  5146. if (val === 'custom') {
  5147. customBox.classList.remove('hidden');
  5148. } else {
  5149. customBox.classList.add('hidden');
  5150. }
  5151. }
  5152. async function submitGeoIntervalSettings(e) {
  5153. e.preventDefault();
  5154. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5155. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5156. let hours = 24;
  5157. if (intervalVal === 'custom') {
  5158. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5159. } else {
  5160. hours = parseInt(intervalVal, 10) || 24;
  5161. }
  5162. try {
  5163. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5164. method: 'POST',
  5165. headers: { 'Content-Type': 'application/json' },
  5166. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5167. });
  5168. if (res.ok) {
  5169. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5170. closeGeoIntervalModal();
  5171. loadGeoIP();
  5172. } else {
  5173. const err = await res.json();
  5174. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5175. }
  5176. } catch (err) {
  5177. showToast('Error', err.message, 'error');
  5178. }
  5179. }
  5180. async function viewGeoSubnets(code, name) {
  5181. if (!name) {
  5182. const found = (state.geoCountries || []).find(x => x.code === code);
  5183. name = found ? found.name : code;
  5184. }
  5185. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5186. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5187. const listEl = document.getElementById('geo-subnets-list');
  5188. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5189. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5190. try {
  5191. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5192. if (res.ok) {
  5193. const data = await res.json();
  5194. const subnets = data.subnets || [];
  5195. if (subnets.length === 0) {
  5196. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5197. } else {
  5198. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5199. }
  5200. } else {
  5201. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5202. }
  5203. } catch (err) {
  5204. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5205. }
  5206. }
  5207. function closeGeoSubnetsModal() {
  5208. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5209. }
  5210. // ----------------- Active Connections Tracking -----------------
  5211. async function loadConnections() {
  5212. try {
  5213. const res = await fetch(`${API_BASE}/firewall/connections`);
  5214. const data = await res.json();
  5215. state.connections = Array.isArray(data) ? data : [];
  5216. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5217. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5218. renderConnections();
  5219. } catch (err) {
  5220. console.error('Failed to load connections:', err);
  5221. }
  5222. }
  5223. function renderConnections() {
  5224. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  5225. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  5226. const tbody = document.getElementById('conns-table-body');
  5227. const empty = document.getElementById('conns-empty');
  5228. if (!tbody) return;
  5229. tbody.innerHTML = '';
  5230. const conns = (state.connections || []).filter(c => {
  5231. if (protoFilter && c.protocol !== protoFilter) return false;
  5232. if (search) {
  5233. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  5234. if (!line.includes(search)) return false;
  5235. }
  5236. return true;
  5237. });
  5238. if (conns.length === 0) {
  5239. empty?.classList.remove('hidden');
  5240. return;
  5241. }
  5242. empty?.classList.add('hidden');
  5243. conns.slice(0, 150).forEach(c => {
  5244. const tr = document.createElement('tr');
  5245. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5246. let stateColor = 'text-slate-400';
  5247. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  5248. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  5249. tr.innerHTML = `
  5250. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  5251. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  5252. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  5253. <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>
  5254. <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>
  5255. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  5256. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  5257. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  5258. <td class="py-2.5 px-3 text-right font-sans">
  5259. <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>
  5260. </td>
  5261. `;
  5262. tbody.appendChild(tr);
  5263. });
  5264. }
  5265. async function killConnection(protocol, src, sport, dst, dport) {
  5266. try {
  5267. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  5268. method: 'POST',
  5269. headers: { 'Content-Type': 'application/json' },
  5270. body: JSON.stringify({ protocol, src, sport, dst, dport })
  5271. });
  5272. if (res.ok) {
  5273. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  5274. loadConnections();
  5275. }
  5276. } catch (err) {
  5277. showToast('Error', err.message, 'error');
  5278. }
  5279. }
  5280. async function resetFirewallCounters() {
  5281. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  5282. try {
  5283. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  5284. if (res.ok) {
  5285. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  5286. loadFirewall(false);
  5287. }
  5288. } catch (err) {
  5289. showToast('Error', err.message, 'error');
  5290. }
  5291. }
  5292. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  5293. function switchRoutesSubTab(tab) {
  5294. state.routesSubTab = tab;
  5295. const tabs = ['routes', 'rules', 'tables'];
  5296. tabs.forEach(t => {
  5297. const panel = document.getElementById(`routes-subtab-${t}`);
  5298. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  5299. if (panel) {
  5300. if (t === tab) panel.classList.remove('hidden');
  5301. else panel.classList.add('hidden');
  5302. }
  5303. if (btn) {
  5304. if (t === tab) {
  5305. 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';
  5306. } else {
  5307. 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';
  5308. }
  5309. }
  5310. });
  5311. setTimeout(initTableSorting, 50);
  5312. }
  5313. async function loadRoutes() {
  5314. try {
  5315. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  5316. fetch(`${API_BASE}/routes`),
  5317. fetch(`${API_BASE}/routing/rules`),
  5318. fetch(`${API_BASE}/routing/tables`)
  5319. ]);
  5320. if (routesRes.ok) state.routes = await routesRes.json();
  5321. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  5322. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  5323. const bRoutes = document.getElementById('routes-badge-routes');
  5324. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  5325. const showSystem = document.getElementById('prule-show-system')?.checked;
  5326. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5327. const bRules = document.getElementById('routes-badge-rules');
  5328. if (bRules) bRules.innerText = userRules.length;
  5329. const bTables = document.getElementById('routes-badge-tables');
  5330. if (bTables) bTables.innerText = (state.routingTables || []).length;
  5331. const bRoutesCount = document.getElementById('badge-routes-count');
  5332. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  5333. renderRoutesList();
  5334. renderPolicyRules();
  5335. renderRoutingTables();
  5336. } catch (err) {
  5337. console.error('Failed to load routing:', err);
  5338. }
  5339. }
  5340. function renderRoutesList() {
  5341. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  5342. const tbody = document.getElementById('routes-table-body');
  5343. const empty = document.getElementById('routes-empty');
  5344. if (!tbody) return;
  5345. tbody.innerHTML = '';
  5346. // Update table filter select
  5347. const sel = document.getElementById('routes-filter-table');
  5348. if (sel) {
  5349. const cur = sel.value;
  5350. sel.innerHTML = '<option value="">All Tables</option>';
  5351. (state.routingTables || []).forEach(t => {
  5352. const opt = document.createElement('option');
  5353. opt.value = t.name;
  5354. opt.innerText = t.name;
  5355. if (t.name === cur) opt.selected = true;
  5356. sel.appendChild(opt);
  5357. });
  5358. }
  5359. const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
  5360. document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
  5361. if (routes.length === 0) {
  5362. empty?.classList.remove('hidden');
  5363. return;
  5364. }
  5365. empty?.classList.add('hidden');
  5366. routes.forEach(r => {
  5367. const tr = document.createElement('tr');
  5368. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  5369. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  5370. // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
  5371. let flags = '';
  5372. if (r.dynamic) flags += 'D';
  5373. if (r.active) flags += 'A';
  5374. if (r.connect) flags += 'C';
  5375. if (r.static) flags += 'S';
  5376. if (r.disabled) flags += 'X';
  5377. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  5378. tr.innerHTML = `
  5379. <td class="py-2.5 px-3 text-center">
  5380. <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'}">
  5381. ${flags || '-'}
  5382. </span>
  5383. </td>
  5384. <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
  5385. <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>
  5386. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  5387. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  5388. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  5389. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  5390. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5391. ${r.static ? `
  5392. <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>
  5393. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  5394. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5395. ` : `
  5396. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  5397. `}
  5398. </td>
  5399. `;
  5400. tbody.appendChild(tr);
  5401. });
  5402. }
  5403. function openAddRouteModal() {
  5404. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  5405. document.getElementById('route-modal-id').value = '';
  5406. document.getElementById('route-modal-old-dst').value = '';
  5407. document.getElementById('route-modal-old-gw').value = '';
  5408. document.getElementById('route-modal-old-distance').value = '';
  5409. document.getElementById('route-modal-old-table').value = '';
  5410. document.getElementById('route-modal-old-iface').value = '';
  5411. const dstInput = document.getElementById('route-modal-dst');
  5412. const gwInput = document.getElementById('route-modal-gw');
  5413. const distInput = document.getElementById('route-modal-distance');
  5414. const ifaceSelect = document.getElementById('route-modal-iface');
  5415. const tableSelect = document.getElementById('route-modal-table');
  5416. const commentInput = document.getElementById('route-modal-comment');
  5417. const disCheck = document.getElementById('route-modal-disabled');
  5418. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5419. dstInput.disabled = false;
  5420. dstInput.value = '0.0.0.0/0';
  5421. gwInput.disabled = false;
  5422. gwInput.value = '';
  5423. distInput.disabled = false;
  5424. distInput.value = '1';
  5425. ifaceSelect.disabled = false;
  5426. tableSelect.disabled = false;
  5427. commentInput.disabled = false;
  5428. commentInput.value = '';
  5429. disCheck.disabled = false;
  5430. disCheck.checked = false;
  5431. if (saveBtn) saveBtn.classList.remove('hidden');
  5432. populateInterfaceSelect('route-modal-iface');
  5433. // Populate tables
  5434. tableSelect.innerHTML = '';
  5435. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5436. const opt = document.createElement('option');
  5437. opt.value = t.name;
  5438. opt.innerText = t.name;
  5439. if (t.name === 'main') opt.selected = true;
  5440. tableSelect.appendChild(opt);
  5441. });
  5442. document.getElementById('route-modal').classList.remove('hidden');
  5443. }
  5444. function openEditRouteModal(id) {
  5445. const r = (state.routes || []).find(route => route.id === id);
  5446. if (!r) return;
  5447. const isStatic = !!r.static;
  5448. document.getElementById('route-modal-title').innerText = isStatic
  5449. ? `Edit Route: ${r.dst_address}`
  5450. : `Route Properties (Read Only): ${r.dst_address}`;
  5451. document.getElementById('route-modal-id').value = r.id;
  5452. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  5453. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  5454. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  5455. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  5456. document.getElementById('route-modal-old-iface').value = r.interface || '';
  5457. const dstInput = document.getElementById('route-modal-dst');
  5458. const gwInput = document.getElementById('route-modal-gw');
  5459. const distInput = document.getElementById('route-modal-distance');
  5460. const ifaceSelect = document.getElementById('route-modal-iface');
  5461. const tableSelect = document.getElementById('route-modal-table');
  5462. const commentInput = document.getElementById('route-modal-comment');
  5463. const disCheck = document.getElementById('route-modal-disabled');
  5464. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5465. dstInput.value = r.dst_address;
  5466. gwInput.value = r.gateway || '';
  5467. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  5468. commentInput.value = r.comment || '';
  5469. disCheck.checked = !!r.disabled;
  5470. dstInput.disabled = !isStatic;
  5471. gwInput.disabled = !isStatic;
  5472. distInput.disabled = !isStatic;
  5473. ifaceSelect.disabled = !isStatic;
  5474. tableSelect.disabled = !isStatic;
  5475. commentInput.disabled = !isStatic;
  5476. disCheck.disabled = !isStatic;
  5477. if (saveBtn) {
  5478. if (isStatic) {
  5479. saveBtn.classList.remove('hidden');
  5480. } else {
  5481. saveBtn.classList.add('hidden');
  5482. }
  5483. }
  5484. populateInterfaceSelect('route-modal-iface', r.interface);
  5485. tableSelect.innerHTML = '';
  5486. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5487. const opt = document.createElement('option');
  5488. opt.value = t.name;
  5489. opt.innerText = t.name;
  5490. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  5491. tableSelect.appendChild(opt);
  5492. });
  5493. document.getElementById('route-modal').classList.remove('hidden');
  5494. }
  5495. function closeRouteModal() {
  5496. document.getElementById('route-modal').classList.add('hidden');
  5497. }
  5498. async function submitSaveRoute(e) {
  5499. e.preventDefault();
  5500. const id = document.getElementById('route-modal-id').value;
  5501. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  5502. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  5503. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  5504. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  5505. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  5506. const dst = document.getElementById('route-modal-dst').value.trim();
  5507. const gw = document.getElementById('route-modal-gw').value.trim();
  5508. const table = document.getElementById('route-modal-table').value;
  5509. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  5510. const iface = document.getElementById('route-modal-iface').value;
  5511. const comment = document.getElementById('route-modal-comment').value.trim();
  5512. const disabled = document.getElementById('route-modal-disabled').checked;
  5513. if (!dst) {
  5514. showToast('Error', 'Destination address is required', 'error');
  5515. return;
  5516. }
  5517. if (!gw && !iface) {
  5518. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  5519. return;
  5520. }
  5521. const payload = {
  5522. id,
  5523. old_dst_address: oldDst,
  5524. old_gateway: oldGw,
  5525. old_routing_table: oldTable,
  5526. old_interface: oldIface,
  5527. dst_address: dst,
  5528. gateway: gw || iface,
  5529. routing_table: table,
  5530. distance,
  5531. interface: iface,
  5532. comment,
  5533. disabled
  5534. };
  5535. if (oldDistStr !== undefined && oldDistStr !== '') {
  5536. payload.old_distance = parseInt(oldDistStr, 10);
  5537. }
  5538. try {
  5539. const res = await fetch(`${API_BASE}/routes`, {
  5540. method: 'POST',
  5541. headers: { 'Content-Type': 'application/json' },
  5542. body: JSON.stringify(payload)
  5543. });
  5544. if (res.ok) {
  5545. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  5546. closeRouteModal();
  5547. loadRoutes();
  5548. } else {
  5549. const err = await res.json();
  5550. showToast('Error', err.message || 'Failed to save route', 'error');
  5551. }
  5552. } catch (err) {
  5553. showToast('Error', err.message, 'error');
  5554. }
  5555. }
  5556. async function toggleRouteState(id, disabled) {
  5557. try {
  5558. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  5559. method: 'POST',
  5560. headers: { 'Content-Type': 'application/json' },
  5561. body: JSON.stringify({ disabled })
  5562. });
  5563. if (res.ok) loadRoutes();
  5564. } catch (err) {
  5565. showToast('Error', err.message, 'error');
  5566. }
  5567. }
  5568. async function deleteRoute(id) {
  5569. if (!confirm('Are you sure you want to delete this route?')) return;
  5570. try {
  5571. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5572. if (res.ok) {
  5573. showToast('Deleted', 'Route removed', 'success');
  5574. loadRoutes();
  5575. }
  5576. } catch (err) {
  5577. showToast('Error', err.message, 'error');
  5578. }
  5579. }
  5580. // ----------------- Policy Rules (/ip route rule) -----------------
  5581. function renderPolicyRules() {
  5582. const tbody = document.getElementById('rules-table-body');
  5583. const empty = document.getElementById('rules-empty');
  5584. if (!tbody) return;
  5585. tbody.innerHTML = '';
  5586. const showSystem = document.getElementById('prule-show-system')?.checked;
  5587. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5588. const countBadge = document.getElementById('rules-count-badge');
  5589. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  5590. const bRules = document.getElementById('routes-badge-rules');
  5591. if (bRules) bRules.innerText = filtered.length;
  5592. if (filtered.length === 0) {
  5593. empty?.classList.remove('hidden');
  5594. return;
  5595. }
  5596. empty?.classList.add('hidden');
  5597. filtered.forEach(pr => {
  5598. const isSys = pr.is_default || pr.is_system;
  5599. const tr = document.createElement('tr');
  5600. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  5601. tr.innerHTML = `
  5602. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  5603. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  5604. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  5605. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  5606. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  5607. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  5608. <td class="py-2.5 px-3 text-right font-sans">
  5609. ${!pr.is_default ? `
  5610. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5611. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  5612. </td>
  5613. `;
  5614. tbody.appendChild(tr);
  5615. });
  5616. }
  5617. function openAddPolicyRuleModal() {
  5618. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  5619. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  5620. document.getElementById('prule-modal-mark').value = '';
  5621. document.getElementById('prule-modal-src').value = '';
  5622. document.getElementById('prule-modal-dst').value = '';
  5623. const sel = document.getElementById('prule-modal-table');
  5624. sel.innerHTML = '';
  5625. (state.routingTables || []).forEach(t => {
  5626. const opt = document.createElement('option');
  5627. opt.value = t.name;
  5628. opt.innerText = t.name;
  5629. sel.appendChild(opt);
  5630. });
  5631. document.getElementById('prule-modal').classList.remove('hidden');
  5632. }
  5633. function closePolicyRuleModal() {
  5634. document.getElementById('prule-modal').classList.add('hidden');
  5635. }
  5636. async function submitSavePolicyRule(e) {
  5637. e.preventDefault();
  5638. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  5639. const mark = document.getElementById('prule-modal-mark').value.trim();
  5640. const src = document.getElementById('prule-modal-src').value.trim();
  5641. const dst = document.getElementById('prule-modal-dst').value.trim();
  5642. const table = document.getElementById('prule-modal-table').value;
  5643. const action = document.getElementById('prule-modal-action').value;
  5644. try {
  5645. const res = await fetch(`${API_BASE}/routing/rules`, {
  5646. method: 'POST',
  5647. headers: { 'Content-Type': 'application/json' },
  5648. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  5649. });
  5650. if (res.ok) {
  5651. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  5652. closePolicyRuleModal();
  5653. loadRoutes();
  5654. } else {
  5655. const err = await res.json();
  5656. showToast('Error', err.message, 'error');
  5657. }
  5658. } catch (err) {
  5659. showToast('Error', err.message, 'error');
  5660. }
  5661. }
  5662. async function deletePolicyRule(id) {
  5663. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  5664. try {
  5665. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5666. if (res.ok) {
  5667. showToast('Rule Removed', 'Policy rule deleted', 'success');
  5668. loadRoutes();
  5669. }
  5670. } catch (err) {
  5671. showToast('Error', err.message, 'error');
  5672. }
  5673. }
  5674. // ----------------- Routing Tables -----------------
  5675. function renderRoutingTables() {
  5676. const tbody = document.getElementById('tables-table-body');
  5677. if (!tbody) return;
  5678. tbody.innerHTML = '';
  5679. (state.routingTables || []).forEach(t => {
  5680. const tr = document.createElement('tr');
  5681. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5682. tr.innerHTML = `
  5683. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  5684. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  5685. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  5686. `;
  5687. tbody.appendChild(tr);
  5688. });
  5689. }
  5690. function openAddTableModal() {
  5691. document.getElementById('table-modal-name').value = '';
  5692. document.getElementById('table-modal-id').value = '';
  5693. document.getElementById('table-modal-comment').value = '';
  5694. document.getElementById('table-modal').classList.remove('hidden');
  5695. }
  5696. function closeTableModal() {
  5697. document.getElementById('table-modal').classList.add('hidden');
  5698. }
  5699. async function submitSaveTable(e) {
  5700. e.preventDefault();
  5701. const name = document.getElementById('table-modal-name').value.trim();
  5702. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  5703. const comment = document.getElementById('table-modal-comment').value.trim();
  5704. try {
  5705. const res = await fetch(`${API_BASE}/routing/tables`, {
  5706. method: 'POST',
  5707. headers: { 'Content-Type': 'application/json' },
  5708. body: JSON.stringify({ name, table_id: id, comment })
  5709. });
  5710. if (res.ok) {
  5711. showToast('Table Created', `Routing table ${name} registered`, 'success');
  5712. closeTableModal();
  5713. loadRoutes();
  5714. } else {
  5715. const err = await res.json();
  5716. showToast('Error', err.message, 'error');
  5717. }
  5718. } catch (err) {
  5719. showToast('Error', err.message, 'error');
  5720. }
  5721. }
  5722. async function loadDebianConfig() {
  5723. const view = document.getElementById('debian-config-view');
  5724. view.innerText = 'Generating live configuration...';
  5725. try {
  5726. const res = await fetch(`${API_BASE}/debian/config`);
  5727. const data = await res.json();
  5728. view.innerText = data.content || '# Empty config';
  5729. } catch (err) {
  5730. view.innerText = 'Failed to generate Debian network config.';
  5731. }
  5732. }
  5733. async function saveDebianConfig() {
  5734. try {
  5735. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  5736. const data = await res.json();
  5737. if (res.ok) {
  5738. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  5739. loadDebianConfig();
  5740. }
  5741. } catch (err) {
  5742. showToast('Error', err.message, 'error');
  5743. }
  5744. }
  5745. function showToast(title, message, type = 'info') {
  5746. const container = document.getElementById('toast-container');
  5747. const toast = document.createElement('div');
  5748. const borderColors = {
  5749. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  5750. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  5751. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  5752. };
  5753. 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}`;
  5754. toast.innerHTML = `
  5755. <div class="flex-1">
  5756. <div class="font-bold text-xs text-white">${title}</div>
  5757. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  5758. </div>
  5759. `;
  5760. container.appendChild(toast);
  5761. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  5762. setTimeout(() => {
  5763. toast.classList.add('opacity-0', 'translate-y-2');
  5764. setTimeout(() => toast.remove(), 300);
  5765. }, 4000);
  5766. }
  5767. function formatTraffic(bytesPerSec) {
  5768. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  5769. const kb = bytesPerSec / 1024;
  5770. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  5771. const mb = kb / 1024;
  5772. return `${mb.toFixed(2)} MB/s`;
  5773. }
  5774. function toggleSidebar() {
  5775. const sb = document.getElementById('sidebar');
  5776. sb.classList.toggle('-translate-x-full');
  5777. }
  5778. // ======================== EoIP (Ethernet over IP) ========================
  5779. async function loadEoIP(populate = true) {
  5780. try {
  5781. const res = await fetch(`${API_BASE}/vpn/eoip`);
  5782. const data = await res.json();
  5783. state.eoipTunnels = Array.isArray(data) ? data : [];
  5784. const badge = document.getElementById('eoip-count-badge');
  5785. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  5786. const sideBadge = document.getElementById('badge-eoip-count');
  5787. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  5788. renderEoIPTunnels();
  5789. } catch (err) {
  5790. console.error('Failed to load EoIP:', err);
  5791. }
  5792. }
  5793. function renderEoIPTunnels() {
  5794. const tbody = document.getElementById('eoip-table-body');
  5795. const empty = document.getElementById('eoip-empty');
  5796. if (!tbody) return;
  5797. tbody.innerHTML = '';
  5798. const tunnels = state.eoipTunnels || [];
  5799. if (tunnels.length === 0) {
  5800. empty?.classList.remove('hidden');
  5801. return;
  5802. }
  5803. empty?.classList.add('hidden');
  5804. tunnels.forEach(t => {
  5805. const tr = document.createElement('tr');
  5806. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  5807. tr.innerHTML = `
  5808. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  5809. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  5810. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  5811. <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>
  5812. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  5813. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  5814. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  5815. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  5816. <td class="py-2.5 px-3 font-mono text-[11px]">
  5817. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  5818. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  5819. </td>
  5820. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  5821. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5822. <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>
  5823. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5824. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  5825. </td>
  5826. `;
  5827. tbody.appendChild(tr);
  5828. });
  5829. }
  5830. function openAddEoIPModal() {
  5831. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  5832. document.getElementById('eoip-modal-id').value = '';
  5833. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  5834. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  5835. document.getElementById('eoip-modal-remote').value = '';
  5836. document.getElementById('eoip-modal-ip').value = '';
  5837. document.getElementById('eoip-modal-local').value = '';
  5838. document.getElementById('eoip-modal-mac').value = '';
  5839. document.getElementById('eoip-modal-mtu').value = '1500';
  5840. document.getElementById('eoip-modal-comment').value = '';
  5841. document.getElementById('eoip-modal-clampmss').checked = true;
  5842. document.getElementById('eoip-modal-disabled').checked = false;
  5843. document.getElementById('eoip-modal').classList.remove('hidden');
  5844. }
  5845. function openEditEoIPModal(id) {
  5846. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  5847. if (!t) return;
  5848. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  5849. document.getElementById('eoip-modal-id').value = t.id;
  5850. document.getElementById('eoip-modal-name').value = t.name;
  5851. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  5852. document.getElementById('eoip-modal-remote').value = t.remote_address;
  5853. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  5854. document.getElementById('eoip-modal-local').value = t.local_address || '';
  5855. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  5856. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  5857. document.getElementById('eoip-modal-comment').value = t.comment || '';
  5858. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  5859. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  5860. document.getElementById('eoip-modal').classList.remove('hidden');
  5861. }
  5862. function closeEoIPModal() {
  5863. document.getElementById('eoip-modal').classList.add('hidden');
  5864. }
  5865. async function submitSaveEoIP(e) {
  5866. e.preventDefault();
  5867. const id = document.getElementById('eoip-modal-id').value;
  5868. const name = document.getElementById('eoip-modal-name').value.trim();
  5869. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  5870. const remote = document.getElementById('eoip-modal-remote').value.trim();
  5871. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  5872. const local = document.getElementById('eoip-modal-local').value.trim();
  5873. const mac = document.getElementById('eoip-modal-mac').value.trim();
  5874. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  5875. const comment = document.getElementById('eoip-modal-comment').value.trim();
  5876. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  5877. const disabled = document.getElementById('eoip-modal-disabled').checked;
  5878. try {
  5879. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  5880. method: 'POST',
  5881. headers: { 'Content-Type': 'application/json' },
  5882. body: JSON.stringify({
  5883. id,
  5884. name,
  5885. tunnel_id: tunnelId,
  5886. remote_address: remote,
  5887. ip_address: ipAddress,
  5888. local_address: local,
  5889. mac_address: mac,
  5890. mtu,
  5891. clamp_mss: clampMss,
  5892. comment,
  5893. disabled
  5894. })
  5895. });
  5896. if (res.ok) {
  5897. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  5898. closeEoIPModal();
  5899. loadEoIP(false);
  5900. fetchData(false);
  5901. } else {
  5902. const err = await res.json();
  5903. showToast('Error', err.message, 'error');
  5904. }
  5905. } catch (err) {
  5906. showToast('Error', err.message, 'error');
  5907. }
  5908. }
  5909. async function toggleEoIPState(id, disabled) {
  5910. try {
  5911. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  5912. method: 'POST',
  5913. headers: { 'Content-Type': 'application/json' },
  5914. body: JSON.stringify({ disabled })
  5915. });
  5916. if (res.ok) {
  5917. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  5918. loadEoIP(false);
  5919. fetchData(false);
  5920. }
  5921. } catch (err) {
  5922. showToast('Error', err.message, 'error');
  5923. }
  5924. }
  5925. async function deleteEoIP(id) {
  5926. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  5927. try {
  5928. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5929. if (res.ok) {
  5930. showToast('Deleted', 'EoIP tunnel removed', 'success');
  5931. loadEoIP(false);
  5932. fetchData(false);
  5933. }
  5934. } catch (err) {
  5935. showToast('Error', err.message, 'error');
  5936. }
  5937. }
  5938. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  5939. async function loadAeroTUN(populate = true) {
  5940. try {
  5941. const [tunnelsRes, statsRes] = await Promise.all([
  5942. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  5943. fetch(`${API_BASE}/vpn/aerotun/stats`)
  5944. ]);
  5945. if (tunnelsRes.ok) {
  5946. const data = await tunnelsRes.json();
  5947. state.aerotunTunnels = Array.isArray(data) ? data : [];
  5948. }
  5949. if (statsRes.ok) {
  5950. state.aerotunStats = await statsRes.json();
  5951. }
  5952. const countBadge = document.getElementById('aerotun-count-badge');
  5953. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  5954. const sideBadge = document.getElementById('badge-aerotun-count');
  5955. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  5956. renderAeroTUN();
  5957. } catch (err) {
  5958. console.error('Failed to load AeroTUN:', err);
  5959. }
  5960. }
  5961. function renderAeroTUN() {
  5962. const tbody = document.getElementById('aerotun-table-body');
  5963. const empty = document.getElementById('aerotun-empty');
  5964. // Update summary cards
  5965. const stats = state.aerotunStats || {};
  5966. const tunnels = state.aerotunTunnels || [];
  5967. const statActive = document.getElementById('aerotun-stat-active');
  5968. if (statActive) {
  5969. const activeCount = tunnels.filter(t => t.running).length;
  5970. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  5971. }
  5972. const statSaved = document.getElementById('aerotun-stat-saved');
  5973. if (statSaved) {
  5974. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  5975. }
  5976. const statRatio = document.getElementById('aerotun-stat-ratio');
  5977. if (statRatio) {
  5978. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  5979. }
  5980. const statTraffic = document.getElementById('aerotun-stat-traffic');
  5981. if (statTraffic) {
  5982. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  5983. }
  5984. if (!tbody) return;
  5985. tbody.innerHTML = '';
  5986. if (tunnels.length === 0) {
  5987. empty?.classList.remove('hidden');
  5988. return;
  5989. }
  5990. empty?.classList.add('hidden');
  5991. tunnels.forEach(t => {
  5992. const tr = document.createElement('tr');
  5993. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  5994. const modeBadge = t.mode === 'server'
  5995. ? `<span class="px-2 py-0.5 rounded text-[10px] font-mono bg-sky-500/20 text-sky-300 border border-sky-500/30 font-semibold uppercase">Server</span>`
  5996. : `<span class="px-2 py-0.5 rounded text-[10px] font-mono bg-indigo-500/20 text-indigo-300 border border-indigo-500/30 font-semibold uppercase">Client</span>`;
  5997. const endpointInfo = t.mode === 'server'
  5998. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  5999. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  6000. const compBadge = t.compression
  6001. ? `<span class="px-1.5 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-semibold" title="Adaptive LZ4 active">${t.compression_ratio || 'LZ4'}</span>`
  6002. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  6003. const activePeer = t.active_peer_endpoint
  6004. ? `<span class="text-emerald-400 font-mono text-[11px]" title="Last seen: ${t.last_handshake || 'just now'}">● ${escapeHtml(t.active_peer_endpoint)}</span>`
  6005. : `<span class="text-slate-500 text-[11px]">${t.mode === 'server' ? 'Waiting for peer...' : 'Connecting...'}</span>`;
  6006. const rawRx = formatBytes(t.rx_bytes || 0);
  6007. const rawTx = formatBytes(t.tx_bytes || 0);
  6008. const wireRx = formatBytes(t.wire_bytes_in || 0);
  6009. const wireTx = formatBytes(t.wire_bytes_out || 0);
  6010. tr.innerHTML = `
  6011. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6012. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  6013. <span>${escapeHtml(t.name)}</span>
  6014. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  6015. </td>
  6016. <td class="py-2.5 px-3">${modeBadge}</td>
  6017. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  6018. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  6019. <td class="py-2.5 px-3">${compBadge}</td>
  6020. <td class="py-2.5 px-3">${activePeer}</td>
  6021. <td class="py-2.5 px-3 font-mono text-[11px]">
  6022. <span class="text-emerald-400">↓ ${rawRx}</span>
  6023. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  6024. </td>
  6025. <td class="py-2.5 px-3 font-mono text-[11px]">
  6026. <span class="text-slate-400">↓ ${wireRx}</span>
  6027. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  6028. </td>
  6029. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  6030. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6031. ${t.running
  6032. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  6033. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  6034. }
  6035. <button onclick="toggleAeroTUNState('${t.id}', ${!t.disabled})" class="text-xs ${t.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${t.disabled ? 'Enable' : 'Disable'}</button>
  6036. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6037. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6038. </td>
  6039. `;
  6040. tbody.appendChild(tr);
  6041. });
  6042. }
  6043. function onAeroTUNModeChange() {
  6044. const mode = document.getElementById('aerotun-modal-mode').value;
  6045. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  6046. const portInput = document.getElementById('aerotun-modal-port');
  6047. if (mode === 'server') {
  6048. if (!portInput.value) portInput.value = '51830';
  6049. endpointInput.placeholder = 'Optional / learned roaming peer';
  6050. } else {
  6051. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  6052. if (!portInput.value) portInput.value = '';
  6053. }
  6054. }
  6055. async function generateAeroTUNKey() {
  6056. try {
  6057. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  6058. if (res.ok) {
  6059. const data = await res.json();
  6060. document.getElementById('aerotun-modal-psk').value = data.key;
  6061. showToast('Key Generated', 'Cryptographic 256-bit PSK generated', 'success');
  6062. }
  6063. } catch (err) {
  6064. const arr = new Uint8Array(32);
  6065. crypto.getRandomValues(arr);
  6066. const hex = Array.from(arr).map(b => b.toString(16).padStart(2, '0')).join('');
  6067. document.getElementById('aerotun-modal-psk').value = hex;
  6068. }
  6069. }
  6070. function openAddAeroTUNModal() {
  6071. const tunnels = state.aerotunTunnels || [];
  6072. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  6073. document.getElementById('aerotun-modal-id').value = '';
  6074. document.getElementById('aerotun-modal-name').value = `aerotun${tunnels.length}`;
  6075. document.getElementById('aerotun-modal-mode').value = 'server';
  6076. document.getElementById('aerotun-modal-port').value = 51830 + tunnels.length;
  6077. document.getElementById('aerotun-modal-endpoint').value = '';
  6078. document.getElementById('aerotun-modal-local').value = `10.99.${tunnels.length}.1/24`;
  6079. document.getElementById('aerotun-modal-peer').value = `10.99.${tunnels.length}.2/24`;
  6080. document.getElementById('aerotun-modal-psk').value = '';
  6081. document.getElementById('aerotun-modal-mtu').value = '1420';
  6082. document.getElementById('aerotun-modal-comment').value = '';
  6083. document.getElementById('aerotun-modal-compression').checked = true;
  6084. document.getElementById('aerotun-modal-defroute').checked = false;
  6085. document.getElementById('aerotun-modal-disabled').checked = false;
  6086. generateAeroTUNKey();
  6087. onAeroTUNModeChange();
  6088. document.getElementById('aerotun-modal').classList.remove('hidden');
  6089. }
  6090. function openEditAeroTUNModal(id) {
  6091. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  6092. if (!t) return;
  6093. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  6094. document.getElementById('aerotun-modal-id').value = t.id;
  6095. document.getElementById('aerotun-modal-name').value = t.name;
  6096. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  6097. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  6098. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  6099. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  6100. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  6101. document.getElementById('aerotun-modal-psk').value = t.psk || '';
  6102. document.getElementById('aerotun-modal-mtu').value = t.mtu || 1420;
  6103. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  6104. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  6105. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  6106. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  6107. onAeroTUNModeChange();
  6108. document.getElementById('aerotun-modal').classList.remove('hidden');
  6109. }
  6110. function closeAeroTUNModal() {
  6111. document.getElementById('aerotun-modal').classList.add('hidden');
  6112. }
  6113. async function submitSaveAeroTUN(e) {
  6114. e.preventDefault();
  6115. const id = document.getElementById('aerotun-modal-id').value;
  6116. const name = document.getElementById('aerotun-modal-name').value.trim();
  6117. const mode = document.getElementById('aerotun-modal-mode').value;
  6118. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  6119. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  6120. const local = document.getElementById('aerotun-modal-local').value.trim();
  6121. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  6122. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  6123. const mtu = parseInt(document.getElementById('aerotun-modal-mtu').value) || 1420;
  6124. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  6125. const compression = document.getElementById('aerotun-modal-compression').checked;
  6126. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  6127. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  6128. if (mode === 'client' && !endpoint) {
  6129. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  6130. return;
  6131. }
  6132. if (!psk) {
  6133. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  6134. return;
  6135. }
  6136. try {
  6137. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  6138. method: 'POST',
  6139. headers: { 'Content-Type': 'application/json' },
  6140. body: JSON.stringify({
  6141. id,
  6142. name,
  6143. mode,
  6144. listen_port: port,
  6145. remote_endpoint: endpoint,
  6146. local_address: local,
  6147. peer_address: peer,
  6148. psk,
  6149. mtu,
  6150. compression,
  6151. default_route: defaultRoute,
  6152. comment,
  6153. disabled
  6154. })
  6155. });
  6156. if (res.ok) {
  6157. showToast('AeroTUN Saved', `Tunnel ${name} configured successfully`, 'success');
  6158. closeAeroTUNModal();
  6159. loadAeroTUN(false);
  6160. fetchData(false);
  6161. } else {
  6162. const err = await res.text();
  6163. showToast('Error Saving Tunnel', err, 'error');
  6164. }
  6165. } catch (err) {
  6166. showToast('Network Error', err.message, 'error');
  6167. }
  6168. }
  6169. async function startAeroTUNTunnel(id) {
  6170. try {
  6171. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  6172. if (res.ok) {
  6173. showToast('AeroTUN Started', 'Tunnel interface is active', 'success');
  6174. loadAeroTUN(false);
  6175. fetchData(false);
  6176. } else {
  6177. const err = await res.text();
  6178. showToast('Failed to Start', err, 'error');
  6179. }
  6180. } catch (err) {
  6181. showToast('Error', err.message, 'error');
  6182. }
  6183. }
  6184. async function stopAeroTUNTunnel(id) {
  6185. try {
  6186. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  6187. if (res.ok) {
  6188. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  6189. loadAeroTUN(false);
  6190. fetchData(false);
  6191. } else {
  6192. const err = await res.text();
  6193. showToast('Failed to Stop', err, 'error');
  6194. }
  6195. } catch (err) {
  6196. showToast('Error', err.message, 'error');
  6197. }
  6198. }
  6199. async function toggleAeroTUNState(id, disabled) {
  6200. try {
  6201. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  6202. method: 'POST',
  6203. headers: { 'Content-Type': 'application/json' },
  6204. body: JSON.stringify({ disabled })
  6205. });
  6206. if (res.ok) {
  6207. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  6208. loadAeroTUN(false);
  6209. fetchData(false);
  6210. }
  6211. } catch (err) {
  6212. showToast('Error', err.message, 'error');
  6213. }
  6214. }
  6215. async function deleteAeroTUN(id) {
  6216. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  6217. try {
  6218. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6219. if (res.ok) {
  6220. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  6221. loadAeroTUN(false);
  6222. fetchData(false);
  6223. }
  6224. } catch (err) {
  6225. showToast('Error', err.message, 'error');
  6226. }
  6227. }
  6228. // ======================== PPP Central Hub & Servers ========================
  6229. function switchPPPSubTab(tab) {
  6230. state.pppSubTab = tab;
  6231. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  6232. tabs.forEach(t => {
  6233. const panel = document.getElementById(`ppp-subtab-${t}`);
  6234. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  6235. if (panel) {
  6236. if (t === tab) panel.classList.remove('hidden');
  6237. else panel.classList.add('hidden');
  6238. }
  6239. if (btn) {
  6240. if (t === tab) {
  6241. 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';
  6242. } else {
  6243. 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';
  6244. }
  6245. }
  6246. });
  6247. const addBtn = document.getElementById('ppp-primary-add-btn');
  6248. if (addBtn) {
  6249. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  6250. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  6251. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  6252. else addBtn.innerHTML = '<span>Save Config</span>';
  6253. }
  6254. if (tab === 'active') loadPPPSessions();
  6255. }
  6256. function openCurrentPPPModal() {
  6257. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  6258. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  6259. else if (state.pppSubTab === 'active') loadPPPSessions();
  6260. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  6261. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  6262. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  6263. }
  6264. async function loadPPP(populateDropdowns = true) {
  6265. await Promise.all([
  6266. loadPPPSecrets(),
  6267. loadPPPProfiles(),
  6268. loadPPPServers(),
  6269. loadPPPSessions()
  6270. ]);
  6271. }
  6272. async function loadPPPSecrets() {
  6273. try {
  6274. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  6275. const data = await res.json();
  6276. state.pppSecrets = Array.isArray(data) ? data : [];
  6277. const b = document.getElementById('ppp-badge-secrets');
  6278. if (b) b.innerText = state.pppSecrets.length;
  6279. const b2 = document.getElementById('secrets-count-badge');
  6280. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  6281. renderPPPSecrets();
  6282. } catch (err) {
  6283. console.error('Failed to load PPP secrets:', err);
  6284. }
  6285. }
  6286. function renderPPPSecrets() {
  6287. const tbody = document.getElementById('secrets-table-body');
  6288. const empty = document.getElementById('secrets-empty');
  6289. if (!tbody) return;
  6290. tbody.innerHTML = '';
  6291. const secrets = state.pppSecrets || [];
  6292. if (secrets.length === 0) {
  6293. empty?.classList.remove('hidden');
  6294. return;
  6295. }
  6296. empty?.classList.add('hidden');
  6297. secrets.forEach(s => {
  6298. const tr = document.createElement('tr');
  6299. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  6300. tr.innerHTML = `
  6301. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  6302. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  6303. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  6304. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  6305. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  6306. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  6307. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  6308. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6309. <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>
  6310. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6311. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6312. </td>
  6313. `;
  6314. tbody.appendChild(tr);
  6315. });
  6316. }
  6317. async function loadPPPProfiles() {
  6318. try {
  6319. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  6320. const data = await res.json();
  6321. state.pppProfiles = Array.isArray(data) ? data : [];
  6322. const b = document.getElementById('ppp-badge-profiles');
  6323. if (b) b.innerText = state.pppProfiles.length;
  6324. const b2 = document.getElementById('profiles-count-badge');
  6325. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  6326. // Populate profile selects across modals
  6327. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  6328. selects.forEach(sid => {
  6329. const el = document.getElementById(sid);
  6330. if (!el) return;
  6331. const cur = el.value;
  6332. el.innerHTML = '';
  6333. state.pppProfiles.forEach(p => {
  6334. const opt = document.createElement('option');
  6335. opt.value = p.name;
  6336. opt.innerText = `${p.name} (${p.remote_address})`;
  6337. if (p.name === cur) opt.selected = true;
  6338. el.appendChild(opt);
  6339. });
  6340. });
  6341. renderPPPProfiles();
  6342. } catch (err) {
  6343. console.error('Failed to load PPP profiles:', err);
  6344. }
  6345. }
  6346. function renderPPPProfiles() {
  6347. const tbody = document.getElementById('profiles-table-body');
  6348. if (!tbody) return;
  6349. tbody.innerHTML = '';
  6350. (state.pppProfiles || []).forEach(p => {
  6351. const isDefault = p.name.startsWith('default');
  6352. const tr = document.createElement('tr');
  6353. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6354. tr.innerHTML = `
  6355. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  6356. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  6357. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  6358. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  6359. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  6360. <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>
  6361. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  6362. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  6363. ${!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>`}
  6364. </td>
  6365. `;
  6366. tbody.appendChild(tr);
  6367. });
  6368. }
  6369. async function loadPPPServers() {
  6370. try {
  6371. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  6372. fetch(`${API_BASE}/vpn/servers/pppoe`),
  6373. fetch(`${API_BASE}/vpn/servers/pptp`),
  6374. fetch(`${API_BASE}/vpn/servers/l2tp`),
  6375. fetch(`${API_BASE}/vpn/servers/ipsec`)
  6376. ]);
  6377. if (pppoeRes.ok) {
  6378. state.pppoeServer = await pppoeRes.json();
  6379. const s = state.pppoeServer;
  6380. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  6381. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  6382. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  6383. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  6384. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  6385. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  6386. const pill = document.getElementById('pppoe-server-status-pill');
  6387. if (pill) {
  6388. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6389. 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';
  6390. }
  6391. setDotBadge('ppp-badge-pppoe-state', s.running);
  6392. }
  6393. if (pptpRes.ok) {
  6394. state.pptpServer = await pptpRes.json();
  6395. const s = state.pptpServer;
  6396. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  6397. document.getElementById('pptp-server-port').value = s.port || 1723;
  6398. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  6399. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  6400. const pill = document.getElementById('pptp-server-status-pill');
  6401. if (pill) {
  6402. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6403. 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';
  6404. }
  6405. setDotBadge('ppp-badge-pptp-state', s.running);
  6406. }
  6407. if (l2tpRes.ok) {
  6408. state.l2tpServer = await l2tpRes.json();
  6409. const s = state.l2tpServer;
  6410. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  6411. document.getElementById('l2tp-server-port').value = s.port || 1701;
  6412. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  6413. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  6414. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  6415. const pill = document.getElementById('l2tp-server-status-pill');
  6416. if (pill) {
  6417. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6418. 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';
  6419. }
  6420. setDotBadge('ppp-badge-l2tp-state', s.running);
  6421. }
  6422. if (ipsecRes.ok) {
  6423. state.ipsecServer = await ipsecRes.json();
  6424. const s = state.ipsecServer;
  6425. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  6426. if (modalEn) modalEn.checked = !!s.enabled;
  6427. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  6428. if (modalPsk) modalPsk.value = s.preshared_key || '';
  6429. const modalPool = document.getElementById('modal-ipsec-server-pool');
  6430. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  6431. const modalDns = document.getElementById('modal-ipsec-server-dns');
  6432. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  6433. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  6434. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  6435. const pill = document.getElementById('modal-ipsec-server-status');
  6436. if (pill) {
  6437. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  6438. 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';
  6439. }
  6440. }
  6441. } catch (err) {
  6442. console.error('Failed to load VPN servers:', err);
  6443. }
  6444. }
  6445. async function loadPPPSessions() {
  6446. try {
  6447. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  6448. const data = await res.json();
  6449. state.pppActiveSessions = Array.isArray(data) ? data : [];
  6450. const b = document.getElementById('ppp-badge-active');
  6451. if (b) b.innerText = state.pppActiveSessions.length;
  6452. const sideB = document.getElementById('badge-ppp-sessions');
  6453. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  6454. renderPPPSessions();
  6455. } catch (err) {
  6456. console.error('Failed to load active PPP sessions:', err);
  6457. }
  6458. }
  6459. function renderPPPSessions() {
  6460. const tbody = document.getElementById('active-ppp-table-body');
  6461. const empty = document.getElementById('active-ppp-empty');
  6462. if (!tbody) return;
  6463. tbody.innerHTML = '';
  6464. const list = state.pppActiveSessions || [];
  6465. if (list.length === 0) {
  6466. empty?.classList.remove('hidden');
  6467. return;
  6468. }
  6469. empty?.classList.add('hidden');
  6470. list.forEach(s => {
  6471. const tr = document.createElement('tr');
  6472. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6473. tr.innerHTML = `
  6474. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  6475. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  6476. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  6477. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  6478. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  6479. <td class="py-2.5 px-3 text-[11px]">
  6480. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  6481. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  6482. </td>
  6483. <td class="py-2.5 px-3 text-right font-sans">
  6484. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  6485. </td>
  6486. `;
  6487. tbody.appendChild(tr);
  6488. });
  6489. }
  6490. async function disconnectPPPSession(iface) {
  6491. if (!confirm(`Disconnect session ${iface}?`)) return;
  6492. try {
  6493. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  6494. if (res.ok) {
  6495. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  6496. loadPPPSessions();
  6497. }
  6498. } catch (err) {
  6499. showToast('Error', err.message, 'error');
  6500. }
  6501. }
  6502. // PPP Secret Modal handlers
  6503. function openAddPPPSecretModal() {
  6504. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  6505. document.getElementById('secret-modal-id').value = '';
  6506. document.getElementById('secret-modal-name').value = '';
  6507. document.getElementById('secret-modal-password').value = '';
  6508. document.getElementById('secret-modal-service').value = 'any';
  6509. document.getElementById('secret-modal-profile').value = 'default';
  6510. document.getElementById('secret-modal-local').value = '';
  6511. document.getElementById('secret-modal-remote').value = '';
  6512. document.getElementById('secret-modal-comment').value = '';
  6513. document.getElementById('secret-modal-disabled').checked = false;
  6514. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  6515. }
  6516. function openEditPPPSecretModal(id) {
  6517. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  6518. if (!s) return;
  6519. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  6520. document.getElementById('secret-modal-id').value = s.id;
  6521. document.getElementById('secret-modal-name').value = s.name;
  6522. document.getElementById('secret-modal-password').value = s.password;
  6523. document.getElementById('secret-modal-service').value = s.service || 'any';
  6524. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  6525. document.getElementById('secret-modal-local').value = s.local_address || '';
  6526. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  6527. document.getElementById('secret-modal-comment').value = s.comment || '';
  6528. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  6529. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  6530. }
  6531. function closePPPSecretModal() {
  6532. document.getElementById('ppp-secret-modal').classList.add('hidden');
  6533. }
  6534. async function submitSavePPPSecret(e) {
  6535. e.preventDefault();
  6536. const id = document.getElementById('secret-modal-id').value;
  6537. const name = document.getElementById('secret-modal-name').value.trim();
  6538. const password = document.getElementById('secret-modal-password').value.trim();
  6539. const service = document.getElementById('secret-modal-service').value;
  6540. const profile = document.getElementById('secret-modal-profile').value;
  6541. const local = document.getElementById('secret-modal-local').value.trim();
  6542. const remote = document.getElementById('secret-modal-remote').value.trim();
  6543. const comment = document.getElementById('secret-modal-comment').value.trim();
  6544. const disabled = document.getElementById('secret-modal-disabled').checked;
  6545. try {
  6546. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  6547. method: 'POST',
  6548. headers: { 'Content-Type': 'application/json' },
  6549. body: JSON.stringify({
  6550. id,
  6551. name,
  6552. password,
  6553. service,
  6554. profile,
  6555. local_address: local,
  6556. remote_address: remote,
  6557. comment,
  6558. disabled
  6559. })
  6560. });
  6561. if (res.ok) {
  6562. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  6563. closePPPSecretModal();
  6564. loadPPPSecrets();
  6565. } else {
  6566. const err = await res.json();
  6567. showToast('Error', err.message, 'error');
  6568. }
  6569. } catch (err) {
  6570. showToast('Error', err.message, 'error');
  6571. }
  6572. }
  6573. async function togglePPPSecretState(id, disabled) {
  6574. try {
  6575. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  6576. method: 'POST',
  6577. headers: { 'Content-Type': 'application/json' },
  6578. body: JSON.stringify({ disabled })
  6579. });
  6580. if (res.ok) {
  6581. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  6582. loadPPPSecrets();
  6583. }
  6584. } catch (err) {
  6585. showToast('Error', err.message, 'error');
  6586. }
  6587. }
  6588. async function deletePPPSecret(id) {
  6589. if (!confirm('Are you sure you want to delete this secret account?')) return;
  6590. try {
  6591. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6592. if (res.ok) {
  6593. showToast('Deleted', 'Secret account removed', 'success');
  6594. loadPPPSecrets();
  6595. }
  6596. } catch (err) {
  6597. showToast('Error', err.message, 'error');
  6598. }
  6599. }
  6600. // PPP Profile Modal handlers
  6601. function openAddPPPProfileModal() {
  6602. document.getElementById('profile-modal-name').value = '';
  6603. document.getElementById('profile-modal-local').value = '10.10.10.1';
  6604. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  6605. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  6606. document.getElementById('profile-modal-encryption').value = 'required';
  6607. document.getElementById('profile-modal-onlyone').checked = true;
  6608. document.getElementById('profile-modal-comment').value = '';
  6609. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  6610. }
  6611. function closePPPProfileModal() {
  6612. document.getElementById('ppp-profile-modal').classList.add('hidden');
  6613. }
  6614. async function submitSavePPPProfile(e) {
  6615. e.preventDefault();
  6616. const name = document.getElementById('profile-modal-name').value.trim();
  6617. const local = document.getElementById('profile-modal-local').value.trim();
  6618. const remote = document.getElementById('profile-modal-remote').value.trim();
  6619. const dns = document.getElementById('profile-modal-dns').value.trim();
  6620. const enc = document.getElementById('profile-modal-encryption').value;
  6621. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  6622. const comment = document.getElementById('profile-modal-comment').value.trim();
  6623. try {
  6624. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  6625. method: 'POST',
  6626. headers: { 'Content-Type': 'application/json' },
  6627. body: JSON.stringify({
  6628. id: name,
  6629. name,
  6630. local_address: local,
  6631. remote_address: remote,
  6632. dns_servers: dns,
  6633. use_encryption: enc,
  6634. only_one: onlyone,
  6635. comment
  6636. })
  6637. });
  6638. if (res.ok) {
  6639. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  6640. closePPPProfileModal();
  6641. loadPPPProfiles();
  6642. } else {
  6643. const err = await res.json();
  6644. showToast('Error', err.message, 'error');
  6645. }
  6646. } catch (err) {
  6647. showToast('Error', err.message, 'error');
  6648. }
  6649. }
  6650. async function deletePPPProfile(name) {
  6651. if (!confirm(`Delete PPP profile ${name}?`)) return;
  6652. try {
  6653. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  6654. if (res.ok) {
  6655. showToast('Deleted', 'Profile removed', 'success');
  6656. loadPPPProfiles();
  6657. } else {
  6658. const err = await res.json();
  6659. showToast('Error', err.message, 'error');
  6660. }
  6661. } catch (err) {
  6662. showToast('Error', err.message, 'error');
  6663. }
  6664. }
  6665. // Server Config submissions
  6666. async function savePPPoEServerConfig(e) {
  6667. e.preventDefault();
  6668. const enabled = document.getElementById('pppoe-server-enabled').checked;
  6669. const name = document.getElementById('pppoe-server-name').value.trim();
  6670. const iface = document.getElementById('pppoe-server-iface').value;
  6671. const profile = document.getElementById('pppoe-server-profile').value;
  6672. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  6673. const onesession = document.getElementById('pppoe-server-onesession').checked;
  6674. try {
  6675. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  6676. method: 'POST',
  6677. headers: { 'Content-Type': 'application/json' },
  6678. body: JSON.stringify({
  6679. enabled,
  6680. service_name: name,
  6681. interface: iface,
  6682. default_profile: profile,
  6683. max_mtu: mtu,
  6684. max_mru: mtu,
  6685. one_session_per_host: onesession
  6686. })
  6687. });
  6688. if (res.ok) {
  6689. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  6690. loadPPPServers();
  6691. fetchData(false);
  6692. } else {
  6693. const err = await res.json();
  6694. showToast('Error', err.message, 'error');
  6695. }
  6696. } catch (err) {
  6697. showToast('Error', err.message, 'error');
  6698. }
  6699. }
  6700. async function savePPTPServerConfig(e) {
  6701. e.preventDefault();
  6702. const enabled = document.getElementById('pptp-server-enabled').checked;
  6703. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  6704. const profile = document.getElementById('pptp-server-profile').value;
  6705. const mppe = document.getElementById('pptp-server-mppe').checked;
  6706. try {
  6707. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  6708. method: 'POST',
  6709. headers: { 'Content-Type': 'application/json' },
  6710. body: JSON.stringify({
  6711. enabled,
  6712. port,
  6713. default_profile: profile,
  6714. require_mppe: mppe
  6715. })
  6716. });
  6717. if (res.ok) {
  6718. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  6719. loadPPPServers();
  6720. fetchData(false);
  6721. } else {
  6722. const err = await res.json();
  6723. showToast('Error', err.message, 'error');
  6724. }
  6725. } catch (err) {
  6726. showToast('Error', err.message, 'error');
  6727. }
  6728. }
  6729. async function saveL2TPServerConfig(e) {
  6730. e.preventDefault();
  6731. const enabled = document.getElementById('l2tp-server-enabled').checked;
  6732. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  6733. const profile = document.getElementById('l2tp-server-profile').value;
  6734. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  6735. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  6736. try {
  6737. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  6738. method: 'POST',
  6739. headers: { 'Content-Type': 'application/json' },
  6740. body: JSON.stringify({
  6741. enabled,
  6742. port,
  6743. default_profile: profile,
  6744. use_ipsec: useipsec,
  6745. ipsec_secret: psk
  6746. })
  6747. });
  6748. if (res.ok) {
  6749. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  6750. loadPPPServers();
  6751. fetchData(false);
  6752. } else {
  6753. const err = await res.json();
  6754. showToast('Error', err.message, 'error');
  6755. }
  6756. } catch (err) {
  6757. showToast('Error', err.message, 'error');
  6758. }
  6759. }
  6760. // IPSec Server Modal
  6761. function openIPSecServerModal() {
  6762. loadPPPServers();
  6763. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  6764. }
  6765. function closeIPSecServerModal() {
  6766. document.getElementById('ipsec-server-modal').classList.add('hidden');
  6767. }
  6768. async function submitSaveIPSecServer(e) {
  6769. e.preventDefault();
  6770. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  6771. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  6772. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  6773. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  6774. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  6775. try {
  6776. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  6777. method: 'POST',
  6778. headers: { 'Content-Type': 'application/json' },
  6779. body: JSON.stringify({
  6780. enabled,
  6781. preshared_key: psk,
  6782. pool_address: pool,
  6783. dns_servers: dns,
  6784. local_subnet: subnet
  6785. })
  6786. });
  6787. if (res.ok) {
  6788. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  6789. closeIPSecServerModal();
  6790. loadPPPServers();
  6791. fetchData(false);
  6792. } else {
  6793. const err = await res.json();
  6794. showToast('Error', err.message, 'error');
  6795. }
  6796. } catch (err) {
  6797. showToast('Error', err.message, 'error');
  6798. }
  6799. }
  6800. // WireGuard Client Config Viewer
  6801. let currentWGClientConf = '';
  6802. async function openWGClientConfModal(iface, clientIP) {
  6803. try {
  6804. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  6805. method: 'POST',
  6806. headers: { 'Content-Type': 'application/json' },
  6807. body: JSON.stringify({
  6808. interface: iface,
  6809. address: clientIP || '10.10.0.2/32',
  6810. dns: '1.1.1.1, 8.8.8.8'
  6811. })
  6812. });
  6813. if (res.ok) {
  6814. const data = await res.json();
  6815. currentWGClientConf = data.config;
  6816. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  6817. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  6818. } else {
  6819. const err = await res.json();
  6820. showToast('Error', err.message, 'error');
  6821. }
  6822. } catch (err) {
  6823. showToast('Error', err.message, 'error');
  6824. }
  6825. }
  6826. function closeWGClientConfModal() {
  6827. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  6828. }
  6829. function copyWGClientConf() {
  6830. if (!currentWGClientConf) return;
  6831. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  6832. }
  6833. function downloadWGClientConf() {
  6834. if (!currentWGClientConf) return;
  6835. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  6836. const a = document.createElement('a');
  6837. a.href = URL.createObjectURL(blob);
  6838. a.download = 'wireguard-client.conf';
  6839. document.body.appendChild(a);
  6840. a.click();
  6841. document.body.removeChild(a);
  6842. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  6843. }
  6844. // =========================================================================
  6845. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  6846. // =========================================================================
  6847. state.activeDynSubTab = 'bgp-peers';
  6848. state.activeBgpSubTab = 'bgp-peers';
  6849. state.activeOspfTab = 'instances';
  6850. state.bgpInstance = null;
  6851. state.bgpPeers = [];
  6852. state.bgpNets = [];
  6853. state.bgpRoutes = [];
  6854. state.ospfInstance = null;
  6855. state.ospfInstances = [];
  6856. state.ospfAreas = [];
  6857. state.ospfAreaRanges = [];
  6858. state.ospfTemplates = [];
  6859. state.ospfLiveInterfaces = [];
  6860. state.ospfStaticNbrs = [];
  6861. state.ospfNeighbors = [];
  6862. state.ospfLSA = [];
  6863. state.ospfRoutes = [];
  6864. state.selectedOspfRow = {
  6865. instances: null,
  6866. areas: null,
  6867. 'area-ranges': null,
  6868. templates: null,
  6869. interfaces: null,
  6870. 'static-nbrs': null,
  6871. neighbors: null,
  6872. lsa: null,
  6873. };
  6874. state.ospfSort = {
  6875. instances: { col: 'name', asc: true },
  6876. areas: { col: 'name', asc: true },
  6877. ranges: { col: 'area', asc: true },
  6878. templates: { col: 'interfaces', asc: true },
  6879. live_ifaces: { col: 'interface', asc: true },
  6880. snbrs: { col: 'address', asc: true },
  6881. neighbors: { col: 'address', asc: true },
  6882. lsa: { col: 'instance', asc: true },
  6883. };
  6884. function switchBgpSubTab(subTab) {
  6885. state.activeBgpSubTab = subTab;
  6886. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  6887. tabs.forEach(t => {
  6888. const el = document.getElementById(`dyn-subtab-${t}`);
  6889. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  6890. if (el) el.classList.toggle('hidden', t !== subTab);
  6891. if (btn) {
  6892. if (t === subTab) {
  6893. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-purple-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  6894. } else {
  6895. 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';
  6896. }
  6897. }
  6898. });
  6899. }
  6900. function switchOspfTab(tabName) {
  6901. state.activeOspfTab = tabName;
  6902. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  6903. tabs.forEach(t => {
  6904. const pane = document.getElementById(`ospf-pane-${t}`);
  6905. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  6906. if (pane) pane.classList.toggle('hidden', t !== tabName);
  6907. if (btn) {
  6908. if (t === tabName) {
  6909. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-sky-500 text-white transition flex items-center gap-1.5 whitespace-nowrap';
  6910. } else {
  6911. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-transparent text-slate-400 hover:text-white transition flex items-center gap-1.5 whitespace-nowrap';
  6912. }
  6913. }
  6914. });
  6915. }
  6916. function switchOspfSubTab(tab) {
  6917. // Legacy alias
  6918. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  6919. else if (tab === 'ospf-areas') switchOspfTab('areas');
  6920. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  6921. else switchOspfTab('instances');
  6922. }
  6923. function switchDynSubTab(subTab) {
  6924. if (subTab.startsWith('bgp')) {
  6925. if (state.activeTab !== 'bgp') navigate('bgp');
  6926. switchBgpSubTab(subTab);
  6927. } else if (subTab.startsWith('ospf')) {
  6928. if (state.activeTab !== 'ospf') navigate('ospf');
  6929. switchOspfTab('instances');
  6930. }
  6931. }
  6932. async function loadDynamicRouting(showToastMsg = false) {
  6933. try {
  6934. const fetchSafeJson = async (url) => {
  6935. try {
  6936. const r = await fetch(url);
  6937. return r.ok ? await r.json() : null;
  6938. } catch (e) {
  6939. return null;
  6940. }
  6941. };
  6942. const [
  6943. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  6944. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  6945. selectRules, commLists, asLists
  6946. ] = await Promise.all([
  6947. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  6948. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  6949. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  6950. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  6951. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  6952. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  6953. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  6954. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  6955. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  6956. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  6957. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  6958. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  6959. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  6960. fetchSafeJson(`${API_BASE}/routing/filters`),
  6961. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  6962. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  6963. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  6964. ]);
  6965. if (sum) state.dynSummary = sum;
  6966. if (bgpInst) state.bgpInstance = bgpInst;
  6967. if (bgpPeers) state.bgpPeers = bgpPeers;
  6968. if (bgpNets) state.bgpNets = bgpNets;
  6969. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  6970. if (ospfInsts) state.ospfInstances = ospfInsts;
  6971. if (ospfAreas) state.ospfAreas = ospfAreas;
  6972. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  6973. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  6974. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  6975. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  6976. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  6977. if (ospfLsa) state.ospfLSA = ospfLsa;
  6978. if (filters) state.routingFilters = filters;
  6979. if (selectRules) state.routingSelectRules = selectRules;
  6980. if (commLists) state.routingCommunityLists = commLists;
  6981. if (asLists) state.routingASLists = asLists;
  6982. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  6983. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  6984. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  6985. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  6986. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  6987. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  6988. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  6989. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  6990. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  6991. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  6992. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  6993. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  6994. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  6995. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  6996. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  6997. } catch (err) {
  6998. console.error('Failed to load dynamic routing:', err);
  6999. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  7000. }
  7001. }
  7002. async function loadOspfAll() {
  7003. await loadDynamicRouting(true);
  7004. }
  7005. function renderBgpStatusPill() {
  7006. const pill = document.getElementById('bgp-live-status-pill');
  7007. if (!pill) return;
  7008. const inst = state.bgpInstance;
  7009. if (!inst || !inst.enabled) {
  7010. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  7011. pill.innerText = 'BGP DISABLED';
  7012. } else if (inst.running) {
  7013. 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';
  7014. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  7015. } else {
  7016. 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';
  7017. pill.innerText = 'BGP STARTING...';
  7018. }
  7019. }
  7020. function renderBgpPeers() {
  7021. const tbody = document.getElementById('bgp-peers-table-body');
  7022. if (!tbody) return;
  7023. const empty = document.getElementById('bgp-peers-empty');
  7024. const countBadge = document.getElementById('bgp-peers-count-badge');
  7025. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  7026. const peers = state.bgpPeers || [];
  7027. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  7028. if (navBadge) navBadge.innerText = peers.length;
  7029. if (peers.length === 0) {
  7030. tbody.innerHTML = '';
  7031. if (empty) empty.classList.remove('hidden');
  7032. return;
  7033. }
  7034. if (empty) empty.classList.add('hidden');
  7035. tbody.innerHTML = peers.map(p => {
  7036. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  7037. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  7038. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  7039. let stateBadge = '';
  7040. if (p.disabled) {
  7041. 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>';
  7042. } else if (p.state === 'Established') {
  7043. 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>';
  7044. } else if (p.state === 'Connect' || p.state === 'Active') {
  7045. 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>`;
  7046. } else {
  7047. 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>`;
  7048. }
  7049. return `
  7050. <tr class="hover:bg-slate-800/40 transition">
  7051. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  7052. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  7053. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  7054. <td class="py-2.5 px-3">
  7055. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  7056. ${p.local_as ? `<div class="text-[10px] text-purple-400 font-mono font-semibold" title="Custom Multi-Instance AS">Local: AS ${p.local_as}</div>` : `<div class="text-[10px] text-slate-500 font-mono">Global AS</div>`}
  7057. </td>
  7058. <td class="py-2.5 px-3">${stateBadge}</td>
  7059. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  7060. <td class="py-2.5 px-3 text-slate-300">
  7061. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  7062. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  7063. </td>
  7064. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  7065. ${p.in_filter ? `<span class="px-1.5 py-0.5 rounded bg-blue-950 text-blue-300 border border-blue-800/50" title="In Filter">IN: ${escapeHtml(p.in_filter)}</span> ` : ''}
  7066. ${p.out_filter ? `<span class="px-1.5 py-0.5 rounded bg-amber-950 text-amber-300 border border-amber-800/50" title="Out Filter">OUT: ${escapeHtml(p.out_filter)}</span>` : ''}
  7067. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  7068. </td>
  7069. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  7070. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  7071. <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'}">
  7072. ${p.disabled ? 'Enable' : 'Disable'}
  7073. </button>
  7074. <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">
  7075. Edit
  7076. </button>
  7077. <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">
  7078. Delete
  7079. </button>
  7080. </td>
  7081. </tr>
  7082. `;
  7083. }).join('');
  7084. }
  7085. function renderBgpNetworks() {
  7086. const tbody = document.getElementById('bgp-nets-table-body');
  7087. if (!tbody) return;
  7088. const empty = document.getElementById('bgp-nets-empty');
  7089. const countBadge = document.getElementById('bgp-nets-count-badge');
  7090. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  7091. const nets = state.bgpNets || [];
  7092. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  7093. if (navBadge) navBadge.innerText = nets.length;
  7094. if (nets.length === 0) {
  7095. tbody.innerHTML = '';
  7096. if (empty) empty.classList.remove('hidden');
  7097. return;
  7098. }
  7099. if (empty) empty.classList.add('hidden');
  7100. tbody.innerHTML = nets.map(n => `
  7101. <tr class="hover:bg-slate-800/40 transition">
  7102. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  7103. <td class="py-2.5 px-3">
  7104. ${n.disabled
  7105. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  7106. : '<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>'}
  7107. </td>
  7108. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  7109. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  7110. <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">
  7111. Delete
  7112. </button>
  7113. </td>
  7114. </tr>
  7115. `).join('');
  7116. }
  7117. function renderBgpRoutes() {
  7118. const tbody = document.getElementById('bgp-routes-table-body');
  7119. if (!tbody) return;
  7120. const empty = document.getElementById('bgp-routes-empty');
  7121. const countBadge = document.getElementById('bgp-routes-count-badge');
  7122. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  7123. const routes = state.bgpRoutes || [];
  7124. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  7125. if (navBadge) navBadge.innerText = routes.length;
  7126. if (routes.length === 0) {
  7127. tbody.innerHTML = '';
  7128. if (empty) empty.classList.remove('hidden');
  7129. return;
  7130. }
  7131. if (empty) empty.classList.add('hidden');
  7132. tbody.innerHTML = routes.map(r => `
  7133. <tr class="hover:bg-slate-800/40 transition">
  7134. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  7135. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  7136. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  7137. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  7138. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  7139. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  7140. </tr>
  7141. `).join('');
  7142. }
  7143. // =========================================================================
  7144. // ROUTEROS v7 OSPF TABLE RENDERING & SORTING
  7145. // =========================================================================
  7146. function sortOspfTable(tab, col) {
  7147. if (!state.ospfSort) state.ospfSort = {};
  7148. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  7149. if (state.ospfSort[tab].col === col) {
  7150. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  7151. } else {
  7152. state.ospfSort[tab].col = col;
  7153. state.ospfSort[tab].asc = true;
  7154. }
  7155. const asc = state.ospfSort[tab].asc;
  7156. let list = [];
  7157. if (tab === 'instances') list = state.ospfInstances || [];
  7158. else if (tab === 'areas') list = state.ospfAreas || [];
  7159. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  7160. else if (tab === 'templates') list = state.ospfTemplates || [];
  7161. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  7162. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  7163. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  7164. else if (tab === 'lsa') list = state.ospfLSA || [];
  7165. list.sort((a, b) => {
  7166. let valA = a[col] ?? '';
  7167. let valB = b[col] ?? '';
  7168. if (typeof valA === 'number' && typeof valB === 'number') {
  7169. return asc ? valA - valB : valB - valA;
  7170. }
  7171. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  7172. });
  7173. if (tab === 'instances') renderOspfInstances();
  7174. else if (tab === 'areas') renderOspfAreas();
  7175. else if (tab === 'ranges') renderOspfAreaRanges();
  7176. else if (tab === 'templates') renderOspfTemplates();
  7177. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  7178. else if (tab === 'snbrs') renderOspfStaticNbrs();
  7179. else if (tab === 'neighbors') renderOspfNeighbors();
  7180. else if (tab === 'lsa') renderOspfLSA();
  7181. }
  7182. function selectOspfRow(tab, id) {
  7183. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  7184. state.selectedOspfRow[tab] = id;
  7185. if (tab === 'instances') {
  7186. renderOspfInstances();
  7187. const btnEn = document.getElementById('btn-ospf-inst-enable');
  7188. const btnDis = document.getElementById('btn-ospf-inst-disable');
  7189. const btnRem = document.getElementById('btn-ospf-inst-remove');
  7190. const btnCom = document.getElementById('btn-ospf-inst-comment');
  7191. if (btnEn) btnEn.disabled = false;
  7192. if (btnDis) btnDis.disabled = false;
  7193. if (btnRem) btnRem.disabled = false;
  7194. if (btnCom) btnCom.disabled = false;
  7195. } else if (tab === 'areas') {
  7196. renderOspfAreas();
  7197. const btnEn = document.getElementById('btn-ospf-area-enable');
  7198. const btnDis = document.getElementById('btn-ospf-area-disable');
  7199. const btnRem = document.getElementById('btn-ospf-area-remove');
  7200. const btnCom = document.getElementById('btn-ospf-area-comment');
  7201. if (btnEn) btnEn.disabled = false;
  7202. if (btnDis) btnDis.disabled = false;
  7203. if (btnRem) btnRem.disabled = false;
  7204. if (btnCom) btnCom.disabled = false;
  7205. } else if (tab === 'ranges') {
  7206. renderOspfAreaRanges();
  7207. const btnEn = document.getElementById('btn-ospf-range-enable');
  7208. const btnDis = document.getElementById('btn-ospf-range-disable');
  7209. const btnRem = document.getElementById('btn-ospf-range-remove');
  7210. const btnCom = document.getElementById('btn-ospf-range-comment');
  7211. if (btnEn) btnEn.disabled = false;
  7212. if (btnDis) btnDis.disabled = false;
  7213. if (btnRem) btnRem.disabled = false;
  7214. if (btnCom) btnCom.disabled = false;
  7215. } else if (tab === 'templates') {
  7216. renderOspfTemplates();
  7217. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  7218. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  7219. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  7220. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  7221. if (btnEn) btnEn.disabled = false;
  7222. if (btnDis) btnDis.disabled = false;
  7223. if (btnRem) btnRem.disabled = false;
  7224. if (btnCom) btnCom.disabled = false;
  7225. } else if (tab === 'snbrs') {
  7226. renderOspfStaticNbrs();
  7227. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  7228. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  7229. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  7230. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  7231. if (btnEn) btnEn.disabled = false;
  7232. if (btnDis) btnDis.disabled = false;
  7233. if (btnRem) btnRem.disabled = false;
  7234. if (btnCom) btnCom.disabled = false;
  7235. }
  7236. }
  7237. // TAB 1: INSTANCES
  7238. function renderOspfInstances() {
  7239. const tbody = document.getElementById('ospf-instances-table-body');
  7240. if (!tbody) return;
  7241. const countEl = document.getElementById('ospf-instances-footer-count');
  7242. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  7243. let list = state.ospfInstances || [];
  7244. if (filter) {
  7245. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  7246. }
  7247. if (countEl) countEl.innerText = list.length;
  7248. const selId = state.selectedOspfRow?.instances;
  7249. tbody.innerHTML = list.map((inst, idx) => {
  7250. const isSel = inst.id === selId;
  7251. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7252. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7253. return `
  7254. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  7255. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7256. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  7257. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  7258. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7259. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  7260. </td>
  7261. <td class="py-1.5 px-3">${inst.version || 2}</td>
  7262. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  7263. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  7264. </tr>
  7265. `;
  7266. }).join('');
  7267. }
  7268. // TAB 2: AREAS
  7269. function renderOspfAreas() {
  7270. const tbody = document.getElementById('ospf-areas-table-body');
  7271. if (!tbody) return;
  7272. const countEl = document.getElementById('ospf-areas-footer-count');
  7273. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  7274. let list = state.ospfAreas || [];
  7275. if (filter) {
  7276. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  7277. }
  7278. if (countEl) countEl.innerText = list.length;
  7279. const selId = state.selectedOspfRow?.areas;
  7280. tbody.innerHTML = list.map((a, idx) => {
  7281. const isSel = a.id === selId;
  7282. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7283. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7284. return `
  7285. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  7286. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7287. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  7288. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  7289. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7290. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  7291. </td>
  7292. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  7293. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  7294. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  7295. </tr>
  7296. `;
  7297. }).join('');
  7298. }
  7299. // TAB 3: AREA RANGES
  7300. function renderOspfAreaRanges() {
  7301. const tbody = document.getElementById('ospf-ranges-table-body');
  7302. if (!tbody) return;
  7303. const countEl = document.getElementById('ospf-ranges-footer-count');
  7304. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  7305. let list = state.ospfAreaRanges || [];
  7306. if (filter) {
  7307. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  7308. }
  7309. if (countEl) countEl.innerText = list.length;
  7310. const selId = state.selectedOspfRow?.['area-ranges'];
  7311. tbody.innerHTML = list.map((r, idx) => {
  7312. const isSel = r.id === selId;
  7313. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7314. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7315. return `
  7316. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  7317. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7318. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  7319. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  7320. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  7321. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  7322. <td class="py-1.5 px-3">${r.cost || 1}</td>
  7323. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  7324. </tr>
  7325. `;
  7326. }).join('');
  7327. }
  7328. // TAB 4: INTERFACE TEMPLATES
  7329. function renderOspfTemplates() {
  7330. const tbody = document.getElementById('ospf-templates-table-body');
  7331. if (!tbody) return;
  7332. const countEl = document.getElementById('ospf-templates-footer-count');
  7333. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  7334. let list = state.ospfTemplates || [];
  7335. if (filter) {
  7336. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  7337. }
  7338. if (countEl) countEl.innerText = list.length;
  7339. const selId = state.selectedOspfRow?.templates;
  7340. tbody.innerHTML = list.map((t, idx) => {
  7341. const isSel = t.id === selId;
  7342. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7343. const ifaces = t.interfaces || t.interface || 'all';
  7344. const nets = t.networks || t.network || '';
  7345. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7346. return `
  7347. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  7348. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  7349. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  7350. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  7351. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7352. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  7353. </td>
  7354. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  7355. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  7356. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  7357. <td class="py-1.5 px-3">${t.cost || 1}</td>
  7358. <td class="py-1.5 px-3">${t.priority || 128}</td>
  7359. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  7360. </tr>
  7361. `;
  7362. }).join('');
  7363. }
  7364. // TAB 5: LIVE INTERFACES
  7365. function renderOspfLiveInterfaces() {
  7366. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  7367. if (!tbody) return;
  7368. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  7369. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  7370. let list = state.ospfLiveInterfaces || [];
  7371. if (filter) {
  7372. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  7373. }
  7374. if (countEl) countEl.innerText = list.length;
  7375. tbody.innerHTML = list.map(i => `
  7376. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7377. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  7378. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  7379. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  7380. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  7381. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  7382. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  7383. <td class="py-1.5 px-3">${i.cost || 1}</td>
  7384. <td class="py-1.5 px-3">${i.priority || 128}</td>
  7385. </tr>
  7386. `).join('');
  7387. }
  7388. // TAB 6: STATIC NEIGHBORS
  7389. function renderOspfStaticNbrs() {
  7390. const tbody = document.getElementById('ospf-snbrs-table-body');
  7391. if (!tbody) return;
  7392. const countEl = document.getElementById('ospf-snbrs-footer-count');
  7393. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  7394. let list = state.ospfStaticNbrs || [];
  7395. if (filter) {
  7396. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  7397. }
  7398. if (countEl) countEl.innerText = list.length;
  7399. const selId = state.selectedOspfRow?.['static-nbrs'];
  7400. tbody.innerHTML = list.map((n, idx) => {
  7401. const isSel = n.id === selId;
  7402. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7403. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7404. return `
  7405. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  7406. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7407. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  7408. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  7409. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  7410. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  7411. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  7412. <td class="py-1.5 px-3">${n.cost || 1}</td>
  7413. </tr>
  7414. `;
  7415. }).join('');
  7416. }
  7417. // TAB 7: LIVE NEIGHBORS
  7418. function renderOspfNeighbors() {
  7419. const tbody = document.getElementById('ospf-neighbors-table-body');
  7420. if (!tbody) return;
  7421. const countEl = document.getElementById('ospf-neighbors-footer-count');
  7422. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  7423. let list = state.ospfNeighbors || [];
  7424. if (filter) {
  7425. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  7426. }
  7427. if (countEl) countEl.innerText = list.length;
  7428. tbody.innerHTML = list.map(n => `
  7429. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7430. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  7431. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  7432. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7433. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  7434. </td>
  7435. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  7436. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  7437. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  7438. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  7439. </tr>
  7440. `).join('');
  7441. }
  7442. // TAB 8: LINK-STATE DATABASE (LSA)
  7443. function renderOspfLSA() {
  7444. const tbody = document.getElementById('ospf-lsa-table-body');
  7445. if (!tbody) return;
  7446. const countEl = document.getElementById('ospf-lsa-footer-count');
  7447. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  7448. let list = state.ospfLSA || [];
  7449. if (filter) {
  7450. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  7451. }
  7452. if (countEl) countEl.innerText = list.length;
  7453. tbody.innerHTML = list.map(l => `
  7454. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7455. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  7456. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7457. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  7458. </td>
  7459. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  7460. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  7461. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  7462. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  7463. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  7464. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  7465. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  7466. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  7467. </tr>
  7468. `).join('');
  7469. }
  7470. function renderOspfStatusPill() {
  7471. // Maintained for backward compatibility
  7472. const pill = document.getElementById('ospf-live-status-pill');
  7473. if (!pill) return;
  7474. 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';
  7475. pill.innerText = 'OSPF ACTIVE';
  7476. }
  7477. function renderOspfInterfaces() {
  7478. renderOspfTemplates();
  7479. }
  7480. function renderOspfRoutes() {
  7481. // Routes retained in background
  7482. }
  7483. // BGP Modals & Actions
  7484. function openBgpInstanceModal() {
  7485. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  7486. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  7487. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  7488. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  7489. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  7490. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  7491. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  7492. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  7493. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  7494. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  7495. }
  7496. function closeBgpInstanceModal() {
  7497. document.getElementById('bgp-instance-modal').classList.add('hidden');
  7498. }
  7499. async function submitBgpInstance(e) {
  7500. e.preventDefault();
  7501. const payload = {
  7502. enabled: document.getElementById('modal-bgp-enabled').checked,
  7503. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  7504. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  7505. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  7506. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  7507. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  7508. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  7509. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  7510. };
  7511. try {
  7512. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  7513. method: 'POST',
  7514. headers: { 'Content-Type': 'application/json' },
  7515. body: JSON.stringify(payload)
  7516. });
  7517. if (res.ok) {
  7518. closeBgpInstanceModal();
  7519. showToast('Success', 'BGP instance configuration updated', 'success');
  7520. loadDynamicRouting();
  7521. } else {
  7522. const err = await res.json();
  7523. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  7524. }
  7525. } catch (err) {
  7526. showToast('Error', err.message, 'error');
  7527. }
  7528. }
  7529. // ----------------- BGP Peer Connection Modal (RouterOS v7) -----------------
  7530. function switchBgpPeerModalTab(tab) {
  7531. const tabs = ['general', 'extra', 'attributes', 'filter'];
  7532. tabs.forEach(t => {
  7533. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  7534. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  7535. if (t === tab) {
  7536. if (pane) pane.classList.remove('hidden');
  7537. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  7538. } else {
  7539. if (pane) pane.classList.add('hidden');
  7540. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition';
  7541. }
  7542. });
  7543. }
  7544. function addOutputNetworkRow(val = '') {
  7545. const container = document.getElementById('modal-bgp-output-networks-container');
  7546. if (!container) return;
  7547. const row = document.createElement('div');
  7548. row.className = 'flex items-center gap-2 output-net-row';
  7549. row.innerHTML = `
  7550. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 10.2.51.0/24 or BGP-AWMN" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-cyan-500">
  7551. <button type="button" onclick="this.closest('.output-net-row').remove()" class="w-7 h-7 flex items-center justify-center bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-400 border border-slate-700 rounded-lg text-base font-bold transition" title="Remove network">-</button>
  7552. `;
  7553. container.appendChild(row);
  7554. }
  7555. function parseBgpTime(val) {
  7556. if (!val) return 0;
  7557. val = String(val).trim();
  7558. if (val.includes(':')) {
  7559. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  7560. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  7561. if (parts.length === 2) return parts[0] * 60 + parts[1];
  7562. }
  7563. return parseInt(val, 10) || 0;
  7564. }
  7565. function formatBgpTime(secs) {
  7566. if (!secs || secs <= 0) return '00:00:00';
  7567. const h = Math.floor(secs / 3600);
  7568. const m = Math.floor((secs % 3600) / 60);
  7569. const s = secs % 60;
  7570. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  7571. }
  7572. function populateBgpRoutingTables() {
  7573. const sel = document.getElementById('modal-bgp-peer-routing-table');
  7574. if (!sel) return;
  7575. const cur = sel.value || 'main';
  7576. sel.innerHTML = '<option value="main">main</option>';
  7577. (state.routingTables || []).forEach(t => {
  7578. if (t.name !== 'main') {
  7579. const opt = document.createElement('option');
  7580. opt.value = t.name;
  7581. opt.innerText = t.name;
  7582. sel.appendChild(opt);
  7583. }
  7584. });
  7585. sel.value = cur;
  7586. }
  7587. function openAddBgpPeerModal() {
  7588. document.getElementById('bgp-peer-form').reset();
  7589. document.getElementById('modal-bgp-peer-id').value = '';
  7590. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  7591. // General Tab
  7592. document.getElementById('modal-bgp-peer-enabled').checked = true;
  7593. document.getElementById('modal-bgp-peer-comment').value = '';
  7594. document.getElementById('modal-bgp-peer-name').value = '';
  7595. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  7596. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  7597. document.getElementById('modal-bgp-peer-local-as').value = '';
  7598. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  7599. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  7600. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  7601. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  7602. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  7603. document.getElementById('modal-bgp-peer-router-id').value = '';
  7604. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  7605. document.getElementById('modal-bgp-peer-remote-port').value = '';
  7606. document.getElementById('modal-bgp-peer-remote-as').value = '';
  7607. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  7608. document.getElementById('modal-bgp-peer-local-addr').value = '';
  7609. document.getElementById('modal-bgp-peer-local-port').value = '';
  7610. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  7611. document.getElementById('modal-bgp-peer-password').value = '';
  7612. document.getElementById('modal-bgp-peer-multihop').checked = false;
  7613. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  7614. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  7615. document.getElementById('modal-bgp-peer-connect').checked = true;
  7616. document.getElementById('modal-bgp-peer-listen').checked = true;
  7617. // Extra Tab
  7618. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  7619. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  7620. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  7621. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  7622. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  7623. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  7624. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  7625. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  7626. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  7627. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  7628. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  7629. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  7630. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = false;
  7631. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = false;
  7632. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  7633. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = false;
  7634. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = false;
  7635. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = false;
  7636. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = '';
  7637. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = '';
  7638. // Attributes Tab
  7639. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  7640. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  7641. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  7642. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  7643. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  7644. document.getElementById('modal-bgp-peer-as-override').checked = false;
  7645. // Filter Tab
  7646. populateFilterChainsDatalist();
  7647. document.getElementById('modal-bgp-peer-in-filter').value = '';
  7648. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = '';
  7649. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = '';
  7650. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = '';
  7651. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = '';
  7652. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = '';
  7653. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = '';
  7654. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = '';
  7655. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = false;
  7656. document.getElementById('modal-bgp-peer-out-filter').value = '';
  7657. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = 'disabled';
  7658. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  7659. populateBgpRoutingTables();
  7660. const container = document.getElementById('modal-bgp-output-networks-container');
  7661. if (container) {
  7662. container.innerHTML = '';
  7663. addOutputNetworkRow('');
  7664. }
  7665. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7666. if (removeBtn) removeBtn.classList.add('hidden');
  7667. switchBgpPeerModalTab('general');
  7668. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  7669. }
  7670. function populateFilterChainsDatalist() {
  7671. const dl = document.getElementById('filter-chains-list');
  7672. if (!dl) return;
  7673. const chains = new Set();
  7674. (state.routingFilters || []).forEach(f => {
  7675. if (f.chain) chains.add(f.chain);
  7676. });
  7677. if (chains.size === 0) {
  7678. chains.add('awmn');
  7679. chains.add('bgp-in');
  7680. chains.add('bgp-out');
  7681. }
  7682. dl.innerHTML = '';
  7683. chains.forEach(c => {
  7684. const opt = document.createElement('option');
  7685. opt.value = c;
  7686. dl.appendChild(opt);
  7687. });
  7688. }
  7689. function openEditBgpPeerModal(id) {
  7690. const p = (state.bgpPeers || []).find(item => item.id === id);
  7691. if (!p) return;
  7692. populateBgpRoutingTables();
  7693. populateFilterChainsDatalist();
  7694. document.getElementById('modal-bgp-peer-id').value = p.id;
  7695. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  7696. // General Tab
  7697. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  7698. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  7699. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  7700. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  7701. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  7702. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  7703. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  7704. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  7705. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  7706. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  7707. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  7708. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  7709. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  7710. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  7711. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  7712. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  7713. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  7714. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  7715. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  7716. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  7717. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  7718. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  7719. // Extra Tab
  7720. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  7721. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  7722. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  7723. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  7724. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  7725. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  7726. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  7727. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  7728. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  7729. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  7730. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  7731. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  7732. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  7733. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = !!p.redist_bgp_mpls_vpn;
  7734. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = !!p.redist_slaac;
  7735. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  7736. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = !!p.network_blackhole;
  7737. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = !!p.no_early_cut;
  7738. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = !!p.keep_sent_attrs;
  7739. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = p.input_affinity || '';
  7740. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = p.output_affinity || '';
  7741. // Attributes Tab
  7742. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  7743. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  7744. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  7745. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = !!p.ignore_as_path_len;
  7746. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  7747. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  7748. // Filter Tab
  7749. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  7750. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = p.in_accept_nlri || '';
  7751. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = p.in_accept_communities || '';
  7752. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = p.in_accept_ext_communities || '';
  7753. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = p.in_accept_large_communities || '';
  7754. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = p.in_filter_communities || '';
  7755. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = p.in_filter_ext_communities || '';
  7756. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = p.in_filter_large_communities || '';
  7757. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = !!p.in_filter_unknown;
  7758. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  7759. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = p.out_selection_policy || 'disabled';
  7760. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  7761. // Output Networks
  7762. const container = document.getElementById('modal-bgp-output-networks-container');
  7763. if (container) {
  7764. container.innerHTML = '';
  7765. if (p.output_networks && p.output_networks.length > 0) {
  7766. p.output_networks.forEach(net => addOutputNetworkRow(net));
  7767. } else {
  7768. addOutputNetworkRow('');
  7769. }
  7770. }
  7771. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7772. if (removeBtn) removeBtn.classList.remove('hidden');
  7773. switchBgpPeerModalTab('general');
  7774. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  7775. }
  7776. function copyCurrentBgpPeer() {
  7777. document.getElementById('modal-bgp-peer-id').value = '';
  7778. const nameEl = document.getElementById('modal-bgp-peer-name');
  7779. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  7780. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  7781. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7782. if (removeBtn) removeBtn.classList.add('hidden');
  7783. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  7784. }
  7785. function removeCurrentBgpPeer() {
  7786. const id = document.getElementById('modal-bgp-peer-id')?.value;
  7787. if (!id) return;
  7788. deleteBgpPeer(id);
  7789. closeBgpPeerModal();
  7790. }
  7791. function closeBgpPeerModal() {
  7792. document.getElementById('bgp-peer-modal').classList.add('hidden');
  7793. }
  7794. function getBgpPeerFormData() {
  7795. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  7796. const outputNetworks = [];
  7797. netInputs.forEach(inp => {
  7798. const v = inp.value.trim();
  7799. if (v) outputNetworks.push(v);
  7800. });
  7801. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  7802. return {
  7803. id: document.getElementById('modal-bgp-peer-id').value,
  7804. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  7805. enabled: enabled,
  7806. disabled: !enabled,
  7807. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  7808. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  7809. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  7810. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  7811. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  7812. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  7813. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  7814. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  7815. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  7816. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  7817. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  7818. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  7819. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  7820. password: document.getElementById('modal-bgp-peer-password').value,
  7821. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  7822. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  7823. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  7824. connect: document.getElementById('modal-bgp-peer-connect').checked,
  7825. listen: document.getElementById('modal-bgp-peer-listen').checked,
  7826. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  7827. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  7828. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  7829. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  7830. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  7831. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  7832. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  7833. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  7834. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  7835. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  7836. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  7837. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  7838. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  7839. redist_bgp_mpls_vpn: document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')?.checked || false,
  7840. redist_slaac: document.getElementById('modal-bgp-peer-redist-slaac')?.checked || false,
  7841. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  7842. network_blackhole: document.getElementById('modal-bgp-peer-network-blackhole')?.checked || false,
  7843. no_early_cut: document.getElementById('modal-bgp-peer-no-early-cut')?.checked || false,
  7844. keep_sent_attrs: document.getElementById('modal-bgp-peer-keep-sent-attrs')?.checked || false,
  7845. input_affinity: (document.getElementById('modal-bgp-peer-input-affinity')?.value || '').trim(),
  7846. output_affinity: (document.getElementById('modal-bgp-peer-output-affinity')?.value || '').trim(),
  7847. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  7848. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  7849. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  7850. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  7851. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  7852. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  7853. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  7854. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  7855. in_accept_nlri: (document.getElementById('modal-bgp-peer-in-accept-nlri')?.value || '').trim(),
  7856. in_accept_communities: (document.getElementById('modal-bgp-peer-in-accept-comm')?.value || '').trim(),
  7857. in_accept_ext_communities: (document.getElementById('modal-bgp-peer-in-accept-ext-comm')?.value || '').trim(),
  7858. in_accept_large_communities: (document.getElementById('modal-bgp-peer-in-accept-large-comm')?.value || '').trim(),
  7859. in_filter_communities: (document.getElementById('modal-bgp-peer-in-filter-comm')?.value || '').trim(),
  7860. in_filter_ext_communities: (document.getElementById('modal-bgp-peer-in-filter-ext-comm')?.value || '').trim(),
  7861. in_filter_large_communities: (document.getElementById('modal-bgp-peer-in-filter-large-comm')?.value || '').trim(),
  7862. in_filter_unknown: document.getElementById('modal-bgp-peer-in-filter-unknown')?.checked || false,
  7863. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  7864. out_selection_policy: document.getElementById('modal-bgp-peer-out-selection-policy')?.value || 'disabled',
  7865. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  7866. output_networks: outputNetworks
  7867. };
  7868. }
  7869. async function submitBgpPeer(e) {
  7870. if (e) e.preventDefault();
  7871. const payload = getBgpPeerFormData();
  7872. try {
  7873. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  7874. method: 'POST',
  7875. headers: { 'Content-Type': 'application/json' },
  7876. body: JSON.stringify(payload)
  7877. });
  7878. if (res.ok) {
  7879. closeBgpPeerModal();
  7880. showToast('Success', 'BGP Connection saved', 'success');
  7881. loadDynamicRouting();
  7882. } else {
  7883. const err = await res.json();
  7884. showToast('Error', err.error || 'Failed to save peer', 'error');
  7885. }
  7886. } catch (err) {
  7887. showToast('Error', err.message, 'error');
  7888. }
  7889. }
  7890. async function applyBgpPeerModal(e) {
  7891. if (e) e.preventDefault();
  7892. const payload = getBgpPeerFormData();
  7893. try {
  7894. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  7895. method: 'POST',
  7896. headers: { 'Content-Type': 'application/json' },
  7897. body: JSON.stringify(payload)
  7898. });
  7899. if (res.ok) {
  7900. const data = await res.json();
  7901. if (data.peer && data.peer.id) {
  7902. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  7903. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  7904. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  7905. }
  7906. showToast('Applied', 'BGP Connection applied', 'success');
  7907. loadDynamicRouting();
  7908. } else {
  7909. const err = await res.json();
  7910. showToast('Error', err.error || 'Failed to apply peer', 'error');
  7911. }
  7912. } catch (err) {
  7913. showToast('Error', err.message, 'error');
  7914. }
  7915. }
  7916. async function deleteBgpPeer(id) {
  7917. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  7918. try {
  7919. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7920. if (res.ok) {
  7921. showToast('Deleted', 'BGP peer removed', 'success');
  7922. loadDynamicRouting();
  7923. }
  7924. } catch (err) {
  7925. showToast('Error', err.message, 'error');
  7926. }
  7927. }
  7928. async function toggleBgpPeerState(id, disabled) {
  7929. try {
  7930. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  7931. method: 'POST',
  7932. headers: { 'Content-Type': 'application/json' },
  7933. body: JSON.stringify({ disabled })
  7934. });
  7935. if (res.ok) {
  7936. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  7937. loadDynamicRouting();
  7938. }
  7939. } catch (err) {
  7940. showToast('Error', err.message, 'error');
  7941. }
  7942. }
  7943. function openAddBgpNetworkModal() {
  7944. document.getElementById('bgp-network-form').reset();
  7945. document.getElementById('modal-bgp-net-id').value = '';
  7946. document.getElementById('bgp-network-modal').classList.remove('hidden');
  7947. }
  7948. function closeBgpNetworkModal() {
  7949. document.getElementById('bgp-network-modal').classList.add('hidden');
  7950. }
  7951. async function submitBgpNetwork(e) {
  7952. e.preventDefault();
  7953. const payload = {
  7954. id: document.getElementById('modal-bgp-net-id').value,
  7955. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  7956. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  7957. disabled: document.getElementById('modal-bgp-net-disabled').checked
  7958. };
  7959. try {
  7960. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  7961. method: 'POST',
  7962. headers: { 'Content-Type': 'application/json' },
  7963. body: JSON.stringify(payload)
  7964. });
  7965. if (res.ok) {
  7966. closeBgpNetworkModal();
  7967. showToast('Success', 'BGP network advertisement saved', 'success');
  7968. loadDynamicRouting();
  7969. } else {
  7970. const err = await res.json();
  7971. showToast('Error', err.error || 'Failed to save network', 'error');
  7972. }
  7973. } catch (err) {
  7974. showToast('Error', err.message, 'error');
  7975. }
  7976. }
  7977. async function deleteBgpNetwork(id) {
  7978. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  7979. try {
  7980. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7981. if (res.ok) {
  7982. showToast('Deleted', 'Network advertisement removed', 'success');
  7983. loadDynamicRouting();
  7984. }
  7985. } catch (err) {
  7986. showToast('Error', err.message, 'error');
  7987. }
  7988. }
  7989. // =========================================================================
  7990. // ROUTEROS v7 OSPF MODALS & ACTIONS
  7991. // =========================================================================
  7992. // --- 1. OSPF INSTANCE ---
  7993. function openOspfInstanceModal(id = null) {
  7994. const isEdit = !!id;
  7995. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  7996. id: '',
  7997. name: 'Default',
  7998. version: 2,
  7999. vrf: 'main',
  8000. router_id: '192.168.131.56',
  8001. routing_table: 'main',
  8002. enabled: true,
  8003. redistribute_connected: false,
  8004. redistribute_static: true,
  8005. redistribute_bgp: false,
  8006. comment: ''
  8007. };
  8008. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  8009. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  8010. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  8011. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  8012. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  8013. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  8014. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  8015. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  8016. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  8017. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  8018. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  8019. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  8020. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  8021. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8022. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  8023. }
  8024. function openEditOspfInstanceModal(id) {
  8025. openOspfInstanceModal(id);
  8026. }
  8027. function closeOspfInstanceModal() {
  8028. document.getElementById('ospf-instance-modal').classList.add('hidden');
  8029. }
  8030. async function submitOspfInstance(e) {
  8031. if (e) e.preventDefault();
  8032. const payload = {
  8033. id: document.getElementById('modal-ospf-inst-id').value,
  8034. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  8035. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  8036. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  8037. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  8038. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  8039. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  8040. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  8041. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  8042. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  8043. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  8044. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  8045. };
  8046. try {
  8047. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  8048. method: 'POST',
  8049. headers: { 'Content-Type': 'application/json' },
  8050. body: JSON.stringify(payload)
  8051. });
  8052. if (res.ok) {
  8053. closeOspfInstanceModal();
  8054. showToast('Saved', 'OSPF instance updated', 'success');
  8055. loadDynamicRouting();
  8056. } else {
  8057. const err = await res.json();
  8058. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  8059. }
  8060. } catch (err) {
  8061. showToast('Error', err.message, 'error');
  8062. }
  8063. }
  8064. function applyOspfInstanceForm() {
  8065. submitOspfInstance(null);
  8066. }
  8067. function copyOspfInstance() {
  8068. document.getElementById('modal-ospf-inst-id').value = '';
  8069. document.getElementById('modal-ospf-inst-name').value += '-copy';
  8070. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  8071. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  8072. }
  8073. async function deleteCurrentOspfInstance() {
  8074. const id = document.getElementById('modal-ospf-inst-id').value;
  8075. if (!id) return;
  8076. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  8077. try {
  8078. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8079. if (res.ok) {
  8080. closeOspfInstanceModal();
  8081. showToast('Removed', 'OSPF instance deleted', 'success');
  8082. loadDynamicRouting();
  8083. }
  8084. } catch (err) {
  8085. showToast('Error', err.message, 'error');
  8086. }
  8087. }
  8088. async function enableSelectedOspfInstance() {
  8089. const id = state.selectedOspfRow?.instances;
  8090. if (!id) return;
  8091. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8092. method: 'POST',
  8093. headers: { 'Content-Type': 'application/json' },
  8094. body: JSON.stringify({ disabled: false })
  8095. });
  8096. loadDynamicRouting();
  8097. }
  8098. async function disableSelectedOspfInstance() {
  8099. const id = state.selectedOspfRow?.instances;
  8100. if (!id) return;
  8101. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8102. method: 'POST',
  8103. headers: { 'Content-Type': 'application/json' },
  8104. body: JSON.stringify({ disabled: true })
  8105. });
  8106. loadDynamicRouting();
  8107. }
  8108. async function removeSelectedOspfInstance() {
  8109. const id = state.selectedOspfRow?.instances;
  8110. if (!id) return;
  8111. if (!confirm('Delete selected OSPF instance?')) return;
  8112. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8113. loadDynamicRouting();
  8114. }
  8115. async function promptCommentOspfInstance() {
  8116. const id = state.selectedOspfRow?.instances;
  8117. if (!id) return;
  8118. const inst = (state.ospfInstances || []).find(i => i.id === id);
  8119. if (!inst) return;
  8120. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  8121. if (comment === null) return;
  8122. inst.comment = comment;
  8123. await fetch(`${API_BASE}/routing/ospf/instances`, {
  8124. method: 'POST',
  8125. headers: { 'Content-Type': 'application/json' },
  8126. body: JSON.stringify(inst)
  8127. });
  8128. loadDynamicRouting();
  8129. }
  8130. // --- 2. OSPF AREA ---
  8131. function populateOspfAreaDropdowns() {
  8132. const instSelect = document.getElementById('modal-ospf-area-instance');
  8133. if (instSelect) {
  8134. const cur = instSelect.value;
  8135. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  8136. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  8137. if (cur) instSelect.value = cur;
  8138. }
  8139. }
  8140. function openOspfAreaModal(id = null) {
  8141. const isEdit = !!id;
  8142. populateOspfAreaDropdowns();
  8143. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  8144. id: '',
  8145. name: 'Default',
  8146. instance: 'Default',
  8147. area_id: '0.0.0.0',
  8148. area_type: 'default',
  8149. default_cost: 1,
  8150. no_summaries: false,
  8151. disabled: false,
  8152. comment: ''
  8153. };
  8154. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  8155. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  8156. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  8157. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  8158. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  8159. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  8160. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  8161. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  8162. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  8163. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  8164. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  8165. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8166. document.getElementById('ospf-area-modal').classList.remove('hidden');
  8167. }
  8168. function openEditOspfAreaModal(id) {
  8169. openOspfAreaModal(id);
  8170. }
  8171. function closeOspfAreaModal() {
  8172. document.getElementById('ospf-area-modal').classList.add('hidden');
  8173. }
  8174. async function submitOspfArea(e) {
  8175. if (e) e.preventDefault();
  8176. const payload = {
  8177. id: document.getElementById('modal-ospf-area-id').value,
  8178. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  8179. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  8180. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  8181. area_type: document.getElementById('modal-ospf-area-type').value,
  8182. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  8183. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  8184. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  8185. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  8186. };
  8187. try {
  8188. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  8189. method: 'POST',
  8190. headers: { 'Content-Type': 'application/json' },
  8191. body: JSON.stringify(payload)
  8192. });
  8193. if (res.ok) {
  8194. closeOspfAreaModal();
  8195. showToast('Saved', 'OSPF area saved', 'success');
  8196. loadDynamicRouting();
  8197. } else {
  8198. const err = await res.json();
  8199. showToast('Error', err.error || 'Failed to save area', 'error');
  8200. }
  8201. } catch (err) {
  8202. showToast('Error', err.message, 'error');
  8203. }
  8204. }
  8205. function applyOspfAreaForm() {
  8206. submitOspfArea(null);
  8207. }
  8208. function copyOspfArea() {
  8209. document.getElementById('modal-ospf-area-id').value = '';
  8210. document.getElementById('modal-ospf-area-name').value += '-copy';
  8211. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  8212. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  8213. }
  8214. async function deleteCurrentOspfArea() {
  8215. const id = document.getElementById('modal-ospf-area-id').value;
  8216. if (!id) return;
  8217. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  8218. try {
  8219. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8220. if (res.ok) {
  8221. closeOspfAreaModal();
  8222. showToast('Removed', 'OSPF area deleted', 'success');
  8223. loadDynamicRouting();
  8224. }
  8225. } catch (err) {
  8226. showToast('Error', err.message, 'error');
  8227. }
  8228. }
  8229. async function enableSelectedOspfArea() {
  8230. const id = state.selectedOspfRow?.areas;
  8231. if (!id) return;
  8232. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  8233. method: 'POST',
  8234. headers: { 'Content-Type': 'application/json' },
  8235. body: JSON.stringify({ disabled: false })
  8236. });
  8237. loadDynamicRouting();
  8238. }
  8239. async function disableSelectedOspfArea() {
  8240. const id = state.selectedOspfRow?.areas;
  8241. if (!id) return;
  8242. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  8243. method: 'POST',
  8244. headers: { 'Content-Type': 'application/json' },
  8245. body: JSON.stringify({ disabled: true })
  8246. });
  8247. loadDynamicRouting();
  8248. }
  8249. async function removeSelectedOspfArea() {
  8250. const id = state.selectedOspfRow?.areas;
  8251. if (!id) return;
  8252. if (!confirm('Delete selected OSPF area?')) return;
  8253. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8254. loadDynamicRouting();
  8255. }
  8256. async function promptCommentOspfArea() {
  8257. const id = state.selectedOspfRow?.areas;
  8258. if (!id) return;
  8259. const area = (state.ospfAreas || []).find(a => a.id === id);
  8260. if (!area) return;
  8261. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  8262. if (comment === null) return;
  8263. area.comment = comment;
  8264. await fetch(`${API_BASE}/routing/ospf/areas`, {
  8265. method: 'POST',
  8266. headers: { 'Content-Type': 'application/json' },
  8267. body: JSON.stringify(area)
  8268. });
  8269. loadDynamicRouting();
  8270. }
  8271. // --- 3. OSPF AREA RANGE ---
  8272. function populateAreaRangeDropdowns() {
  8273. const select = document.getElementById('modal-ospf-range-area');
  8274. if (select) {
  8275. const cur = select.value;
  8276. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8277. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8278. if (cur) select.value = cur;
  8279. }
  8280. }
  8281. function openOspfAreaRangeModal(id = null) {
  8282. const isEdit = !!id;
  8283. populateAreaRangeDropdowns();
  8284. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  8285. id: '',
  8286. area: 'Default',
  8287. prefix: '',
  8288. cost: 1,
  8289. advertise: true,
  8290. disabled: false,
  8291. comment: ''
  8292. };
  8293. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  8294. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  8295. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  8296. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  8297. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  8298. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  8299. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  8300. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  8301. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  8302. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8303. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  8304. }
  8305. function openEditOspfAreaRangeModal(id) {
  8306. openOspfAreaRangeModal(id);
  8307. }
  8308. function closeOspfAreaRangeModal() {
  8309. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  8310. }
  8311. async function submitOspfAreaRange(e) {
  8312. if (e) e.preventDefault();
  8313. const payload = {
  8314. id: document.getElementById('modal-ospf-range-id').value,
  8315. area: document.getElementById('modal-ospf-range-area').value,
  8316. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  8317. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  8318. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  8319. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  8320. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  8321. };
  8322. try {
  8323. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  8324. method: 'POST',
  8325. headers: { 'Content-Type': 'application/json' },
  8326. body: JSON.stringify(payload)
  8327. });
  8328. if (res.ok) {
  8329. closeOspfAreaRangeModal();
  8330. showToast('Saved', 'Area range saved', 'success');
  8331. loadDynamicRouting();
  8332. } else {
  8333. const err = await res.json();
  8334. showToast('Error', err.error || 'Failed to save area range', 'error');
  8335. }
  8336. } catch (err) {
  8337. showToast('Error', err.message, 'error');
  8338. }
  8339. }
  8340. function applyOspfAreaRangeForm() {
  8341. submitOspfAreaRange(null);
  8342. }
  8343. async function deleteCurrentOspfAreaRange() {
  8344. const id = document.getElementById('modal-ospf-range-id').value;
  8345. if (!id) return;
  8346. if (!confirm('Delete this area range?')) return;
  8347. try {
  8348. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8349. closeOspfAreaRangeModal();
  8350. showToast('Removed', 'Area range removed', 'success');
  8351. loadDynamicRouting();
  8352. } catch (err) {
  8353. showToast('Error', err.message, 'error');
  8354. }
  8355. }
  8356. async function enableSelectedOspfAreaRange() {
  8357. const id = state.selectedOspfRow?.['area-ranges'];
  8358. if (!id) return;
  8359. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8360. if (!r) return;
  8361. r.disabled = false;
  8362. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8363. loadDynamicRouting();
  8364. }
  8365. async function disableSelectedOspfAreaRange() {
  8366. const id = state.selectedOspfRow?.['area-ranges'];
  8367. if (!id) return;
  8368. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8369. if (!r) return;
  8370. r.disabled = true;
  8371. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8372. loadDynamicRouting();
  8373. }
  8374. async function removeSelectedOspfAreaRange() {
  8375. const id = state.selectedOspfRow?.['area-ranges'];
  8376. if (!id) return;
  8377. if (!confirm('Delete selected area range?')) return;
  8378. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8379. loadDynamicRouting();
  8380. }
  8381. async function promptCommentOspfAreaRange() {
  8382. const id = state.selectedOspfRow?.['area-ranges'];
  8383. if (!id) return;
  8384. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8385. if (!r) return;
  8386. const comment = prompt('Enter comment for area range:', r.comment || '');
  8387. if (comment === null) return;
  8388. r.comment = comment;
  8389. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8390. loadDynamicRouting();
  8391. }
  8392. // --- 4. OSPF INTERFACE TEMPLATE ---
  8393. function switchOspfTemplateTab(tab) {
  8394. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  8395. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  8396. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  8397. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  8398. if (tab === 'general') {
  8399. if (tabGen) tabGen.classList.remove('hidden');
  8400. if (tabAuth) tabAuth.classList.add('hidden');
  8401. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  8402. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition';
  8403. } else {
  8404. if (tabGen) tabGen.classList.add('hidden');
  8405. if (tabAuth) tabAuth.classList.remove('hidden');
  8406. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition';
  8407. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  8408. }
  8409. }
  8410. function populateTemplateAreaDropdowns() {
  8411. const select = document.getElementById('modal-ospf-tmpl-area');
  8412. if (select) {
  8413. const cur = select.value;
  8414. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8415. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8416. if (cur) select.value = cur;
  8417. }
  8418. }
  8419. function openOspfTemplateModal(id = null) {
  8420. const isEdit = !!id;
  8421. populateTemplateAreaDropdowns();
  8422. switchOspfTemplateTab('general');
  8423. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  8424. id: '',
  8425. interfaces: '',
  8426. area: 'Default',
  8427. networks: '',
  8428. network_type: 'broadcast',
  8429. cost: 1,
  8430. priority: 128,
  8431. passive: false,
  8432. hello_interval: 10,
  8433. dead_interval: 40,
  8434. auth: 'none',
  8435. auth_key: '',
  8436. disabled: false,
  8437. comment: ''
  8438. };
  8439. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  8440. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  8441. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  8442. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  8443. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  8444. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  8445. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  8446. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  8447. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  8448. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  8449. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  8450. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  8451. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  8452. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  8453. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  8454. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  8455. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8456. document.getElementById('ospf-template-modal').classList.remove('hidden');
  8457. }
  8458. function openEditOspfTemplateModal(id) {
  8459. openOspfTemplateModal(id);
  8460. }
  8461. function closeOspfTemplateModal() {
  8462. document.getElementById('ospf-template-modal').classList.add('hidden');
  8463. }
  8464. async function submitOspfTemplate(e) {
  8465. if (e) e.preventDefault();
  8466. const payload = {
  8467. id: document.getElementById('modal-ospf-tmpl-id').value,
  8468. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  8469. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  8470. area: document.getElementById('modal-ospf-tmpl-area').value,
  8471. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  8472. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  8473. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  8474. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  8475. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  8476. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  8477. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  8478. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  8479. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  8480. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  8481. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  8482. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  8483. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  8484. };
  8485. try {
  8486. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  8487. method: 'POST',
  8488. headers: { 'Content-Type': 'application/json' },
  8489. body: JSON.stringify(payload)
  8490. });
  8491. if (res.ok) {
  8492. closeOspfTemplateModal();
  8493. showToast('Saved', 'Interface template saved', 'success');
  8494. loadDynamicRouting();
  8495. } else {
  8496. const err = await res.json();
  8497. showToast('Error', err.error || 'Failed to save interface template', 'error');
  8498. }
  8499. } catch (err) {
  8500. showToast('Error', err.message, 'error');
  8501. }
  8502. }
  8503. function applyOspfTemplateForm() {
  8504. submitOspfTemplate(null);
  8505. }
  8506. function copyOspfTemplate() {
  8507. document.getElementById('modal-ospf-tmpl-id').value = '';
  8508. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  8509. showToast('Copied', 'Duplicated as new template', 'info');
  8510. }
  8511. async function deleteCurrentOspfTemplate() {
  8512. const id = document.getElementById('modal-ospf-tmpl-id').value;
  8513. if (!id) return;
  8514. if (!confirm('Delete this interface template?')) return;
  8515. try {
  8516. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8517. closeOspfTemplateModal();
  8518. showToast('Removed', 'Interface template deleted', 'success');
  8519. loadDynamicRouting();
  8520. } catch (err) {
  8521. showToast('Error', err.message, 'error');
  8522. }
  8523. }
  8524. async function enableSelectedOspfTemplate() {
  8525. const id = state.selectedOspfRow?.templates;
  8526. if (!id) return;
  8527. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8528. method: 'POST',
  8529. headers: { 'Content-Type': 'application/json' },
  8530. body: JSON.stringify({ disabled: false })
  8531. });
  8532. loadDynamicRouting();
  8533. }
  8534. async function disableSelectedOspfTemplate() {
  8535. const id = state.selectedOspfRow?.templates;
  8536. if (!id) return;
  8537. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8538. method: 'POST',
  8539. headers: { 'Content-Type': 'application/json' },
  8540. body: JSON.stringify({ disabled: true })
  8541. });
  8542. loadDynamicRouting();
  8543. }
  8544. async function removeSelectedOspfTemplate() {
  8545. const id = state.selectedOspfRow?.templates;
  8546. if (!id) return;
  8547. if (!confirm('Delete selected interface template?')) return;
  8548. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8549. loadDynamicRouting();
  8550. }
  8551. async function promptCommentOspfTemplate() {
  8552. const id = state.selectedOspfRow?.templates;
  8553. if (!id) return;
  8554. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  8555. if (!tmpl) return;
  8556. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  8557. if (comment === null) return;
  8558. tmpl.comment = comment;
  8559. await fetch(`${API_BASE}/routing/ospf/templates`, {
  8560. method: 'POST',
  8561. headers: { 'Content-Type': 'application/json' },
  8562. body: JSON.stringify(tmpl)
  8563. });
  8564. loadDynamicRouting();
  8565. }
  8566. // --- 5. OSPF STATIC NEIGHBOR ---
  8567. function populateStaticNbrAreaDropdowns() {
  8568. const select = document.getElementById('modal-ospf-snbr-area');
  8569. if (select) {
  8570. const cur = select.value;
  8571. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8572. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8573. if (cur) select.value = cur;
  8574. }
  8575. }
  8576. function openOspfStaticNbrModal(id = null) {
  8577. const isEdit = !!id;
  8578. populateStaticNbrAreaDropdowns();
  8579. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  8580. id: '',
  8581. address: '',
  8582. area: 'Default',
  8583. poll_interval: 120,
  8584. cost: 1,
  8585. disabled: false,
  8586. comment: ''
  8587. };
  8588. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  8589. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  8590. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  8591. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  8592. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  8593. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  8594. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  8595. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  8596. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  8597. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8598. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  8599. }
  8600. function openEditOspfStaticNbrModal(id) {
  8601. openOspfStaticNbrModal(id);
  8602. }
  8603. function closeOspfStaticNbrModal() {
  8604. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  8605. }
  8606. async function submitOspfStaticNbr(e) {
  8607. if (e) e.preventDefault();
  8608. const payload = {
  8609. id: document.getElementById('modal-ospf-snbr-id').value,
  8610. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  8611. area: document.getElementById('modal-ospf-snbr-area').value,
  8612. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  8613. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  8614. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  8615. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  8616. };
  8617. try {
  8618. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  8619. method: 'POST',
  8620. headers: { 'Content-Type': 'application/json' },
  8621. body: JSON.stringify(payload)
  8622. });
  8623. if (res.ok) {
  8624. closeOspfStaticNbrModal();
  8625. showToast('Saved', 'Static neighbor saved', 'success');
  8626. loadDynamicRouting();
  8627. } else {
  8628. const err = await res.json();
  8629. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  8630. }
  8631. } catch (err) {
  8632. showToast('Error', err.message, 'error');
  8633. }
  8634. }
  8635. function applyOspfStaticNbrForm() {
  8636. submitOspfStaticNbr(null);
  8637. }
  8638. async function deleteCurrentOspfStaticNbr() {
  8639. const id = document.getElementById('modal-ospf-snbr-id').value;
  8640. if (!id) return;
  8641. if (!confirm('Delete this static neighbor?')) return;
  8642. try {
  8643. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8644. closeOspfStaticNbrModal();
  8645. showToast('Removed', 'Static neighbor removed', 'success');
  8646. loadDynamicRouting();
  8647. } catch (err) {
  8648. showToast('Error', err.message, 'error');
  8649. }
  8650. }
  8651. async function enableSelectedOspfStaticNbr() {
  8652. const id = state.selectedOspfRow?.['static-nbrs'];
  8653. if (!id) return;
  8654. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8655. if (!n) return;
  8656. n.disabled = false;
  8657. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8658. loadDynamicRouting();
  8659. }
  8660. async function disableSelectedOspfStaticNbr() {
  8661. const id = state.selectedOspfRow?.['static-nbrs'];
  8662. if (!id) return;
  8663. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8664. if (!n) return;
  8665. n.disabled = true;
  8666. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8667. loadDynamicRouting();
  8668. }
  8669. async function removeSelectedOspfStaticNbr() {
  8670. const id = state.selectedOspfRow?.['static-nbrs'];
  8671. if (!id) return;
  8672. if (!confirm('Delete selected static neighbor?')) return;
  8673. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8674. loadDynamicRouting();
  8675. }
  8676. async function promptCommentOspfStaticNbr() {
  8677. const id = state.selectedOspfRow?.['static-nbrs'];
  8678. if (!id) return;
  8679. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8680. if (!n) return;
  8681. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  8682. if (comment === null) return;
  8683. n.comment = comment;
  8684. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8685. loadDynamicRouting();
  8686. }
  8687. // Backward-compat aliases
  8688. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  8689. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  8690. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  8691. function submitOspfInterface(e) { submitOspfTemplate(e); }
  8692. function deleteOspfInterface(id) {
  8693. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  8694. }
  8695. function toggleOspfInterfaceState(id, disabled) {
  8696. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8697. method: 'POST',
  8698. headers: { 'Content-Type': 'application/json' },
  8699. body: JSON.stringify({ disabled })
  8700. }).then(() => loadDynamicRouting());
  8701. }
  8702. function openAddOspfAreaModal() { openOspfAreaModal(); }
  8703. function deleteOspfArea(id) {
  8704. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  8705. }
  8706. // ============================================================================
  8707. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  8708. // ============================================================================
  8709. function switchBridgeSubTab(tab) {
  8710. state.bridgeSubTab = tab;
  8711. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  8712. tabs.forEach(t => {
  8713. const panel = document.getElementById(`bridge-subtab-${t}`);
  8714. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  8715. if (panel) {
  8716. if (t === tab) panel.classList.remove('hidden');
  8717. else panel.classList.add('hidden');
  8718. }
  8719. if (btn) {
  8720. if (t === tab) {
  8721. 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';
  8722. } else {
  8723. 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';
  8724. }
  8725. }
  8726. });
  8727. const addBtn = document.getElementById('bridge-top-action-btn');
  8728. if (addBtn) {
  8729. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  8730. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  8731. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  8732. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  8733. }
  8734. if (tab === 'hosts') loadBridgeHosts();
  8735. setTimeout(initTableSorting, 50);
  8736. }
  8737. function openCurrentBridgeModal() {
  8738. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  8739. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  8740. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  8741. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  8742. }
  8743. async function loadBridge() {
  8744. try {
  8745. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  8746. fetch(`${API_BASE}/bridge/bridges`),
  8747. fetch(`${API_BASE}/bridge/ports`),
  8748. fetch(`${API_BASE}/bridge/vlans`),
  8749. fetch(`${API_BASE}/bridge/summary`),
  8750. fetch(`${API_BASE}/vpn/eoip`),
  8751. fetch(`${API_BASE}/vlans`)
  8752. ]);
  8753. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  8754. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  8755. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  8756. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  8757. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  8758. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  8759. // Badges & Stats
  8760. const bBridges = document.getElementById('bridge-badge-bridges');
  8761. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  8762. const bPorts = document.getElementById('bridge-badge-ports');
  8763. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  8764. const bVlans = document.getElementById('bridge-badge-vlans');
  8765. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  8766. const bHosts = document.getElementById('bridge-badge-hosts');
  8767. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  8768. const sBr = document.getElementById('bridge-stat-bridges');
  8769. if (sBr) sBr.innerText = (state.bridges || []).length;
  8770. const sPorts = document.getElementById('bridge-stat-ports');
  8771. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  8772. const sHosts = document.getElementById('bridge-stat-hosts');
  8773. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  8774. renderBridges();
  8775. renderBridgePorts();
  8776. renderBridgeVLANs();
  8777. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  8778. } catch (err) {
  8779. console.error('Failed to load bridge subsystem:', err);
  8780. }
  8781. }
  8782. // ----------------- Bridges -----------------
  8783. function renderBridges() {
  8784. const tbody = document.getElementById('bridge-table-body');
  8785. const empty = document.getElementById('bridge-empty-bridges');
  8786. const countBadge = document.getElementById('bridge-count-badge');
  8787. if (!tbody) return;
  8788. tbody.innerHTML = '';
  8789. const bridges = state.bridges || [];
  8790. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  8791. if (bridges.length === 0) {
  8792. empty?.classList.remove('hidden');
  8793. return;
  8794. }
  8795. empty?.classList.add('hidden');
  8796. bridges.forEach((b, idx) => {
  8797. const tr = document.createElement('tr');
  8798. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  8799. // Format IP addresses pill list
  8800. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  8801. if (b.ip_addresses && b.ip_addresses.length > 0) {
  8802. ipsHtml = b.ip_addresses.map(ip => `
  8803. <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">
  8804. <span>${ip}</span>
  8805. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  8806. </span>
  8807. `).join(' ');
  8808. }
  8809. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  8810. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  8811. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  8812. tr.innerHTML = `
  8813. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  8814. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  8815. <td class="py-2.5 px-3 font-bold text-white text-sm">
  8816. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  8817. </td>
  8818. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  8819. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  8820. <td class="py-2.5 px-3">
  8821. <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>
  8822. </td>
  8823. <td class="py-2.5 px-3 text-center">
  8824. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  8825. </td>
  8826. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  8827. <td class="py-2.5 px-3">
  8828. <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>
  8829. </td>
  8830. <td class="py-2.5 px-3">
  8831. <div class="flex items-center gap-1.5 flex-wrap">
  8832. ${ipsHtml}
  8833. <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>
  8834. </div>
  8835. </td>
  8836. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  8837. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  8838. </td>
  8839. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  8840. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8841. <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>
  8842. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8843. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  8844. </td>
  8845. `;
  8846. tbody.appendChild(tr);
  8847. });
  8848. }
  8849. function openAddBridgeModal() {
  8850. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  8851. document.getElementById('bridge-modal-id').value = '';
  8852. document.getElementById('bridge-modal-name').value = 'bridge1';
  8853. document.getElementById('bridge-modal-name').disabled = false;
  8854. document.getElementById('bridge-modal-mtu').value = '1500';
  8855. document.getElementById('bridge-modal-mac').value = '';
  8856. document.getElementById('bridge-modal-stp').value = 'rstp';
  8857. document.getElementById('bridge-modal-priority').value = '32768';
  8858. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  8859. document.getElementById('bridge-modal-pvid').value = '1';
  8860. document.getElementById('bridge-modal-fastforward').checked = true;
  8861. document.getElementById('bridge-modal-comment').value = '';
  8862. document.getElementById('bridge-modal-disabled').checked = false;
  8863. toggleBridgeModalVlanFiltering();
  8864. document.getElementById('bridge-modal').classList.remove('hidden');
  8865. }
  8866. function openEditBridgeModal(id) {
  8867. const b = (state.bridges || []).find(x => x.id === id);
  8868. if (!b) return;
  8869. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  8870. document.getElementById('bridge-modal-id').value = b.id;
  8871. document.getElementById('bridge-modal-name').value = b.name;
  8872. document.getElementById('bridge-modal-name').disabled = true;
  8873. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  8874. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  8875. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  8876. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  8877. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  8878. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  8879. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  8880. document.getElementById('bridge-modal-comment').value = b.comment || '';
  8881. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  8882. toggleBridgeModalVlanFiltering();
  8883. document.getElementById('bridge-modal').classList.remove('hidden');
  8884. }
  8885. function closeBridgeModal() {
  8886. document.getElementById('bridge-modal').classList.add('hidden');
  8887. }
  8888. function toggleBridgeModalVlanFiltering() {
  8889. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  8890. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  8891. if (pvidBox) {
  8892. if (chk) pvidBox.classList.remove('opacity-40');
  8893. else pvidBox.classList.add('opacity-40');
  8894. }
  8895. }
  8896. async function submitSaveBridge(e) {
  8897. e.preventDefault();
  8898. const id = document.getElementById('bridge-modal-id').value;
  8899. const name = document.getElementById('bridge-modal-name').value.trim();
  8900. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  8901. const mac = document.getElementById('bridge-modal-mac').value.trim();
  8902. const stp = document.getElementById('bridge-modal-stp').value;
  8903. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  8904. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  8905. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  8906. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  8907. const comment = document.getElementById('bridge-modal-comment').value.trim();
  8908. const disabled = document.getElementById('bridge-modal-disabled').checked;
  8909. try {
  8910. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  8911. method: 'POST',
  8912. headers: { 'Content-Type': 'application/json' },
  8913. body: JSON.stringify({
  8914. id,
  8915. name,
  8916. mtu,
  8917. mac_address: mac,
  8918. stp,
  8919. priority,
  8920. vlan_filtering: vlanFiltering,
  8921. pvid,
  8922. fast_forward: fastForward,
  8923. comment,
  8924. disabled
  8925. })
  8926. });
  8927. if (res.ok) {
  8928. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  8929. closeBridgeModal();
  8930. loadBridge();
  8931. fetchData(false);
  8932. } else {
  8933. const err = await res.json();
  8934. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  8935. }
  8936. } catch (err) {
  8937. showToast('Error', err.message, 'error');
  8938. }
  8939. }
  8940. async function toggleBridgeState(id, disabled) {
  8941. try {
  8942. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  8943. method: 'POST',
  8944. headers: { 'Content-Type': 'application/json' },
  8945. body: JSON.stringify({ disabled })
  8946. });
  8947. if (res.ok) {
  8948. loadBridge();
  8949. fetchData(false);
  8950. }
  8951. } catch (err) {
  8952. showToast('Error', err.message, 'error');
  8953. }
  8954. }
  8955. async function deleteBridge(id) {
  8956. const b = (state.bridges || []).find(x => x.id === id);
  8957. const name = b ? b.name : id;
  8958. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  8959. try {
  8960. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8961. if (res.ok) {
  8962. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  8963. loadBridge();
  8964. fetchData(false);
  8965. } else {
  8966. const err = await res.json();
  8967. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  8968. }
  8969. } catch (err) {
  8970. showToast('Error', err.message, 'error');
  8971. }
  8972. }
  8973. // ----------------- Bridge IP Assignments -----------------
  8974. function openAddBridgeIPModal(id, name) {
  8975. document.getElementById('bridge-ip-modal-id').value = id;
  8976. document.getElementById('bridge-ip-modal-sub').innerText = name;
  8977. document.getElementById('bridge-ip-modal-cidr').value = '';
  8978. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  8979. }
  8980. function closeBridgeIPModal() {
  8981. document.getElementById('bridge-ip-modal').classList.add('hidden');
  8982. }
  8983. async function submitAddBridgeIP(e) {
  8984. e.preventDefault();
  8985. const id = document.getElementById('bridge-ip-modal-id').value;
  8986. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  8987. try {
  8988. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  8989. method: 'POST',
  8990. headers: { 'Content-Type': 'application/json' },
  8991. body: JSON.stringify({ ip })
  8992. });
  8993. if (res.ok) {
  8994. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  8995. closeBridgeIPModal();
  8996. loadBridge();
  8997. fetchData(false);
  8998. } else {
  8999. const err = await res.json();
  9000. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  9001. }
  9002. } catch (err) {
  9003. showToast('Error', err.message, 'error');
  9004. }
  9005. }
  9006. async function deleteBridgeIP(id, ip) {
  9007. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  9008. try {
  9009. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9010. method: 'DELETE',
  9011. headers: { 'Content-Type': 'application/json' },
  9012. body: JSON.stringify({ ip })
  9013. });
  9014. if (res.ok) {
  9015. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  9016. loadBridge();
  9017. fetchData(false);
  9018. }
  9019. } catch (err) {
  9020. showToast('Error', err.message, 'error');
  9021. }
  9022. }
  9023. // ----------------- Bridge Ports -----------------
  9024. function renderBridgePorts() {
  9025. const tbody = document.getElementById('bridge-ports-table-body');
  9026. const empty = document.getElementById('bridge-empty-ports');
  9027. const countBadge = document.getElementById('bridge-ports-count-badge');
  9028. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  9029. if (!tbody) return;
  9030. tbody.innerHTML = '';
  9031. // Update filter select
  9032. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  9033. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  9034. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  9035. if (ports.length === 0) {
  9036. empty?.classList.remove('hidden');
  9037. return;
  9038. }
  9039. empty?.classList.add('hidden');
  9040. ports.forEach((p, idx) => {
  9041. const tr = document.createElement('tr');
  9042. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  9043. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9044. tr.innerHTML = `
  9045. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9046. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9047. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9048. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  9049. </td>
  9050. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  9051. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  9052. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  9053. <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>
  9054. <td class="py-2.5 px-3">
  9055. ${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>'}
  9056. </td>
  9057. <td class="py-2.5 px-3">
  9058. <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>
  9059. </td>
  9060. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  9061. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9062. <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>
  9063. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9064. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9065. </td>
  9066. `;
  9067. tbody.appendChild(tr);
  9068. });
  9069. }
  9070. function openAddBridgePortModal() {
  9071. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  9072. document.getElementById('bridge-port-modal-id').value = '';
  9073. populateBridgeSelect('bridge-port-modal-bridge');
  9074. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  9075. document.getElementById('bridge-port-modal-pvid').value = '1';
  9076. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  9077. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  9078. document.getElementById('bridge-port-modal-horizon').value = '0';
  9079. document.getElementById('bridge-port-modal-pathcost').value = '10';
  9080. document.getElementById('bridge-port-modal-priority').value = '128';
  9081. document.getElementById('bridge-port-modal-learn').checked = true;
  9082. document.getElementById('bridge-port-modal-comment').value = '';
  9083. document.getElementById('bridge-port-modal-disabled').checked = false;
  9084. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9085. }
  9086. function openEditBridgePortModal(id) {
  9087. const p = (state.bridgePorts || []).find(x => x.id === id);
  9088. if (!p) return;
  9089. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  9090. document.getElementById('bridge-port-modal-id').value = p.id;
  9091. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  9092. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  9093. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  9094. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  9095. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  9096. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  9097. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  9098. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  9099. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  9100. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  9101. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  9102. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9103. }
  9104. function closeBridgePortModal() {
  9105. document.getElementById('bridge-port-modal').classList.add('hidden');
  9106. }
  9107. async function submitSaveBridgePort(e) {
  9108. e.preventDefault();
  9109. const id = document.getElementById('bridge-port-modal-id').value;
  9110. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  9111. const iface = document.getElementById('bridge-port-modal-interface').value;
  9112. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  9113. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  9114. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  9115. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  9116. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  9117. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  9118. const learn = document.getElementById('bridge-port-modal-learn').checked;
  9119. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  9120. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  9121. try {
  9122. const res = await fetch(`${API_BASE}/bridge/ports`, {
  9123. method: 'POST',
  9124. headers: { 'Content-Type': 'application/json' },
  9125. body: JSON.stringify({
  9126. id,
  9127. bridge,
  9128. interface: iface,
  9129. pvid,
  9130. frame_types: frameTypes,
  9131. ingress_filtering: ingressFiltering,
  9132. horizon,
  9133. path_cost: pathCost,
  9134. priority,
  9135. learn,
  9136. comment,
  9137. disabled
  9138. })
  9139. });
  9140. if (res.ok) {
  9141. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  9142. closeBridgePortModal();
  9143. loadBridge();
  9144. fetchData(false);
  9145. } else {
  9146. const err = await res.json();
  9147. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  9148. }
  9149. } catch (err) {
  9150. showToast('Error', err.message, 'error');
  9151. }
  9152. }
  9153. async function toggleBridgePortState(id, disabled) {
  9154. try {
  9155. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  9156. method: 'POST',
  9157. headers: { 'Content-Type': 'application/json' },
  9158. body: JSON.stringify({ disabled })
  9159. });
  9160. if (res.ok) {
  9161. loadBridge();
  9162. fetchData(false);
  9163. }
  9164. } catch (err) {
  9165. showToast('Error', err.message, 'error');
  9166. }
  9167. }
  9168. async function deleteBridgePort(id) {
  9169. const p = (state.bridgePorts || []).find(x => x.id === id);
  9170. const iface = p ? p.interface : id;
  9171. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  9172. try {
  9173. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9174. if (res.ok) {
  9175. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  9176. loadBridge();
  9177. fetchData(false);
  9178. }
  9179. } catch (err) {
  9180. showToast('Error', err.message, 'error');
  9181. }
  9182. }
  9183. // ----------------- Bridge VLANs -----------------
  9184. function renderBridgeVLANs() {
  9185. const tbody = document.getElementById('bridge-vlans-table-body');
  9186. const empty = document.getElementById('bridge-empty-vlans');
  9187. const countBadge = document.getElementById('bridge-vlans-count-badge');
  9188. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  9189. if (!tbody) return;
  9190. tbody.innerHTML = '';
  9191. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  9192. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  9193. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  9194. if (vlans.length === 0) {
  9195. empty?.classList.remove('hidden');
  9196. return;
  9197. }
  9198. empty?.classList.add('hidden');
  9199. vlans.forEach((v, idx) => {
  9200. const tr = document.createElement('tr');
  9201. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  9202. const taggedHtml = (v.tagged && v.tagged.length > 0)
  9203. ? 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(' ')
  9204. : '<span class="text-slate-600">none</span>';
  9205. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  9206. ? 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(' ')
  9207. : '<span class="text-slate-600">none</span>';
  9208. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9209. tr.innerHTML = `
  9210. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9211. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9212. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  9213. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  9214. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  9215. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  9216. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  9217. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9218. <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>
  9219. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9220. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9221. </td>
  9222. `;
  9223. tbody.appendChild(tr);
  9224. });
  9225. }
  9226. function openAddBridgeVLANModal() {
  9227. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  9228. document.getElementById('bridge-vlan-modal-id').value = '';
  9229. populateBridgeSelect('bridge-vlan-modal-bridge');
  9230. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  9231. document.getElementById('bridge-vlan-modal-comment').value = '';
  9232. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  9233. updateBridgeVlanPortCheckboxes();
  9234. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  9235. }
  9236. function openEditBridgeVLANModal(id) {
  9237. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  9238. if (!v) return;
  9239. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  9240. document.getElementById('bridge-vlan-modal-id').value = v.id;
  9241. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  9242. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  9243. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  9244. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  9245. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  9246. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  9247. }
  9248. function closeBridgeVlanModal() {
  9249. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  9250. }
  9251. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  9252. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  9253. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  9254. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  9255. if (!taggedBox || !untaggedBox) return;
  9256. // Ports belonging to the selected bridge
  9257. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  9258. if (memberPorts.length === 0) {
  9259. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  9260. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  9261. return;
  9262. }
  9263. taggedBox.innerHTML = memberPorts.map(p => `
  9264. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  9265. <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">
  9266. <span>${p.interface}</span>
  9267. </label>
  9268. `).join('');
  9269. untaggedBox.innerHTML = memberPorts.map(p => `
  9270. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  9271. <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">
  9272. <span>${p.interface}</span>
  9273. </label>
  9274. `).join('');
  9275. }
  9276. async function submitSaveBridgeVLAN(e) {
  9277. e.preventDefault();
  9278. const id = document.getElementById('bridge-vlan-modal-id').value;
  9279. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  9280. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  9281. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  9282. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  9283. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  9284. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  9285. try {
  9286. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  9287. method: 'POST',
  9288. headers: { 'Content-Type': 'application/json' },
  9289. body: JSON.stringify({
  9290. id,
  9291. bridge,
  9292. vlan_ids: vlanIDs,
  9293. tagged,
  9294. untagged,
  9295. comment,
  9296. disabled
  9297. })
  9298. });
  9299. if (res.ok) {
  9300. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  9301. closeBridgeVlanModal();
  9302. loadBridge();
  9303. } else {
  9304. const err = await res.json();
  9305. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  9306. }
  9307. } catch (err) {
  9308. showToast('Error', err.message, 'error');
  9309. }
  9310. }
  9311. async function toggleBridgeVLANState(id, disabled) {
  9312. try {
  9313. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  9314. method: 'POST',
  9315. headers: { 'Content-Type': 'application/json' },
  9316. body: JSON.stringify({ disabled })
  9317. });
  9318. if (res.ok) loadBridge();
  9319. } catch (err) {
  9320. showToast('Error', err.message, 'error');
  9321. }
  9322. }
  9323. async function deleteBridgeVLAN(id) {
  9324. if (!confirm('Delete this bridge VLAN entry?')) return;
  9325. try {
  9326. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9327. if (res.ok) {
  9328. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  9329. loadBridge();
  9330. }
  9331. } catch (err) {
  9332. showToast('Error', err.message, 'error');
  9333. }
  9334. }
  9335. // ----------------- Hosts / MAC Table -----------------
  9336. async function loadBridgeHosts() {
  9337. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  9338. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  9339. try {
  9340. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  9341. const res = await fetch(url);
  9342. if (res.ok) {
  9343. state.bridgeHosts = await res.json();
  9344. renderBridgeHosts();
  9345. }
  9346. } catch (err) {
  9347. console.error('Failed to load bridge hosts:', err);
  9348. }
  9349. }
  9350. function renderBridgeHosts() {
  9351. const tbody = document.getElementById('bridge-hosts-table-body');
  9352. const empty = document.getElementById('bridge-empty-hosts');
  9353. const countBadge = document.getElementById('bridge-hosts-count-badge');
  9354. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  9355. if (!tbody) return;
  9356. tbody.innerHTML = '';
  9357. const hosts = (state.bridgeHosts || []).filter(h => {
  9358. if (!search) return true;
  9359. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  9360. });
  9361. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  9362. if (hosts.length === 0) {
  9363. empty?.classList.remove('hidden');
  9364. return;
  9365. }
  9366. empty?.classList.add('hidden');
  9367. hosts.forEach(h => {
  9368. const tr = document.createElement('tr');
  9369. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  9370. let flagBadges = '';
  9371. 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>';
  9372. 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>';
  9373. 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>';
  9374. tr.innerHTML = `
  9375. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  9376. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  9377. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  9378. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  9379. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  9380. <td class="py-2.5 px-3">${flagBadges}</td>
  9381. `;
  9382. tbody.appendChild(tr);
  9383. });
  9384. }
  9385. async function flushBridgeHosts() {
  9386. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  9387. if (!selBridge) {
  9388. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  9389. return;
  9390. }
  9391. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  9392. try {
  9393. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  9394. method: 'POST',
  9395. headers: { 'Content-Type': 'application/json' },
  9396. body: JSON.stringify({ bridge: selBridge })
  9397. });
  9398. if (res.ok) {
  9399. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  9400. loadBridgeHosts();
  9401. }
  9402. } catch (err) {
  9403. showToast('Error', err.message, 'error');
  9404. }
  9405. }
  9406. // ----------------- Helpers -----------------
  9407. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  9408. const sel = document.getElementById(selectId);
  9409. if (!sel) return;
  9410. const prevVal = currentVal || sel.value;
  9411. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  9412. (state.bridges || []).forEach(b => {
  9413. const opt = document.createElement('option');
  9414. opt.value = b.name;
  9415. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  9416. if (b.name === prevVal) opt.selected = true;
  9417. sel.appendChild(opt);
  9418. });
  9419. }
  9420. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  9421. const sel = document.getElementById(selectId);
  9422. if (!sel) return;
  9423. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  9424. // 1. Physical Interfaces
  9425. const grpPhys = document.createElement('optgroup');
  9426. grpPhys.label = 'Physical Interfaces';
  9427. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  9428. const opt = document.createElement('option');
  9429. opt.value = i.name;
  9430. opt.innerText = `${i.name} (${i.role || i.type})`;
  9431. if (i.name === currentVal) opt.selected = true;
  9432. grpPhys.appendChild(opt);
  9433. });
  9434. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  9435. // 2. VLAN Sub-interfaces
  9436. const grpVlans = document.createElement('optgroup');
  9437. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  9438. (state.vlans || []).forEach(v => {
  9439. const opt = document.createElement('option');
  9440. opt.value = v.name;
  9441. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  9442. if (v.name === currentVal) opt.selected = true;
  9443. grpVlans.appendChild(opt);
  9444. });
  9445. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  9446. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  9447. const grpEoip = document.createElement('optgroup');
  9448. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  9449. (state.eoipTunnels || []).forEach(t => {
  9450. const opt = document.createElement('option');
  9451. opt.value = t.name;
  9452. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  9453. if (t.name === currentVal) opt.selected = true;
  9454. grpEoip.appendChild(opt);
  9455. });
  9456. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  9457. }
  9458. // -------------------------------------------------------------
  9459. // RouterOS v7 Routing Filters Management (/routing filter)
  9460. // -------------------------------------------------------------
  9461. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  9462. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  9463. if (!state.rfSort) state.rfSort = {};
  9464. function switchRoutingFilterTab(tab) {
  9465. state.activeRoutingFilterTab = tab;
  9466. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  9467. tabs.forEach(t => {
  9468. const btn = document.getElementById(`tab-rf-${t}`);
  9469. const content = document.getElementById(`tab-content-rf-${t}`);
  9470. if (btn) {
  9471. if (t === tab) {
  9472. btn.className = 'px-3 py-1 text-xs font-semibold rounded bg-emerald-600/20 text-emerald-300 border border-emerald-500/30 transition shadow-sm';
  9473. } else {
  9474. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  9475. }
  9476. }
  9477. if (content) {
  9478. if (t === tab) content.classList.remove('hidden');
  9479. else content.classList.add('hidden');
  9480. }
  9481. });
  9482. const chainContainer = document.getElementById('rf-chain-filter-container');
  9483. if (chainContainer) {
  9484. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  9485. else chainContainer.classList.add('hidden');
  9486. }
  9487. renderRoutingFilters();
  9488. }
  9489. function selectFilterRow(tab, id) {
  9490. if (state.selectedFilterRow[tab] === id) {
  9491. delete state.selectedFilterRow[tab];
  9492. } else {
  9493. state.selectedFilterRow[tab] = id;
  9494. }
  9495. if (tab === 'rules') renderRoutingFilterRules();
  9496. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  9497. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  9498. else if (tab === 'as-lists') renderRoutingFilterASLists();
  9499. }
  9500. function openRoutingFilterNewModal() {
  9501. const tab = state.activeRoutingFilterTab || 'rules';
  9502. if (tab === 'rules') openAddRoutingFilterModal();
  9503. else if (tab === 'select-rules') openAddSelectRuleModal();
  9504. else if (tab === 'community-lists') openAddCommunityListModal();
  9505. else if (tab === 'as-lists') openAddASListModal();
  9506. }
  9507. function toggleSelectedRoutingFilter(disabled) {
  9508. const tab = state.activeRoutingFilterTab || 'rules';
  9509. const id = state.selectedFilterRow[tab];
  9510. if (!id) {
  9511. showToast('Select Row', 'Please click on a row to select it first', 'info');
  9512. return;
  9513. }
  9514. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  9515. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  9516. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  9517. else if (tab === 'as-lists') toggleASListState(id, disabled);
  9518. }
  9519. function removeSelectedRoutingFilter() {
  9520. const tab = state.activeRoutingFilterTab || 'rules';
  9521. const id = state.selectedFilterRow[tab];
  9522. if (!id) {
  9523. showToast('Select Row', 'Please click on a row to select it first', 'info');
  9524. return;
  9525. }
  9526. if (tab === 'rules') deleteRoutingFilter(id);
  9527. else if (tab === 'select-rules') deleteSelectRule(id);
  9528. else if (tab === 'community-lists') deleteCommunityList(id);
  9529. else if (tab === 'as-lists') deleteASList(id);
  9530. }
  9531. function searchRoutingFilters(q) {
  9532. state.rfSearchQuery = (q || '').trim().toLowerCase();
  9533. renderRoutingFilters();
  9534. }
  9535. function sortFilterTable(tab, col) {
  9536. if (!state.rfSort) state.rfSort = {};
  9537. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  9538. if (state.rfSort[tab].col === col) {
  9539. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  9540. } else {
  9541. state.rfSort[tab].col = col;
  9542. state.rfSort[tab].asc = true;
  9543. }
  9544. const asc = state.rfSort[tab].asc;
  9545. let list = [];
  9546. if (tab === 'rules') list = state.routingFilters || [];
  9547. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  9548. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  9549. else if (tab === 'as-lists') list = state.routingASLists || [];
  9550. list.sort((a, b) => {
  9551. let valA = a[col] ?? '';
  9552. let valB = b[col] ?? '';
  9553. if (col === 'flags') {
  9554. valA = a.disabled ? 'X' : 'A';
  9555. valB = b.disabled ? 'X' : 'A';
  9556. }
  9557. if (typeof valA === 'number' && typeof valB === 'number') {
  9558. return asc ? valA - valB : valB - valA;
  9559. }
  9560. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  9561. });
  9562. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  9563. allCols.forEach(c => {
  9564. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  9565. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  9566. });
  9567. if (tab === 'rules') renderRoutingFilterRules();
  9568. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  9569. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  9570. else if (tab === 'as-lists') renderRoutingFilterASLists();
  9571. }
  9572. function renderRoutingFilters() {
  9573. const navBadge = document.getElementById('badge-filters-count');
  9574. const allRules = state.routingFilters || [];
  9575. if (navBadge) navBadge.innerText = allRules.length;
  9576. // Populate chain filter select options and datalist
  9577. const chainSelect = document.getElementById('routing-filter-chain-select');
  9578. const chainDatalist = document.getElementById('dl-routing-chains');
  9579. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  9580. if (chainSelect) {
  9581. const currentVal = state.filterChainSelected || 'all';
  9582. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  9583. uniqueChains.map(ch => {
  9584. const count = allRules.filter(r => r.chain === ch).length;
  9585. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  9586. }).join('');
  9587. chainSelect.value = currentVal;
  9588. }
  9589. if (chainDatalist) {
  9590. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  9591. }
  9592. renderRoutingFilterRules();
  9593. renderRoutingFilterSelectRules();
  9594. renderRoutingFilterCommunityLists();
  9595. renderRoutingFilterASLists();
  9596. }
  9597. function filterRoutingFiltersByChain(chain) {
  9598. state.filterChainSelected = chain;
  9599. renderRoutingFilters();
  9600. }
  9601. // -------------------------------------------------------------
  9602. // TAB 1: RULES (/routing filter rule)
  9603. // -------------------------------------------------------------
  9604. function renderRoutingFilterRules() {
  9605. const tbody = document.getElementById('routing-filter-rules-tbody');
  9606. if (!tbody) return;
  9607. const empty = document.getElementById('rf-rules-empty');
  9608. const statusCount = document.getElementById('rf-status-count');
  9609. let list = (state.routingFilters || []).slice();
  9610. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  9611. list = list.filter(r => r.chain === state.filterChainSelected);
  9612. }
  9613. const q = state.rfSearchQuery;
  9614. if (q) {
  9615. list = list.filter(r =>
  9616. (r.chain && r.chain.toLowerCase().includes(q)) ||
  9617. (r.rule && r.rule.toLowerCase().includes(q)) ||
  9618. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  9619. (r.comment && r.comment.toLowerCase().includes(q))
  9620. );
  9621. }
  9622. if (!state.rfSort?.['rules']) {
  9623. list.sort((a, b) => {
  9624. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  9625. return (a.rule_order || 0) - (b.rule_order || 0);
  9626. });
  9627. }
  9628. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  9629. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9630. }
  9631. if (list.length === 0) {
  9632. tbody.innerHTML = '';
  9633. if (empty) empty.classList.remove('hidden');
  9634. return;
  9635. }
  9636. if (empty) empty.classList.add('hidden');
  9637. tbody.innerHTML = list.map(r => {
  9638. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  9639. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  9640. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9641. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  9642. let ruleDisplay = '';
  9643. if (r.rule && r.rule.trim() !== '') {
  9644. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  9645. } else {
  9646. let conds = [];
  9647. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  9648. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  9649. let act = r.action || 'accept';
  9650. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  9651. }
  9652. return `
  9653. <tr onclick="selectFilterRow('rules', '${r.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  9654. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  9655. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  9656. <td class="py-2 px-3">
  9657. <span class="px-2 py-0.5 rounded text-[11px] font-mono bg-slate-800 text-cyan-300 border border-slate-700 font-semibold">${escapeHtml(r.chain)}</span>
  9658. </td>
  9659. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  9660. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  9661. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9662. <button onclick="moveRoutingFilterOrder('${r.id}', -1)" title="Move Up" class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700">▲</button>
  9663. <button onclick="moveRoutingFilterOrder('${r.id}', 1)" title="Move Down" class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700">▼</button>
  9664. <button onclick="toggleRoutingFilterState('${r.id}', ${!r.disabled})" class="px-2 py-0.5 rounded text-[10px] ${r.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  9665. ${r.disabled ? 'Enable' : 'Disable'}
  9666. </button>
  9667. <button onclick="openEditRoutingFilterModal('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  9668. Edit
  9669. </button>
  9670. <button onclick="deleteRoutingFilter('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  9671. ✕
  9672. </button>
  9673. </td>
  9674. </tr>
  9675. `;
  9676. }).join('');
  9677. }
  9678. // -------------------------------------------------------------
  9679. // TAB 2: SELECT RULES (/routing filter select-rule)
  9680. // -------------------------------------------------------------
  9681. function renderRoutingFilterSelectRules() {
  9682. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  9683. if (!tbody) return;
  9684. const empty = document.getElementById('rf-select-rules-empty');
  9685. const statusCount = document.getElementById('rf-status-count');
  9686. let list = (state.routingSelectRules || []).slice();
  9687. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  9688. list = list.filter(r => r.chain === state.filterChainSelected);
  9689. }
  9690. const q = state.rfSearchQuery;
  9691. if (q) {
  9692. list = list.filter(r =>
  9693. (r.chain && r.chain.toLowerCase().includes(q)) ||
  9694. (r.rule && r.rule.toLowerCase().includes(q)) ||
  9695. (r.comment && r.comment.toLowerCase().includes(q))
  9696. );
  9697. }
  9698. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  9699. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9700. }
  9701. if (list.length === 0) {
  9702. tbody.innerHTML = '';
  9703. if (empty) empty.classList.remove('hidden');
  9704. return;
  9705. }
  9706. if (empty) empty.classList.add('hidden');
  9707. tbody.innerHTML = list.map(r => {
  9708. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  9709. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9710. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9711. return `
  9712. <tr onclick="selectFilterRow('select-rules', '${r.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  9713. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9714. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  9715. <td class="py-2 px-3">
  9716. <span class="px-2 py-0.5 rounded text-[11px] font-mono bg-slate-800 text-cyan-300 border border-slate-700 font-semibold">${escapeHtml(r.chain)}</span>
  9717. </td>
  9718. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  9719. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  9720. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9721. <button onclick="toggleSelectRuleState('${r.id}', ${!r.disabled})" class="px-2 py-0.5 rounded text-[10px] ${r.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  9722. ${r.disabled ? 'Enable' : 'Disable'}
  9723. </button>
  9724. <button onclick="openEditSelectRuleModal('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  9725. Edit
  9726. </button>
  9727. <button onclick="deleteSelectRule('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  9728. ✕
  9729. </button>
  9730. </td>
  9731. </tr>
  9732. `;
  9733. }).join('');
  9734. }
  9735. // -------------------------------------------------------------
  9736. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  9737. // -------------------------------------------------------------
  9738. function renderRoutingFilterCommunityLists() {
  9739. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  9740. if (!tbody) return;
  9741. const empty = document.getElementById('rf-comm-lists-empty');
  9742. const statusCount = document.getElementById('rf-status-count');
  9743. let list = (state.routingCommunityLists || []).slice();
  9744. const q = state.rfSearchQuery;
  9745. if (q) {
  9746. list = list.filter(cl =>
  9747. (cl.name && cl.name.toLowerCase().includes(q)) ||
  9748. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  9749. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  9750. );
  9751. }
  9752. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  9753. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9754. }
  9755. if (list.length === 0) {
  9756. tbody.innerHTML = '';
  9757. if (empty) empty.classList.remove('hidden');
  9758. return;
  9759. }
  9760. if (empty) empty.classList.add('hidden');
  9761. tbody.innerHTML = list.map(cl => {
  9762. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  9763. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9764. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9765. const commBadges = (cl.communities || []).map(c =>
  9766. `<span class="px-1.5 py-0.5 rounded text-[10px] bg-indigo-950 text-indigo-300 border border-indigo-800/40 font-mono">${escapeHtml(c)}</span>`
  9767. ).join(' ');
  9768. return `
  9769. <tr onclick="selectFilterRow('community-lists', '${cl.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  9770. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9771. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  9772. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  9773. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  9774. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  9775. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9776. <button onclick="toggleCommunityListState('${cl.id}', ${!cl.disabled})" class="px-2 py-0.5 rounded text-[10px] ${cl.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'}">
  9777. ${cl.disabled ? 'Enable' : 'Disable'}
  9778. </button>
  9779. <button onclick="openEditCommunityListModal('${cl.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  9780. Edit
  9781. </button>
  9782. <button onclick="deleteCommunityList('${cl.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  9783. ✕
  9784. </button>
  9785. </td>
  9786. </tr>
  9787. `;
  9788. }).join('');
  9789. }
  9790. // -------------------------------------------------------------
  9791. // TAB 4: AS LISTS (/routing filter num-list)
  9792. // -------------------------------------------------------------
  9793. function renderRoutingFilterASLists() {
  9794. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  9795. if (!tbody) return;
  9796. const empty = document.getElementById('rf-as-lists-empty');
  9797. const statusCount = document.getElementById('rf-status-count');
  9798. let list = (state.routingASLists || []).slice();
  9799. const q = state.rfSearchQuery;
  9800. if (q) {
  9801. list = list.filter(al =>
  9802. (al.name && al.name.toLowerCase().includes(q)) ||
  9803. (al.range && al.range.toLowerCase().includes(q)) ||
  9804. (al.comment && al.comment.toLowerCase().includes(q))
  9805. );
  9806. }
  9807. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  9808. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9809. }
  9810. if (list.length === 0) {
  9811. tbody.innerHTML = '';
  9812. if (empty) empty.classList.remove('hidden');
  9813. return;
  9814. }
  9815. if (empty) empty.classList.add('hidden');
  9816. tbody.innerHTML = list.map(al => {
  9817. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  9818. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9819. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9820. return `
  9821. <tr onclick="selectFilterRow('as-lists', '${al.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  9822. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9823. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  9824. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  9825. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  9826. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9827. <button onclick="toggleASListState('${al.id}', ${!al.disabled})" class="px-2 py-0.5 rounded text-[10px] ${al.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'}">
  9828. ${al.disabled ? 'Enable' : 'Disable'}
  9829. </button>
  9830. <button onclick="openEditASListModal('${al.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  9831. Edit
  9832. </button>
  9833. <button onclick="deleteASList('${al.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  9834. ✕
  9835. </button>
  9836. </td>
  9837. </tr>
  9838. `;
  9839. }).join('');
  9840. }
  9841. // -------------------------------------------------------------
  9842. // SNIPPETS & WIZARD HELPERS
  9843. // -------------------------------------------------------------
  9844. function insertRuleSnippet(type) {
  9845. const textarea = document.getElementById('modal-rf-rule');
  9846. if (!textarea) return;
  9847. let snippet = '';
  9848. switch (type) {
  9849. case 'accept-default':
  9850. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  9851. break;
  9852. case 'drop-rfc1918':
  9853. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  9854. break;
  9855. case 'len-24':
  9856. snippet = 'if (dst-len > 24) { reject; }';
  9857. break;
  9858. case 'local-pref-150':
  9859. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  9860. break;
  9861. case 'as-prepend-2':
  9862. snippet = 'set bgp-path-prepend 2; accept;';
  9863. break;
  9864. case 'set-comm':
  9865. snippet = 'set bgp-communities.add 65000:100; accept;';
  9866. break;
  9867. case 'match-comm':
  9868. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  9869. break;
  9870. case 'reject-all':
  9871. snippet = 'reject;';
  9872. break;
  9873. }
  9874. if (!snippet) return;
  9875. if (!textarea.value.trim()) {
  9876. textarea.value = snippet;
  9877. } else {
  9878. textarea.value = textarea.value.trim() + '\n' + snippet;
  9879. }
  9880. }
  9881. function generateScriptFromWizard() {
  9882. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  9883. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  9884. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  9885. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  9886. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  9887. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  9888. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  9889. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  9890. const conds = [];
  9891. if (pfx) {
  9892. if (pfxLen) {
  9893. if (pfxLen.includes('-')) {
  9894. const parts = pfxLen.split('-');
  9895. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  9896. } else {
  9897. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  9898. }
  9899. } else {
  9900. conds.push(`dst in ${pfx}`);
  9901. }
  9902. }
  9903. if (proto && proto !== 'any') {
  9904. conds.push(`protocol ${proto}`);
  9905. }
  9906. if (asp) {
  9907. conds.push(`bgp-as-path "${asp}"`);
  9908. }
  9909. if (comm) {
  9910. conds.push(`bgp-communities includes ${comm}`);
  9911. }
  9912. const actions = [];
  9913. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  9914. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  9915. actions.push(`${act};`);
  9916. let code = '';
  9917. if (conds.length > 0) {
  9918. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  9919. } else {
  9920. code = actions.join(' ');
  9921. }
  9922. const textarea = document.getElementById('modal-rf-rule');
  9923. if (textarea) textarea.value = code;
  9924. }
  9925. // -------------------------------------------------------------
  9926. // MODAL CRUD: RULES (/routing filter rule)
  9927. // -------------------------------------------------------------
  9928. function openAddRoutingFilterModal(defaultChain = '') {
  9929. const form = document.getElementById('routing-filter-form');
  9930. if (form) form.reset();
  9931. const idEl = document.getElementById('modal-rf-id');
  9932. if (idEl) idEl.value = '';
  9933. const titleEl = document.getElementById('modal-rf-title');
  9934. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  9935. const chainEl = document.getElementById('modal-rf-chain');
  9936. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  9937. const orderEl = document.getElementById('modal-rf-order');
  9938. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  9939. const ruleEl = document.getElementById('modal-rf-rule');
  9940. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  9941. const disEl = document.getElementById('modal-rf-disabled');
  9942. if (disEl) disEl.checked = false;
  9943. const modal = document.getElementById('modal-routing-filter');
  9944. if (modal) modal.classList.remove('hidden');
  9945. }
  9946. function openEditRoutingFilterModal(id) {
  9947. const r = (state.routingFilters || []).find(item => item.id === id);
  9948. if (!r) return;
  9949. const idEl = document.getElementById('modal-rf-id');
  9950. if (idEl) idEl.value = r.id;
  9951. const titleEl = document.getElementById('modal-rf-title');
  9952. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  9953. const chainEl = document.getElementById('modal-rf-chain');
  9954. if (chainEl) chainEl.value = r.chain || '';
  9955. const orderEl = document.getElementById('modal-rf-order');
  9956. if (orderEl) orderEl.value = r.rule_order || 10;
  9957. const ruleEl = document.getElementById('modal-rf-rule');
  9958. if (ruleEl) {
  9959. if (r.rule) {
  9960. ruleEl.value = r.rule;
  9961. } else {
  9962. let conds = [];
  9963. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  9964. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  9965. let act = r.action || 'accept';
  9966. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  9967. }
  9968. }
  9969. const comEl = document.getElementById('modal-rf-comment');
  9970. if (comEl) comEl.value = r.comment || '';
  9971. const disEl = document.getElementById('modal-rf-disabled');
  9972. if (disEl) disEl.checked = !!r.disabled;
  9973. const modal = document.getElementById('modal-routing-filter');
  9974. if (modal) modal.classList.remove('hidden');
  9975. }
  9976. function closeRoutingFilterModal() {
  9977. const modal = document.getElementById('modal-routing-filter');
  9978. if (modal) modal.classList.add('hidden');
  9979. }
  9980. async function submitRoutingFilter(e) {
  9981. if (e) e.preventDefault();
  9982. const payload = {
  9983. id: document.getElementById('modal-rf-id').value,
  9984. chain: document.getElementById('modal-rf-chain').value.trim(),
  9985. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  9986. rule: document.getElementById('modal-rf-rule').value.trim(),
  9987. comment: document.getElementById('modal-rf-comment').value.trim(),
  9988. disabled: document.getElementById('modal-rf-disabled').checked
  9989. };
  9990. try {
  9991. const res = await fetch(`${API_BASE}/routing/filters`, {
  9992. method: 'POST',
  9993. headers: { 'Content-Type': 'application/json' },
  9994. body: JSON.stringify(payload)
  9995. });
  9996. if (res.ok) {
  9997. closeRoutingFilterModal();
  9998. showToast('Success', 'Routing filter rule saved', 'success');
  9999. loadDynamicRouting();
  10000. } else {
  10001. const err = await res.json();
  10002. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  10003. }
  10004. } catch (err) {
  10005. showToast('Error', err.message, 'error');
  10006. }
  10007. }
  10008. async function applyRoutingFilterForm() {
  10009. const payload = {
  10010. id: document.getElementById('modal-rf-id').value,
  10011. chain: document.getElementById('modal-rf-chain').value.trim(),
  10012. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10013. rule: document.getElementById('modal-rf-rule').value.trim(),
  10014. comment: document.getElementById('modal-rf-comment').value.trim(),
  10015. disabled: document.getElementById('modal-rf-disabled').checked
  10016. };
  10017. try {
  10018. const res = await fetch(`${API_BASE}/routing/filters`, {
  10019. method: 'POST',
  10020. headers: { 'Content-Type': 'application/json' },
  10021. body: JSON.stringify(payload)
  10022. });
  10023. if (res.ok) {
  10024. const data = await res.json();
  10025. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  10026. showToast('Applied', 'Routing filter configuration applied', 'success');
  10027. loadDynamicRouting();
  10028. } else {
  10029. const err = await res.json();
  10030. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  10031. }
  10032. } catch (err) {
  10033. showToast('Error', err.message, 'error');
  10034. }
  10035. }
  10036. async function moveRoutingFilterOrder(id, delta) {
  10037. const list = state.routingFilters || [];
  10038. const idx = list.findIndex(r => r.id === id);
  10039. if (idx < 0) return;
  10040. const targetIdx = idx + delta;
  10041. if (targetIdx < 0 || targetIdx >= list.length) return;
  10042. const currentOrder = list[idx].rule_order || 10;
  10043. const targetOrder = list[targetIdx].rule_order || 20;
  10044. list[idx].rule_order = targetOrder;
  10045. list[targetIdx].rule_order = currentOrder;
  10046. try {
  10047. await fetch(`${API_BASE}/routing/filters`, {
  10048. method: 'POST',
  10049. headers: { 'Content-Type': 'application/json' },
  10050. body: JSON.stringify(list[idx])
  10051. });
  10052. await fetch(`${API_BASE}/routing/filters`, {
  10053. method: 'POST',
  10054. headers: { 'Content-Type': 'application/json' },
  10055. body: JSON.stringify(list[targetIdx])
  10056. });
  10057. loadDynamicRouting();
  10058. } catch (e) {
  10059. console.error('Reorder error:', e);
  10060. }
  10061. }
  10062. async function deleteRoutingFilter(id) {
  10063. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  10064. try {
  10065. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10066. if (res.ok) {
  10067. showToast('Deleted', 'Routing filter rule removed', 'info');
  10068. loadDynamicRouting();
  10069. } else {
  10070. const err = await res.json();
  10071. showToast('Error', err.error || 'Failed to delete rule', 'error');
  10072. }
  10073. } catch (err) {
  10074. showToast('Error', err.message, 'error');
  10075. }
  10076. }
  10077. async function toggleRoutingFilterState(id, disabled) {
  10078. try {
  10079. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  10080. method: 'POST',
  10081. headers: { 'Content-Type': 'application/json' },
  10082. body: JSON.stringify({ disabled })
  10083. });
  10084. if (res.ok) {
  10085. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10086. loadDynamicRouting();
  10087. } else {
  10088. const err = await res.json();
  10089. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  10090. }
  10091. } catch (err) {
  10092. showToast('Error', err.message, 'error');
  10093. }
  10094. }
  10095. // -------------------------------------------------------------
  10096. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  10097. // -------------------------------------------------------------
  10098. function openAddSelectRuleModal() {
  10099. document.getElementById('modal-rf-sr-id').value = '';
  10100. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  10101. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  10102. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  10103. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  10104. document.getElementById('modal-rf-sr-comment').value = '';
  10105. document.getElementById('modal-rf-sr-disabled').checked = false;
  10106. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10107. }
  10108. function openEditSelectRuleModal(id) {
  10109. const r = (state.routingSelectRules || []).find(item => item.id === id);
  10110. if (!r) return;
  10111. document.getElementById('modal-rf-sr-id').value = r.id;
  10112. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  10113. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  10114. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  10115. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  10116. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  10117. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  10118. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10119. }
  10120. function closeSelectRuleModal() {
  10121. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  10122. }
  10123. async function submitSelectRule(e) {
  10124. e.preventDefault();
  10125. const payload = {
  10126. id: document.getElementById('modal-rf-sr-id').value,
  10127. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  10128. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  10129. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  10130. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  10131. disabled: document.getElementById('modal-rf-sr-disabled').checked
  10132. };
  10133. try {
  10134. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  10135. method: 'POST',
  10136. headers: { 'Content-Type': 'application/json' },
  10137. body: JSON.stringify(payload)
  10138. });
  10139. if (res.ok) {
  10140. closeSelectRuleModal();
  10141. showToast('Success', 'Select rule saved', 'success');
  10142. loadDynamicRouting();
  10143. } else {
  10144. const err = await res.json();
  10145. showToast('Error', err.error || 'Failed to save select rule', 'error');
  10146. }
  10147. } catch (err) {
  10148. showToast('Error', err.message, 'error');
  10149. }
  10150. }
  10151. async function deleteSelectRule(id) {
  10152. if (!confirm('Are you sure you want to delete this select rule?')) return;
  10153. try {
  10154. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10155. if (res.ok) {
  10156. showToast('Deleted', 'Select rule removed', 'info');
  10157. loadDynamicRouting();
  10158. } else {
  10159. const err = await res.json();
  10160. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  10161. }
  10162. } catch (err) {
  10163. showToast('Error', err.message, 'error');
  10164. }
  10165. }
  10166. async function toggleSelectRuleState(id, disabled) {
  10167. try {
  10168. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  10169. method: 'POST',
  10170. headers: { 'Content-Type': 'application/json' },
  10171. body: JSON.stringify({ disabled })
  10172. });
  10173. if (res.ok) {
  10174. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10175. loadDynamicRouting();
  10176. } else {
  10177. const err = await res.json();
  10178. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  10179. }
  10180. } catch (err) {
  10181. showToast('Error', err.message, 'error');
  10182. }
  10183. }
  10184. // -------------------------------------------------------------
  10185. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  10186. // -------------------------------------------------------------
  10187. function openAddCommunityListModal() {
  10188. document.getElementById('modal-rf-cl-id').value = '';
  10189. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  10190. document.getElementById('modal-rf-cl-name').value = '';
  10191. document.getElementById('modal-rf-cl-communities').value = '';
  10192. document.getElementById('modal-rf-cl-regexp').value = '';
  10193. document.getElementById('modal-rf-cl-comment').value = '';
  10194. document.getElementById('modal-rf-cl-disabled').checked = false;
  10195. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  10196. }
  10197. function openEditCommunityListModal(id) {
  10198. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  10199. if (!cl) return;
  10200. document.getElementById('modal-rf-cl-id').value = cl.id;
  10201. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  10202. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  10203. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  10204. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  10205. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  10206. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  10207. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  10208. }
  10209. function closeCommunityListModal() {
  10210. document.getElementById('modal-rf-community-list').classList.add('hidden');
  10211. }
  10212. async function submitCommunityList(e) {
  10213. e.preventDefault();
  10214. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  10215. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  10216. const payload = {
  10217. id: document.getElementById('modal-rf-cl-id').value,
  10218. name: document.getElementById('modal-rf-cl-name').value.trim(),
  10219. communities: comms,
  10220. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  10221. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  10222. disabled: document.getElementById('modal-rf-cl-disabled').checked
  10223. };
  10224. try {
  10225. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  10226. method: 'POST',
  10227. headers: { 'Content-Type': 'application/json' },
  10228. body: JSON.stringify(payload)
  10229. });
  10230. if (res.ok) {
  10231. closeCommunityListModal();
  10232. showToast('Success', 'Community list saved', 'success');
  10233. loadDynamicRouting();
  10234. } else {
  10235. const err = await res.json();
  10236. showToast('Error', err.error || 'Failed to save community list', 'error');
  10237. }
  10238. } catch (err) {
  10239. showToast('Error', err.message, 'error');
  10240. }
  10241. }
  10242. async function deleteCommunityList(id) {
  10243. if (!confirm('Are you sure you want to delete this community list?')) return;
  10244. try {
  10245. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10246. if (res.ok) {
  10247. showToast('Deleted', 'Community list removed', 'info');
  10248. loadDynamicRouting();
  10249. } else {
  10250. const err = await res.json();
  10251. showToast('Error', err.error || 'Failed to delete community list', 'error');
  10252. }
  10253. } catch (err) {
  10254. showToast('Error', err.message, 'error');
  10255. }
  10256. }
  10257. async function toggleCommunityListState(id, disabled) {
  10258. try {
  10259. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  10260. method: 'POST',
  10261. headers: { 'Content-Type': 'application/json' },
  10262. body: JSON.stringify({ disabled })
  10263. });
  10264. if (res.ok) {
  10265. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10266. loadDynamicRouting();
  10267. } else {
  10268. const err = await res.json();
  10269. showToast('Error', err.error || 'Failed to update community list state', 'error');
  10270. }
  10271. } catch (err) {
  10272. showToast('Error', err.message, 'error');
  10273. }
  10274. }
  10275. // -------------------------------------------------------------
  10276. // MODAL CRUD: AS LISTS (/routing filter num-list)
  10277. // -------------------------------------------------------------
  10278. function openAddASListModal() {
  10279. document.getElementById('modal-rf-al-id').value = '';
  10280. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  10281. document.getElementById('modal-rf-al-name').value = '';
  10282. document.getElementById('modal-rf-al-range').value = '';
  10283. document.getElementById('modal-rf-al-comment').value = '';
  10284. document.getElementById('modal-rf-al-disabled').checked = false;
  10285. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  10286. }
  10287. function openEditASListModal(id) {
  10288. const al = (state.routingASLists || []).find(item => item.id === id);
  10289. if (!al) return;
  10290. document.getElementById('modal-rf-al-id').value = al.id;
  10291. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  10292. document.getElementById('modal-rf-al-name').value = al.name || '';
  10293. document.getElementById('modal-rf-al-range').value = al.range || '';
  10294. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  10295. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  10296. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  10297. }
  10298. function closeASListModal() {
  10299. document.getElementById('modal-rf-as-list').classList.add('hidden');
  10300. }
  10301. async function submitASList(e) {
  10302. e.preventDefault();
  10303. const payload = {
  10304. id: document.getElementById('modal-rf-al-id').value,
  10305. name: document.getElementById('modal-rf-al-name').value.trim(),
  10306. range: document.getElementById('modal-rf-al-range').value.trim(),
  10307. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  10308. disabled: document.getElementById('modal-rf-al-disabled').checked
  10309. };
  10310. try {
  10311. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  10312. method: 'POST',
  10313. headers: { 'Content-Type': 'application/json' },
  10314. body: JSON.stringify(payload)
  10315. });
  10316. if (res.ok) {
  10317. closeASListModal();
  10318. showToast('Success', 'AS number list saved', 'success');
  10319. loadDynamicRouting();
  10320. } else {
  10321. const err = await res.json();
  10322. showToast('Error', err.error || 'Failed to save AS list', 'error');
  10323. }
  10324. } catch (err) {
  10325. showToast('Error', err.message, 'error');
  10326. }
  10327. }
  10328. async function deleteASList(id) {
  10329. if (!confirm('Are you sure you want to delete this AS list?')) return;
  10330. try {
  10331. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10332. if (res.ok) {
  10333. showToast('Deleted', 'AS list removed', 'info');
  10334. loadDynamicRouting();
  10335. } else {
  10336. const err = await res.json();
  10337. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  10338. }
  10339. } catch (err) {
  10340. showToast('Error', err.message, 'error');
  10341. }
  10342. }
  10343. async function toggleASListState(id, disabled) {
  10344. try {
  10345. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  10346. method: 'POST',
  10347. headers: { 'Content-Type': 'application/json' },
  10348. body: JSON.stringify({ disabled })
  10349. });
  10350. if (res.ok) {
  10351. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10352. loadDynamicRouting();
  10353. } else {
  10354. const err = await res.json();
  10355. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  10356. }
  10357. } catch (err) {
  10358. showToast('Error', err.message, 'error');
  10359. }
  10360. }
  10361. // ==========================================
  10362. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  10363. // ==========================================
  10364. function loadToolsView() {
  10365. populateToolsInterfaces();
  10366. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  10367. }
  10368. function populateToolsInterfaces() {
  10369. const pingSel = document.getElementById('tools-ping-iface');
  10370. const traceSel = document.getElementById('tools-tr-iface');
  10371. let opts = '<option value="">Auto (Default Route)</option>';
  10372. if (Array.isArray(state.interfaces)) {
  10373. state.interfaces.forEach(iface => {
  10374. if (iface.name) {
  10375. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  10376. }
  10377. });
  10378. }
  10379. if (pingSel) {
  10380. const cur = pingSel.value;
  10381. pingSel.innerHTML = opts;
  10382. if (cur) pingSel.value = cur;
  10383. }
  10384. if (traceSel) {
  10385. const cur = traceSel.value;
  10386. traceSel.innerHTML = opts;
  10387. if (cur) traceSel.value = cur;
  10388. }
  10389. }
  10390. function switchToolsSubTab(subTab) {
  10391. state.activeToolsSubTab = subTab;
  10392. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  10393. tabs.forEach(t => {
  10394. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  10395. const view = document.getElementById(`tools-view-${t}`);
  10396. if (btn) {
  10397. if (t === subTab) {
  10398. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-amber-400 text-amber-300 transition flex items-center gap-2 whitespace-nowrap';
  10399. } else {
  10400. 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';
  10401. }
  10402. }
  10403. if (view) {
  10404. if (t === subTab) {
  10405. view.classList.remove('hidden');
  10406. } else {
  10407. view.classList.add('hidden');
  10408. }
  10409. }
  10410. });
  10411. }
  10412. function setPortPreset(port) {
  10413. const input = document.getElementById('tools-port-num');
  10414. if (input) input.value = port;
  10415. }
  10416. let pingAbortController = null;
  10417. let tracerouteAbortController = null;
  10418. function clearPingTable() {
  10419. const tbody = document.getElementById('tools-ping-tbody');
  10420. if (tbody) tbody.innerHTML = '';
  10421. const rawEl = document.getElementById('tools-ping-raw');
  10422. if (rawEl) rawEl.innerText = '';
  10423. const sentEl = document.getElementById('tools-ping-stat-sent');
  10424. if (sentEl) sentEl.innerText = '0';
  10425. const recvEl = document.getElementById('tools-ping-stat-recv');
  10426. if (recvEl) recvEl.innerText = '0';
  10427. const lossEl = document.getElementById('tools-ping-stat-loss');
  10428. if (lossEl) lossEl.innerText = '0%';
  10429. const avgEl = document.getElementById('tools-ping-stat-avg');
  10430. if (avgEl) avgEl.innerText = '0 ms';
  10431. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  10432. if (minMaxEl) minMaxEl.innerText = '-';
  10433. const badge = document.getElementById('tools-ping-status-badge');
  10434. if (badge) {
  10435. badge.className = '';
  10436. badge.innerText = '';
  10437. }
  10438. }
  10439. function clearTracerouteTable() {
  10440. const tbody = document.getElementById('tools-tr-tbody');
  10441. if (tbody) tbody.innerHTML = '';
  10442. const rawEl = document.getElementById('tools-tr-raw');
  10443. if (rawEl) rawEl.innerText = '';
  10444. const statHops = document.getElementById('tools-tr-hops-count');
  10445. if (statHops) statHops.innerText = '0 Hops';
  10446. }
  10447. function resetPingButton() {
  10448. const btn = document.getElementById('tools-ping-btn');
  10449. const btnText = document.getElementById('tools-ping-btn-text');
  10450. const spinner = document.getElementById('tools-ping-spinner');
  10451. if (btn) {
  10452. btn.disabled = false;
  10453. btn.className = 'px-5 py-2 rounded-lg font-semibold text-xs bg-amber-500 hover:bg-amber-400 text-slate-950 shadow-lg shadow-amber-500/20 transition flex items-center gap-2';
  10454. }
  10455. if (btnText) btnText.innerText = 'Start Ping';
  10456. if (spinner) spinner.classList.add('hidden');
  10457. }
  10458. function setPingRunningButton() {
  10459. const btn = document.getElementById('tools-ping-btn');
  10460. const btnText = document.getElementById('tools-ping-btn-text');
  10461. const spinner = document.getElementById('tools-ping-spinner');
  10462. if (btn) {
  10463. btn.disabled = false;
  10464. btn.className = 'px-5 py-2 rounded-lg font-semibold text-xs bg-rose-600 hover:bg-rose-500 text-white shadow-lg shadow-rose-600/30 transition flex items-center gap-2';
  10465. }
  10466. if (btnText) btnText.innerText = 'Stop Ping';
  10467. if (spinner) spinner.classList.remove('hidden');
  10468. }
  10469. function resetTracerouteButton() {
  10470. const btn = document.getElementById('tools-tr-btn');
  10471. const btnText = document.getElementById('tools-tr-btn-text');
  10472. const spinner = document.getElementById('tools-tr-spinner');
  10473. if (btn) {
  10474. btn.disabled = false;
  10475. btn.className = 'px-5 py-2 rounded-lg font-semibold text-xs bg-amber-500 hover:bg-amber-400 text-slate-950 shadow-lg shadow-amber-500/20 transition flex items-center gap-2';
  10476. }
  10477. if (btnText) btnText.innerText = 'Start Traceroute';
  10478. if (spinner) spinner.classList.add('hidden');
  10479. }
  10480. function setTracerouteRunningButton() {
  10481. const btn = document.getElementById('tools-tr-btn');
  10482. const btnText = document.getElementById('tools-tr-btn-text');
  10483. const spinner = document.getElementById('tools-tr-spinner');
  10484. if (btn) {
  10485. btn.disabled = false;
  10486. btn.className = 'px-5 py-2 rounded-lg font-semibold text-xs bg-rose-600 hover:bg-rose-500 text-white shadow-lg shadow-rose-600/30 transition flex items-center gap-2';
  10487. }
  10488. if (btnText) btnText.innerText = 'Stop Traceroute';
  10489. if (spinner) spinner.classList.remove('hidden');
  10490. }
  10491. async function executePing(e) {
  10492. if (e) e.preventDefault();
  10493. // If already running, clicking the button stops the stream!
  10494. if (pingAbortController) {
  10495. pingAbortController.abort();
  10496. pingAbortController = null;
  10497. resetPingButton();
  10498. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  10499. return;
  10500. }
  10501. const target = document.getElementById('tools-ping-target')?.value?.trim();
  10502. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  10503. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  10504. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  10505. const iface = document.getElementById('tools-ping-iface')?.value || '';
  10506. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  10507. if (!target) {
  10508. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10509. return;
  10510. }
  10511. clearPingTable();
  10512. const resCard = document.getElementById('tools-ping-results');
  10513. if (resCard) resCard.classList.remove('hidden');
  10514. pingAbortController = new AbortController();
  10515. setPingRunningButton();
  10516. try {
  10517. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  10518. method: 'POST',
  10519. headers: { 'Content-Type': 'application/json' },
  10520. body: JSON.stringify({
  10521. target,
  10522. count,
  10523. size,
  10524. timeout,
  10525. interface: iface,
  10526. dont_frag: dontFrag
  10527. }),
  10528. signal: pingAbortController.signal
  10529. });
  10530. if (!res.ok) {
  10531. const errText = await res.text();
  10532. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  10533. resetPingButton();
  10534. pingAbortController = null;
  10535. return;
  10536. }
  10537. const reader = res.body.getReader();
  10538. const decoder = new TextDecoder('utf-8');
  10539. let buffer = '';
  10540. while (true) {
  10541. const { done, value } = await reader.read();
  10542. if (done) break;
  10543. buffer += decoder.decode(value, { stream: true });
  10544. const blocks = buffer.split('\n\n');
  10545. buffer = blocks.pop() || '';
  10546. for (const block of blocks) {
  10547. const trimmed = block.trim();
  10548. if (!trimmed) continue;
  10549. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  10550. try {
  10551. const evt = JSON.parse(line);
  10552. handleLivePingEvent(evt);
  10553. } catch (parseErr) {
  10554. console.warn('Ping SSE parse error:', parseErr, line);
  10555. }
  10556. }
  10557. }
  10558. } catch (err) {
  10559. if (err.name === 'AbortError') {
  10560. // User aborted normally
  10561. } else {
  10562. showToast('Ping Error', err.message, 'error');
  10563. }
  10564. } finally {
  10565. pingAbortController = null;
  10566. resetPingButton();
  10567. }
  10568. }
  10569. function handleLivePingEvent(evt) {
  10570. const sentEl = document.getElementById('tools-ping-stat-sent');
  10571. const recvEl = document.getElementById('tools-ping-stat-recv');
  10572. const lossEl = document.getElementById('tools-ping-stat-loss');
  10573. const avgEl = document.getElementById('tools-ping-stat-avg');
  10574. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  10575. const badge = document.getElementById('tools-ping-status-badge');
  10576. const tbody = document.getElementById('tools-ping-tbody');
  10577. const rawEl = document.getElementById('tools-ping-raw');
  10578. if (evt.raw && rawEl) {
  10579. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  10580. rawEl.scrollTop = rawEl.scrollHeight;
  10581. }
  10582. if (evt.type === 'reply') {
  10583. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10584. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  10585. if (lossEl && evt.packet_loss_pct !== undefined) {
  10586. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10587. lossEl.className = evt.packet_loss_pct === 0
  10588. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  10589. : (evt.packet_loss_pct < 50 ? 'text-base font-bold font-mono text-amber-400 mt-1' : 'text-base font-bold font-mono text-rose-400 mt-1');
  10590. }
  10591. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  10592. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  10593. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  10594. }
  10595. if (badge) {
  10596. if (evt.packet_loss_pct === 0) {
  10597. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-emerald-950 text-emerald-300 border border-emerald-800/60';
  10598. badge.innerText = '100% OK';
  10599. } else {
  10600. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-amber-950 text-amber-300 border border-amber-800/60';
  10601. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  10602. }
  10603. }
  10604. if (tbody) {
  10605. const tr = document.createElement('tr');
  10606. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  10607. tr.innerHTML = `
  10608. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  10609. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  10610. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  10611. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  10612. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  10613. <td class="py-2 px-3 text-right"><span class="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-950 text-emerald-300 border border-emerald-800/60">REPLY</span></td>
  10614. `;
  10615. tbody.appendChild(tr);
  10616. }
  10617. } else if (evt.type === 'timeout') {
  10618. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10619. if (lossEl && evt.packet_loss_pct !== undefined) {
  10620. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10621. lossEl.className = evt.packet_loss_pct < 50 ? 'text-base font-bold font-mono text-amber-400 mt-1' : 'text-base font-bold font-mono text-rose-400 mt-1';
  10622. }
  10623. if (badge) {
  10624. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-rose-950 text-rose-300 border border-rose-800/60';
  10625. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  10626. }
  10627. if (tbody) {
  10628. const tr = document.createElement('tr');
  10629. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  10630. tr.innerHTML = `
  10631. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  10632. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  10633. <td class="py-2 px-3 text-slate-600">--</td>
  10634. <td class="py-2 px-3 text-slate-600">--</td>
  10635. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  10636. <td class="py-2 px-3 text-right"><span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span></td>
  10637. `;
  10638. tbody.appendChild(tr);
  10639. }
  10640. } else if (evt.type === 'unreach') {
  10641. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10642. if (lossEl && evt.packet_loss_pct !== undefined) {
  10643. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10644. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  10645. }
  10646. if (badge) {
  10647. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-rose-950 text-rose-300 border border-rose-800/60';
  10648. badge.innerText = 'UNREACHABLE';
  10649. }
  10650. if (tbody) {
  10651. const tr = document.createElement('tr');
  10652. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  10653. tr.innerHTML = `
  10654. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  10655. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  10656. <td class="py-2 px-3 text-slate-600">--</td>
  10657. <td class="py-2 px-3 text-slate-600">--</td>
  10658. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  10659. <td class="py-2 px-3 text-right"><span class="px-2 py-0.5 rounded text-[10px] font-bold bg-rose-950 text-rose-300 border border-rose-800/60">UNREACH</span></td>
  10660. `;
  10661. tbody.appendChild(tr);
  10662. }
  10663. } else if (evt.type === 'stats') {
  10664. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10665. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  10666. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10667. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  10668. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  10669. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  10670. }
  10671. } else if (evt.type === 'done') {
  10672. showToast('Ping Finished', `Sent ${evt.packets_sent}, received ${evt.packets_recv} (${evt.packet_loss_pct?.toFixed(0)}% loss)`, evt.packet_loss_pct === 0 ? 'success' : 'info');
  10673. }
  10674. }
  10675. async function executeTraceroute(e) {
  10676. if (e) e.preventDefault();
  10677. if (tracerouteAbortController) {
  10678. tracerouteAbortController.abort();
  10679. tracerouteAbortController = null;
  10680. resetTracerouteButton();
  10681. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  10682. return;
  10683. }
  10684. const target = document.getElementById('tools-tr-target')?.value?.trim();
  10685. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  10686. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  10687. const iface = document.getElementById('tools-tr-iface')?.value || '';
  10688. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  10689. if (!target) {
  10690. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10691. return;
  10692. }
  10693. clearTracerouteTable();
  10694. const resCard = document.getElementById('tools-tr-results');
  10695. if (resCard) resCard.classList.remove('hidden');
  10696. tracerouteAbortController = new AbortController();
  10697. setTracerouteRunningButton();
  10698. try {
  10699. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  10700. method: 'POST',
  10701. headers: { 'Content-Type': 'application/json' },
  10702. body: JSON.stringify({
  10703. target,
  10704. max_hops: maxHops,
  10705. protocol,
  10706. interface: iface,
  10707. resolve
  10708. }),
  10709. signal: tracerouteAbortController.signal
  10710. });
  10711. if (!res.ok) {
  10712. const errText = await res.text();
  10713. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  10714. resetTracerouteButton();
  10715. tracerouteAbortController = null;
  10716. return;
  10717. }
  10718. const reader = res.body.getReader();
  10719. const decoder = new TextDecoder('utf-8');
  10720. let buffer = '';
  10721. while (true) {
  10722. const { done, value } = await reader.read();
  10723. if (done) break;
  10724. buffer += decoder.decode(value, { stream: true });
  10725. const blocks = buffer.split('\n\n');
  10726. buffer = blocks.pop() || '';
  10727. for (const block of blocks) {
  10728. const trimmed = block.trim();
  10729. if (!trimmed) continue;
  10730. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  10731. try {
  10732. const evt = JSON.parse(line);
  10733. handleLiveTracerouteEvent(evt);
  10734. } catch (parseErr) {
  10735. console.warn('Traceroute SSE parse error:', parseErr, line);
  10736. }
  10737. }
  10738. }
  10739. } catch (err) {
  10740. if (err.name === 'AbortError') {
  10741. // User aborted normally
  10742. } else {
  10743. showToast('Traceroute Error', err.message, 'error');
  10744. }
  10745. } finally {
  10746. tracerouteAbortController = null;
  10747. resetTracerouteButton();
  10748. }
  10749. }
  10750. function handleLiveTracerouteEvent(evt) {
  10751. const statHops = document.getElementById('tools-tr-hops-count');
  10752. const tbody = document.getElementById('tools-tr-tbody');
  10753. const rawEl = document.getElementById('tools-tr-raw');
  10754. if (evt.raw && rawEl) {
  10755. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  10756. rawEl.scrollTop = rawEl.scrollHeight;
  10757. }
  10758. if (evt.hops_count !== undefined && statHops) {
  10759. statHops.innerText = `${evt.hops_count} Hops`;
  10760. }
  10761. if (evt.type === 'hop' && evt.hop && tbody) {
  10762. const h = evt.hop;
  10763. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  10764. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  10765. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  10766. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  10767. const tr = document.createElement('tr');
  10768. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  10769. tr.innerHTML = `
  10770. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  10771. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  10772. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  10773. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  10774. <td class="py-2.5 px-3 text-right">
  10775. ${isTimeout
  10776. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  10777. : '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-950 text-emerald-300 border border-emerald-800/60">OK</span>'}
  10778. </td>
  10779. `;
  10780. tbody.appendChild(tr);
  10781. } else if (evt.type === 'done') {
  10782. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  10783. }
  10784. }
  10785. async function executeMTR(e) {
  10786. if (e) e.preventDefault();
  10787. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  10788. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  10789. if (!target) {
  10790. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10791. return;
  10792. }
  10793. const btn = document.getElementById('tools-mtr-btn');
  10794. const spinner = document.getElementById('tools-mtr-spinner');
  10795. if (btn) btn.disabled = true;
  10796. if (spinner) spinner.classList.remove('hidden');
  10797. try {
  10798. const res = await fetch(`${API_BASE}/tools/mtr`, {
  10799. method: 'POST',
  10800. headers: { 'Content-Type': 'application/json' },
  10801. body: JSON.stringify({ target, count: cycles })
  10802. });
  10803. const data = await res.json();
  10804. if (!res.ok) {
  10805. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  10806. return;
  10807. }
  10808. const resCard = document.getElementById('tools-mtr-results');
  10809. if (resCard) resCard.classList.remove('hidden');
  10810. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  10811. const statHops = document.getElementById('tools-mtr-hops-count');
  10812. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  10813. const tbody = document.getElementById('tools-mtr-tbody');
  10814. if (tbody) {
  10815. if (hopsCount > 0) {
  10816. tbody.innerHTML = data.hops.map(h => {
  10817. const lossClass = h.loss_pct === 0 ? 'text-emerald-400 font-bold' : (h.loss_pct < 20 ? 'text-amber-400 font-bold' : 'text-rose-400 font-bold');
  10818. return `
  10819. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  10820. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  10821. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  10822. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  10823. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  10824. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  10825. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  10826. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  10827. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  10828. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  10829. </tr>
  10830. `;
  10831. }).join('');
  10832. } else {
  10833. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  10834. }
  10835. }
  10836. const rawEl = document.getElementById('tools-mtr-raw');
  10837. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  10838. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  10839. } catch (err) {
  10840. showToast('MTR Error', err.message, 'error');
  10841. } finally {
  10842. if (btn) btn.disabled = false;
  10843. if (spinner) spinner.classList.add('hidden');
  10844. }
  10845. }
  10846. async function executeDNS(e) {
  10847. if (e) e.preventDefault();
  10848. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  10849. const type = document.getElementById('tools-dns-type')?.value || 'A';
  10850. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  10851. if (!domain) {
  10852. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  10853. return;
  10854. }
  10855. const btn = document.getElementById('tools-dns-btn');
  10856. const spinner = document.getElementById('tools-dns-spinner');
  10857. if (btn) btn.disabled = true;
  10858. if (spinner) spinner.classList.remove('hidden');
  10859. try {
  10860. const res = await fetch(`${API_BASE}/tools/dns`, {
  10861. method: 'POST',
  10862. headers: { 'Content-Type': 'application/json' },
  10863. body: JSON.stringify({ domain, type, server })
  10864. });
  10865. const data = await res.json();
  10866. if (!res.ok) {
  10867. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  10868. return;
  10869. }
  10870. const resCard = document.getElementById('tools-dns-results');
  10871. if (resCard) resCard.classList.remove('hidden');
  10872. const metaEl = document.getElementById('tools-dns-meta');
  10873. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  10874. const tbody = document.getElementById('tools-dns-tbody');
  10875. if (tbody) {
  10876. if (Array.isArray(data.records) && data.records.length > 0) {
  10877. tbody.innerHTML = data.records.map(r => `
  10878. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  10879. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  10880. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  10881. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  10882. <td class="py-2.5 px-3"><span class="px-2 py-0.5 rounded text-[10px] font-bold bg-cyan-950 text-cyan-300 border border-cyan-800/60">${escapeHtml(r.type)}</span></td>
  10883. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  10884. </tr>
  10885. `).join('');
  10886. } else {
  10887. tbody.innerHTML = `<tr><td colspan="5" class="p-4 text-center text-xs text-amber-400 font-mono">No answer records returned for ${escapeHtml(type)} query</td></tr>`;
  10888. }
  10889. }
  10890. const rawEl = document.getElementById('tools-dns-raw');
  10891. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  10892. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  10893. } catch (err) {
  10894. showToast('DNS Error', err.message, 'error');
  10895. } finally {
  10896. if (btn) btn.disabled = false;
  10897. if (spinner) spinner.classList.add('hidden');
  10898. }
  10899. }
  10900. async function executePortProbe(e) {
  10901. if (e) e.preventDefault();
  10902. const target = document.getElementById('tools-port-target')?.value?.trim();
  10903. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  10904. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  10905. if (!target || !port) {
  10906. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  10907. return;
  10908. }
  10909. const btn = document.getElementById('tools-port-btn');
  10910. const spinner = document.getElementById('tools-port-spinner');
  10911. if (btn) btn.disabled = true;
  10912. if (spinner) spinner.classList.remove('hidden');
  10913. try {
  10914. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  10915. method: 'POST',
  10916. headers: { 'Content-Type': 'application/json' },
  10917. body: JSON.stringify({ target, port, timeout })
  10918. });
  10919. const data = await res.json();
  10920. if (!res.ok) {
  10921. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  10922. return;
  10923. }
  10924. const resCard = document.getElementById('tools-port-results');
  10925. if (resCard) resCard.classList.remove('hidden');
  10926. const banner = document.getElementById('tools-port-banner');
  10927. const icon = document.getElementById('tools-port-icon');
  10928. const title = document.getElementById('tools-port-title');
  10929. const sub = document.getElementById('tools-port-sub');
  10930. const latency = document.getElementById('tools-port-latency');
  10931. if (data.open) {
  10932. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  10933. if (icon) {
  10934. icon.className = 'w-8 h-8 rounded-full flex items-center justify-center font-bold text-sm bg-emerald-500/20 text-emerald-400 border border-emerald-500/40';
  10935. icon.innerText = '✓';
  10936. }
  10937. if (title) {
  10938. title.className = 'text-sm font-bold text-emerald-300';
  10939. title.innerText = `PORT ${port} OPEN / LISTENING`;
  10940. }
  10941. if (sub) {
  10942. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  10943. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  10944. }
  10945. if (latency) {
  10946. latency.className = 'text-base font-bold font-mono text-emerald-300';
  10947. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  10948. }
  10949. } else {
  10950. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  10951. if (icon) {
  10952. icon.className = 'w-8 h-8 rounded-full flex items-center justify-center font-bold text-sm bg-rose-500/20 text-rose-400 border border-rose-500/40';
  10953. icon.innerText = '✕';
  10954. }
  10955. if (title) {
  10956. title.className = 'text-sm font-bold text-rose-300';
  10957. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  10958. }
  10959. if (sub) {
  10960. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  10961. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  10962. }
  10963. if (latency) {
  10964. latency.className = 'text-base font-bold font-mono text-slate-500';
  10965. latency.innerText = '--';
  10966. }
  10967. }
  10968. const rawEl = document.getElementById('tools-port-raw');
  10969. if (rawEl) rawEl.innerText = data.raw_output || (data.open ? `Successfully connected to ${target}:${port} in ${data.latency_ms} ms` : `Connection failed: ${data.error || 'timed out or connection refused'}`);
  10970. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  10971. } catch (err) {
  10972. showToast('Probe Error', err.message, 'error');
  10973. } finally {
  10974. if (btn) btn.disabled = false;
  10975. if (spinner) spinner.classList.add('hidden');
  10976. }
  10977. }
  10978. // ==========================================
  10979. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  10980. // ==========================================
  10981. async function loadDHCPClients(showToastMsg = false) {
  10982. try {
  10983. const [clientsRes, sumRes] = await Promise.all([
  10984. fetch(`${API_BASE}/dhcp/clients`),
  10985. fetch(`${API_BASE}/dhcp/clients/summary`)
  10986. ]);
  10987. if (clientsRes.ok) {
  10988. state.dhcpClients = await clientsRes.json();
  10989. }
  10990. if (sumRes.ok) {
  10991. state.dhcpSummary = await sumRes.json();
  10992. }
  10993. renderDHCPClients();
  10994. updateDHCPSummaryCards();
  10995. const bDhcp = document.getElementById('badge-dhcp-client-count');
  10996. if (bDhcp && state.dhcpSummary) {
  10997. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  10998. }
  10999. if (showToastMsg) {
  11000. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  11001. }
  11002. } catch (err) {
  11003. console.error('Failed to load DHCP clients:', err);
  11004. if (showToastMsg) {
  11005. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  11006. }
  11007. }
  11008. }
  11009. function updateDHCPSummaryCards() {
  11010. const sum = state.dhcpSummary || {
  11011. total_clients: (state.dhcpClients || []).length,
  11012. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  11013. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  11014. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  11015. };
  11016. const totalEl = document.getElementById('dhcp-stat-total');
  11017. const boundEl = document.getElementById('dhcp-stat-bound');
  11018. const searchEl = document.getElementById('dhcp-stat-searching');
  11019. const disEl = document.getElementById('dhcp-stat-disabled');
  11020. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  11021. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  11022. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  11023. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  11024. }
  11025. function renderDHCPClients() {
  11026. const tbody = document.getElementById('dhcp-clients-tbody');
  11027. const emptyState = document.getElementById('dhcp-clients-empty');
  11028. if (!tbody) return;
  11029. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  11030. if (clients.length === 0) {
  11031. tbody.innerHTML = '';
  11032. if (emptyState) emptyState.classList.remove('hidden');
  11033. return;
  11034. }
  11035. if (emptyState) emptyState.classList.add('hidden');
  11036. tbody.innerHTML = clients.map(c => {
  11037. let statusBadge = '';
  11038. if (!c.enabled) {
  11039. statusBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>';
  11040. } else if (c.status === 'bound') {
  11041. statusBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-950 text-emerald-300 border border-emerald-800/60 inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>BOUND</span>';
  11042. } else if (c.status === 'searching') {
  11043. statusBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-amber-950 text-amber-300 border border-amber-800/60 inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>SEARCHING...</span>';
  11044. } else if (c.status === 'stopped') {
  11045. statusBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">STOPPED</span>';
  11046. } else {
  11047. statusBadge = `<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-rose-950 text-rose-300 border border-rose-800/60">${escapeHtml((c.status || 'UNKNOWN').toUpperCase())}</span>`;
  11048. }
  11049. const ipDisplay = c.ip_address ? `<span class="font-bold text-white">${escapeHtml(c.ip_address)}</span>` : '<span class="text-slate-500 italic">No lease</span>';
  11050. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  11051. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  11052. const dnsDisplay = (Array.isArray(c.dns_servers) && c.dns_servers.length > 0) ? `<span class="text-cyan-400">${c.dns_servers.map(d => escapeHtml(d)).join(', ')}</span>` : '<span class="text-slate-600">--</span>';
  11053. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  11054. // Option flags
  11055. const flags = [];
  11056. if (c.add_default_route) flags.push('<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 border border-slate-700" title="Add Default Route">+GW</span>');
  11057. if (c.use_peer_dns) flags.push('<span class="px-1.5 py-0.5 rounded text-[10px] bg-cyan-950/60 text-cyan-300 border border-cyan-800/50" title="Use Peer DNS">+DNS</span>');
  11058. if (c.use_peer_ntp) flags.push('<span class="px-1.5 py-0.5 rounded text-[10px] bg-indigo-950/60 text-indigo-300 border border-indigo-800/50" title="Use Peer NTP">+NTP</span>');
  11059. flags.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800/60 text-slate-400" title="Default Route Distance">dist:${c.default_route_distance || 1}</span>`);
  11060. return `
  11061. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  11062. <td class="py-3 px-4">
  11063. <div class="flex items-center gap-2">
  11064. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  11065. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  11066. </div>
  11067. </td>
  11068. <td class="py-3 px-4">${statusBadge}</td>
  11069. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  11070. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  11071. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  11072. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  11073. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  11074. <td class="py-3 px-4">
  11075. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  11076. </td>
  11077. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  11078. ${c.enabled ? `
  11079. <button onclick="renewDHCPClient('${c.id}')" class="px-2 py-1 rounded bg-slate-800 hover:bg-slate-700 text-amber-400 text-xs font-medium border border-slate-700 transition" title="Renew Lease">Renew</button>
  11080. <button onclick="releaseDHCPClient('${c.id}')" class="px-2 py-1 rounded bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs font-medium border border-slate-700 transition" title="Release Lease">Release</button>
  11081. <button onclick="toggleDHCPClientState('${c.id}', false)" class="px-2 py-1 rounded bg-amber-500/10 hover:bg-amber-500/20 text-amber-400 text-xs font-medium border border-amber-500/30 transition" title="Disable DHCP Client">Disable</button>
  11082. ` : `
  11083. <button onclick="toggleDHCPClientState('${c.id}', true)" class="px-2.5 py-1 rounded bg-emerald-500/10 hover:bg-emerald-500/20 text-emerald-400 text-xs font-semibold border border-emerald-500/30 transition" title="Enable DHCP Client">Enable</button>
  11084. `}
  11085. <button onclick="openDHCPClientModal('${c.id}')" class="px-2 py-1 rounded bg-slate-800 hover:bg-slate-700 text-white text-xs font-medium border border-slate-700 transition" title="Edit Settings">Edit</button>
  11086. <button onclick="deleteDHCPClient('${c.id}', '${c.interface}')" class="px-2 py-1 rounded bg-rose-500/10 hover:bg-rose-500/20 text-rose-400 text-xs font-medium border border-rose-500/30 transition" title="Remove Client">✕</button>
  11087. </td>
  11088. </tr>
  11089. `;
  11090. }).join('');
  11091. }
  11092. function openDHCPClientModal(clientId = null) {
  11093. const modal = document.getElementById('modal-dhcp-client');
  11094. if (!modal) return;
  11095. const title = document.getElementById('modal-dhcp-title');
  11096. const idInput = document.getElementById('modal-dhcp-id');
  11097. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11098. const distInput = document.getElementById('modal-dhcp-distance');
  11099. const commentInput = document.getElementById('modal-dhcp-comment');
  11100. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  11101. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  11102. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  11103. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  11104. // Populate interfaces
  11105. if (ifaceSelect) {
  11106. let opts = '<option value="">Select interface...</option>';
  11107. const allIfaces = state.interfaces || [];
  11108. const allVlans = state.vlans || [];
  11109. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  11110. // Group 1: Physical & Bridge Interfaces
  11111. opts += '<optgroup label="Physical & Bridge Interfaces">';
  11112. allIfaces.forEach(i => {
  11113. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  11114. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  11115. });
  11116. opts += '</optgroup>';
  11117. // Group 2: VLAN Interfaces
  11118. if (allVlans.length > 0) {
  11119. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  11120. allVlans.forEach(v => {
  11121. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  11122. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  11123. });
  11124. opts += '</optgroup>';
  11125. }
  11126. ifaceSelect.innerHTML = opts;
  11127. }
  11128. if (clientId) {
  11129. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  11130. if (client) {
  11131. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  11132. if (idInput) idInput.value = client.id;
  11133. if (ifaceSelect) {
  11134. ifaceSelect.value = client.interface;
  11135. ifaceSelect.disabled = true; // interface cannot be changed on edit
  11136. }
  11137. if (distInput) distInput.value = client.default_route_distance || 1;
  11138. if (commentInput) commentInput.value = client.comment || '';
  11139. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  11140. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  11141. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  11142. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  11143. }
  11144. } else {
  11145. if (title) title.innerText = 'Add DHCP Client';
  11146. if (idInput) idInput.value = '';
  11147. if (ifaceSelect) {
  11148. ifaceSelect.value = '';
  11149. ifaceSelect.disabled = false;
  11150. }
  11151. if (distInput) distInput.value = 1;
  11152. if (commentInput) commentInput.value = '';
  11153. if (defRouteCheck) defRouteCheck.checked = true;
  11154. if (peerDnsCheck) peerDnsCheck.checked = true;
  11155. if (peerNtpCheck) peerNtpCheck.checked = true;
  11156. if (enabledCheck) enabledCheck.checked = true;
  11157. }
  11158. modal.classList.remove('hidden');
  11159. }
  11160. function openDHCPClientModalForIface(ifaceName) {
  11161. openDHCPClientModal();
  11162. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11163. if (ifaceSelect && ifaceName) {
  11164. ifaceSelect.value = ifaceName;
  11165. }
  11166. }
  11167. function closeDHCPClientModal() {
  11168. const modal = document.getElementById('modal-dhcp-client');
  11169. if (modal) modal.classList.add('hidden');
  11170. }
  11171. async function submitSaveDHCPClient(e) {
  11172. if (e) e.preventDefault();
  11173. const id = document.getElementById('modal-dhcp-id')?.value;
  11174. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  11175. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  11176. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  11177. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  11178. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  11179. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  11180. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  11181. if (!id && !iface) {
  11182. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  11183. return;
  11184. }
  11185. try {
  11186. let res;
  11187. if (id) {
  11188. // PUT update
  11189. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  11190. method: 'PUT',
  11191. headers: { 'Content-Type': 'application/json' },
  11192. body: JSON.stringify({
  11193. enabled,
  11194. add_default_route: defRoute,
  11195. default_route_distance: distance,
  11196. use_peer_dns: peerDns,
  11197. use_peer_ntp: peerNtp,
  11198. comment
  11199. })
  11200. });
  11201. } else {
  11202. // POST create
  11203. res = await fetch(`${API_BASE}/dhcp/clients`, {
  11204. method: 'POST',
  11205. headers: { 'Content-Type': 'application/json' },
  11206. body: JSON.stringify({
  11207. interface: iface,
  11208. enabled,
  11209. add_default_route: defRoute,
  11210. default_route_distance: distance,
  11211. use_peer_dns: peerDns,
  11212. use_peer_ntp: peerNtp,
  11213. comment
  11214. })
  11215. });
  11216. }
  11217. const data = await res.json();
  11218. if (!res.ok) {
  11219. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  11220. return;
  11221. }
  11222. closeDHCPClientModal();
  11223. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  11224. await loadDHCPClients();
  11225. fetchData(); // refresh interfaces list with new lease/status
  11226. } catch (err) {
  11227. showToast('Error', err.message, 'error');
  11228. }
  11229. }
  11230. async function toggleDHCPClientState(id, enabled) {
  11231. try {
  11232. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  11233. method: 'POST',
  11234. headers: { 'Content-Type': 'application/json' },
  11235. body: JSON.stringify({ enabled })
  11236. });
  11237. const data = await res.json();
  11238. if (!res.ok) {
  11239. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  11240. return;
  11241. }
  11242. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  11243. await loadDHCPClients();
  11244. fetchData();
  11245. } catch (err) {
  11246. showToast('Error', err.message, 'error');
  11247. }
  11248. }
  11249. async function renewDHCPClient(id) {
  11250. try {
  11251. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  11252. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  11253. method: 'POST'
  11254. });
  11255. const data = await res.json();
  11256. if (!res.ok) {
  11257. showToast('Error', data.error || 'Failed to renew lease', 'error');
  11258. return;
  11259. }
  11260. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  11261. setTimeout(() => {
  11262. loadDHCPClients();
  11263. fetchData();
  11264. }, 1500);
  11265. } catch (err) {
  11266. showToast('Error', err.message, 'error');
  11267. }
  11268. }
  11269. async function releaseDHCPClient(id) {
  11270. try {
  11271. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  11272. method: 'POST'
  11273. });
  11274. const data = await res.json();
  11275. if (!res.ok) {
  11276. showToast('Error', data.error || 'Failed to release lease', 'error');
  11277. return;
  11278. }
  11279. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  11280. await loadDHCPClients();
  11281. fetchData();
  11282. } catch (err) {
  11283. showToast('Error', err.message, 'error');
  11284. }
  11285. }
  11286. async function deleteDHCPClient(id, ifaceName) {
  11287. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  11288. return;
  11289. }
  11290. try {
  11291. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  11292. method: 'DELETE'
  11293. });
  11294. const data = await res.json();
  11295. if (!res.ok) {
  11296. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  11297. return;
  11298. }
  11299. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  11300. await loadDHCPClients();
  11301. fetchData();
  11302. } catch (err) {
  11303. showToast('Error', err.message, 'error');
  11304. }
  11305. }
  11306. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  11307. async function loadDHCPServer(populate = true) {
  11308. try {
  11309. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  11310. fetch(`${API_BASE}/dhcp-server/summary`),
  11311. fetch(`${API_BASE}/dhcp-server/servers`),
  11312. fetch(`${API_BASE}/dhcp-server/networks`),
  11313. fetch(`${API_BASE}/dhcp-server/leases`),
  11314. fetch(`${API_BASE}/dhcp-server/options`)
  11315. ]);
  11316. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  11317. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  11318. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  11319. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  11320. if (optRes.ok) state.dhcpOptions = await optRes.json();
  11321. const sum = state.dhcpServerSummary || {};
  11322. const srvs = state.dhcpServers || [];
  11323. const nets = state.dhcpNetworks || [];
  11324. const leases = state.dhcpLeases || [];
  11325. const opts = state.dhcpOptions || [];
  11326. // KPI Cards
  11327. const statActive = document.getElementById('dhcp-server-stat-active');
  11328. if (statActive) {
  11329. const activeCount = srvs.filter(s => s.running).length;
  11330. statActive.innerText = `${activeCount} / ${srvs.length}`;
  11331. }
  11332. const statLeases = document.getElementById('dhcp-server-stat-leases');
  11333. if (statLeases) {
  11334. statLeases.innerText = leases.length;
  11335. }
  11336. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  11337. if (statLeasesSub) {
  11338. const dyn = leases.filter(l => l.dynamic).length;
  11339. const st = leases.filter(l => !l.dynamic).length;
  11340. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  11341. }
  11342. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  11343. if (statNetworks) {
  11344. statNetworks.innerText = nets.length;
  11345. }
  11346. // Subtab Badges
  11347. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  11348. if (bSrv) bSrv.innerText = srvs.length;
  11349. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  11350. if (bNet) bNet.innerText = nets.length;
  11351. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  11352. if (bLease) bLease.innerText = leases.length;
  11353. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  11354. if (bOpt) bOpt.innerText = opts.length;
  11355. // Sidebar Badge
  11356. const sideBadge = document.getElementById('badge-dhcp-server-count');
  11357. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  11358. renderCurrentDHCPServerTab();
  11359. } catch (err) {
  11360. console.error('Failed to load DHCP Server:', err);
  11361. }
  11362. }
  11363. function switchDHCPServerTab(tab) {
  11364. state.dhcpServerTab = tab;
  11365. const tabs = ['servers', 'networks', 'leases', 'options'];
  11366. tabs.forEach(t => {
  11367. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  11368. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  11369. if (panel) {
  11370. if (t === tab) panel.classList.remove('hidden');
  11371. else panel.classList.add('hidden');
  11372. }
  11373. if (btn) {
  11374. if (t === tab) {
  11375. 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';
  11376. } else {
  11377. 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';
  11378. }
  11379. }
  11380. });
  11381. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  11382. if (addBtn) {
  11383. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  11384. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  11385. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  11386. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  11387. }
  11388. renderCurrentDHCPServerTab();
  11389. }
  11390. function handleDHCPServerPrimaryAdd() {
  11391. const tab = state.dhcpServerTab || 'servers';
  11392. if (tab === 'servers') openAddDHCPServerModal();
  11393. else if (tab === 'networks') openAddDHCPNetworkModal();
  11394. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  11395. else if (tab === 'options') openAddDHCPOptionModal();
  11396. }
  11397. function renderCurrentDHCPServerTab() {
  11398. const tab = state.dhcpServerTab || 'servers';
  11399. if (tab === 'servers') renderDHCPServers();
  11400. else if (tab === 'networks') renderDHCPNetworks();
  11401. else if (tab === 'leases') renderDHCPLeases();
  11402. else if (tab === 'options') renderDHCPOptions();
  11403. }
  11404. function renderDHCPServers() {
  11405. const tbody = document.getElementById('dhcp-server-tbody');
  11406. const empty = document.getElementById('dhcp-server-empty');
  11407. if (!tbody) return;
  11408. tbody.innerHTML = '';
  11409. const servers = state.dhcpServers || [];
  11410. if (servers.length === 0) {
  11411. empty?.classList.remove('hidden');
  11412. return;
  11413. }
  11414. empty?.classList.add('hidden');
  11415. servers.forEach(s => {
  11416. const tr = document.createElement('tr');
  11417. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  11418. tr.innerHTML = `
  11419. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  11420. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  11421. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  11422. <td class="py-2.5 px-3 font-mono font-semibold">${s.network ? `<span class="px-2 py-0.5 rounded text-[11px] bg-emerald-500/10 text-emerald-300 border border-emerald-500/20 font-bold">${escapeHtml(s.network)}</span>` : '<span class="text-slate-500 italic text-[11px]">Unassigned</span>'}</td>
  11423. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  11424. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  11425. <td class="py-2.5 px-3 font-mono text-slate-300">${s.authoritative ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  11426. <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${s.active_leases || 0}</span></td>
  11427. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  11428. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11429. <button onclick="toggleDHCPServerState('${s.id}', ${!s.disabled})" class="text-xs ${s.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${s.disabled ? 'Enable' : 'Disable'}</button>
  11430. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11431. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  11432. </td>
  11433. `;
  11434. tbody.appendChild(tr);
  11435. });
  11436. }
  11437. function renderDHCPNetworks() {
  11438. const tbody = document.getElementById('dhcp-networks-tbody');
  11439. const empty = document.getElementById('dhcp-networks-empty');
  11440. if (!tbody) return;
  11441. tbody.innerHTML = '';
  11442. const networks = state.dhcpNetworks || [];
  11443. if (networks.length === 0) {
  11444. empty?.classList.remove('hidden');
  11445. return;
  11446. }
  11447. empty?.classList.add('hidden');
  11448. networks.forEach(n => {
  11449. const tr = document.createElement('tr');
  11450. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  11451. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  11452. const ntpStr = (n.ntp_servers || []).join(', ') || '-';
  11453. tr.innerHTML = `
  11454. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  11455. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  11456. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  11457. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[120px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  11458. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  11459. <td class="py-2.5 px-3 font-mono text-purple-300 truncate max-w-[120px]" title="${escapeHtml(ntpStr)}">${escapeHtml(ntpStr)}</td>
  11460. <td class="py-2.5 px-3 font-mono text-amber-300">${escapeHtml(n.next_server || '-')}</td>
  11461. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.boot_file_name || '-')}</td>
  11462. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  11463. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11464. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11465. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  11466. </td>
  11467. `;
  11468. tbody.appendChild(tr);
  11469. });
  11470. }
  11471. function renderDHCPLeases() {
  11472. const tbody = document.getElementById('dhcp-leases-tbody');
  11473. const empty = document.getElementById('dhcp-leases-empty');
  11474. if (!tbody) return;
  11475. tbody.innerHTML = '';
  11476. const leases = state.dhcpLeases || [];
  11477. if (leases.length === 0) {
  11478. empty?.classList.remove('hidden');
  11479. return;
  11480. }
  11481. empty?.classList.add('hidden');
  11482. leases.forEach(l => {
  11483. const tr = document.createElement('tr');
  11484. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  11485. const flag = l.dynamic ? '<span class="text-sky-400 font-bold" title="Dynamic">D</span>' : '<span class="text-purple-400 font-bold" title="Static Reservation">S</span>';
  11486. const statusBadge = l.status === 'bound'
  11487. ? '<span class="px-1.5 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-semibold font-mono">bound</span>'
  11488. : l.status === 'static'
  11489. ? '<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-500/20 text-purple-300 border border-purple-500/30 font-semibold font-mono">static</span>'
  11490. : '<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700 font-mono">waiting</span>';
  11491. const makeStaticBtn = l.dynamic
  11492. ? `<button onclick="makeDHCPLeaseStatic('${escapeHtml(l.mac_address)}', '${escapeHtml(l.address)}', '${escapeHtml(l.hostname || '')}', '${escapeHtml(l.comment || '')}')" class="text-xs px-2 py-0.5 rounded bg-purple-500/20 text-purple-300 border border-purple-500/30 hover:bg-purple-500/30 font-medium">Make Static</button>`
  11493. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  11494. tr.innerHTML = `
  11495. <td class="py-2.5 px-3 text-center">${flag}</td>
  11496. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  11497. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  11498. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  11499. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  11500. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  11501. <td class="py-2.5 px-3">${statusBadge}</td>
  11502. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  11503. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11504. ${makeStaticBtn}
  11505. </td>
  11506. `;
  11507. tbody.appendChild(tr);
  11508. });
  11509. }
  11510. function renderDHCPOptions() {
  11511. const tbody = document.getElementById('dhcp-options-tbody');
  11512. const empty = document.getElementById('dhcp-options-empty');
  11513. if (!tbody) return;
  11514. tbody.innerHTML = '';
  11515. const options = state.dhcpOptions || [];
  11516. if (options.length === 0) {
  11517. empty?.classList.remove('hidden');
  11518. return;
  11519. }
  11520. empty?.classList.add('hidden');
  11521. options.forEach(o => {
  11522. const tr = document.createElement('tr');
  11523. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  11524. tr.innerHTML = `
  11525. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  11526. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  11527. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  11528. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  11529. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11530. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11531. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  11532. </td>
  11533. `;
  11534. tbody.appendChild(tr);
  11535. });
  11536. }
  11537. // ==================== MODALS & ACTIONS: SERVER ====================
  11538. function populateDHCPNetworkSelect(elemId, selectedVal) {
  11539. const sel = document.getElementById(elemId);
  11540. if (!sel) return;
  11541. sel.innerHTML = '<option value="">Select network subnet...</option>';
  11542. const networks = state.dhcpNetworks || [];
  11543. networks.forEach(n => {
  11544. const opt = document.createElement('option');
  11545. opt.value = n.address;
  11546. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  11547. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  11548. opt.selected = true;
  11549. }
  11550. sel.appendChild(opt);
  11551. });
  11552. }
  11553. function onDHCPServerNetworkChange() {
  11554. const netSel = document.getElementById('dhcp-server-modal-network');
  11555. if (!netSel) return;
  11556. const netVal = netSel.value;
  11557. if (!netVal) return;
  11558. const poolInput = document.getElementById('dhcp-server-modal-pool');
  11559. if (!poolInput) return;
  11560. // Auto-calculate suggested address pool based on subnet CIDR
  11561. const parts = netVal.split('/');
  11562. const ip = parts[0];
  11563. const cidr = parseInt(parts[1] || '24', 10);
  11564. if (cidr === 24) {
  11565. const octets = ip.split('.');
  11566. if (octets.length === 4) {
  11567. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  11568. poolInput.value = `${base}.10-${base}.254`;
  11569. }
  11570. }
  11571. }
  11572. function openAddDHCPServerModal() {
  11573. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  11574. document.getElementById('dhcp-server-modal-id').value = '';
  11575. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  11576. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  11577. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  11578. document.getElementById('dhcp-server-modal-comment').value = '';
  11579. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  11580. document.getElementById('dhcp-server-modal-disabled').checked = false;
  11581. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  11582. const networks = state.dhcpNetworks || [];
  11583. const defaultNet = networks.length > 0 ? networks[0].address : '';
  11584. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  11585. if (defaultNet) {
  11586. onDHCPServerNetworkChange();
  11587. }
  11588. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  11589. }
  11590. function openEditDHCPServerModal(id) {
  11591. const s = (state.dhcpServers || []).find(item => item.id === id);
  11592. if (!s) return;
  11593. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  11594. document.getElementById('dhcp-server-modal-id').value = s.id;
  11595. document.getElementById('dhcp-server-modal-name').value = s.name;
  11596. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  11597. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  11598. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  11599. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  11600. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  11601. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  11602. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  11603. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  11604. }
  11605. function closeDHCPServerModal() {
  11606. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  11607. }
  11608. async function submitSaveDHCPServer(e) {
  11609. e.preventDefault();
  11610. const id = document.getElementById('dhcp-server-modal-id').value;
  11611. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  11612. const iface = document.getElementById('dhcp-server-modal-iface').value;
  11613. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  11614. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  11615. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  11616. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  11617. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  11618. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  11619. try {
  11620. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  11621. method: 'POST',
  11622. headers: { 'Content-Type': 'application/json' },
  11623. body: JSON.stringify({
  11624. id,
  11625. name,
  11626. interface: iface,
  11627. network,
  11628. address_pool: pool,
  11629. lease_time: leaseTime,
  11630. authoritative,
  11631. disabled,
  11632. comment
  11633. })
  11634. });
  11635. if (res.ok) {
  11636. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  11637. closeDHCPServerModal();
  11638. loadDHCPServer(false);
  11639. fetchData(false);
  11640. } else {
  11641. const err = await res.text();
  11642. showToast('Error', err, 'error');
  11643. }
  11644. } catch (err) {
  11645. showToast('Error', err.message, 'error');
  11646. }
  11647. }
  11648. async function toggleDHCPServerState(id, disabled) {
  11649. try {
  11650. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  11651. method: 'POST',
  11652. headers: { 'Content-Type': 'application/json' },
  11653. body: JSON.stringify({ disabled })
  11654. });
  11655. if (res.ok) {
  11656. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  11657. loadDHCPServer(false);
  11658. fetchData(false);
  11659. }
  11660. } catch (err) {
  11661. showToast('Error', err.message, 'error');
  11662. }
  11663. }
  11664. async function deleteDHCPServer(id, name) {
  11665. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  11666. try {
  11667. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11668. if (res.ok) {
  11669. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  11670. loadDHCPServer(false);
  11671. fetchData(false);
  11672. }
  11673. } catch (err) {
  11674. showToast('Error', err.message, 'error');
  11675. }
  11676. }
  11677. // ==================== MODALS & ACTIONS: NETWORKS ====================
  11678. function openAddDHCPNetworkModal() {
  11679. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  11680. document.getElementById('dhcp-network-modal-id').value = '';
  11681. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  11682. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  11683. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  11684. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  11685. document.getElementById('dhcp-network-modal-ntp').value = '192.168.88.1, time.cloudflare.com';
  11686. document.getElementById('dhcp-network-modal-tftp').value = '';
  11687. document.getElementById('dhcp-network-modal-bootfile').value = '';
  11688. document.getElementById('dhcp-network-modal-wins').value = '';
  11689. document.getElementById('dhcp-network-modal-netmask').value = '';
  11690. document.getElementById('dhcp-network-modal-comment').value = '';
  11691. renderDHCPNetworkOptionsCheckboxes([]);
  11692. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  11693. }
  11694. function openEditDHCPNetworkModal(id) {
  11695. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  11696. if (!n) return;
  11697. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  11698. document.getElementById('dhcp-network-modal-id').value = n.id;
  11699. document.getElementById('dhcp-network-modal-address').value = n.address;
  11700. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  11701. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  11702. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  11703. document.getElementById('dhcp-network-modal-ntp').value = (n.ntp_servers || []).join(', ');
  11704. document.getElementById('dhcp-network-modal-tftp').value = n.next_server || '';
  11705. document.getElementById('dhcp-network-modal-bootfile').value = n.boot_file_name || '';
  11706. document.getElementById('dhcp-network-modal-wins').value = (n.wins_servers || []).join(', ');
  11707. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  11708. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  11709. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  11710. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  11711. }
  11712. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  11713. const container = document.getElementById('dhcp-network-modal-options-list');
  11714. if (!container) return;
  11715. container.innerHTML = '';
  11716. const opts = state.dhcpOptions || [];
  11717. if (opts.length === 0) {
  11718. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  11719. return;
  11720. }
  11721. opts.forEach(o => {
  11722. const isChecked = selectedIds.includes(o.id);
  11723. const label = document.createElement('label');
  11724. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  11725. label.innerHTML = `
  11726. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  11727. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  11728. `;
  11729. container.appendChild(label);
  11730. });
  11731. }
  11732. function closeDHCPNetworkModal() {
  11733. document.getElementById('dhcp-network-modal').classList.add('hidden');
  11734. }
  11735. async function submitSaveDHCPNetwork(e) {
  11736. e.preventDefault();
  11737. const id = document.getElementById('dhcp-network-modal-id').value;
  11738. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  11739. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  11740. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  11741. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  11742. const ntpStr = document.getElementById('dhcp-network-modal-ntp').value.trim();
  11743. const tftp = document.getElementById('dhcp-network-modal-tftp').value.trim();
  11744. const bootfile = document.getElementById('dhcp-network-modal-bootfile').value.trim();
  11745. const winsStr = document.getElementById('dhcp-network-modal-wins').value.trim();
  11746. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  11747. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  11748. const selectedOpts = [];
  11749. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  11750. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  11751. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  11752. const winsServers = winsStr ? winsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  11753. try {
  11754. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  11755. method: 'POST',
  11756. headers: { 'Content-Type': 'application/json' },
  11757. body: JSON.stringify({
  11758. id,
  11759. address,
  11760. gateway,
  11761. netmask,
  11762. dns_servers: dnsServers,
  11763. domain,
  11764. ntp_servers: ntpServers,
  11765. next_server: tftp,
  11766. boot_file_name: bootfile,
  11767. wins_servers: winsServers,
  11768. dhcp_options: selectedOpts,
  11769. comment
  11770. })
  11771. });
  11772. if (res.ok) {
  11773. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  11774. closeDHCPNetworkModal();
  11775. loadDHCPServer(false);
  11776. fetchData(false);
  11777. } else {
  11778. const err = await res.text();
  11779. showToast('Error', err, 'error');
  11780. }
  11781. } catch (err) {
  11782. showToast('Error', err.message, 'error');
  11783. }
  11784. }
  11785. async function deleteDHCPNetwork(id, addr) {
  11786. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  11787. try {
  11788. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11789. if (res.ok) {
  11790. showToast('Deleted', `Network ${addr} removed`, 'success');
  11791. loadDHCPServer(false);
  11792. fetchData(false);
  11793. }
  11794. } catch (err) {
  11795. showToast('Error', err.message, 'error');
  11796. }
  11797. }
  11798. // ==================== MODALS & ACTIONS: LEASES ====================
  11799. function openAddDHCPStaticLeaseModal() {
  11800. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  11801. document.getElementById('dhcp-static-lease-modal-id').value = '';
  11802. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  11803. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  11804. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  11805. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  11806. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  11807. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  11808. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  11809. }
  11810. function closeDHCPStaticLeaseModal() {
  11811. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  11812. }
  11813. async function submitSaveDHCPStaticLease(e) {
  11814. e.preventDefault();
  11815. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  11816. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  11817. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  11818. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  11819. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  11820. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  11821. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  11822. try {
  11823. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  11824. method: 'POST',
  11825. headers: { 'Content-Type': 'application/json' },
  11826. body: JSON.stringify({
  11827. id,
  11828. mac_address: mac,
  11829. address: ip,
  11830. hostname,
  11831. server,
  11832. comment,
  11833. disabled
  11834. })
  11835. });
  11836. if (res.ok) {
  11837. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  11838. closeDHCPStaticLeaseModal();
  11839. loadDHCPServer(false);
  11840. fetchData(false);
  11841. } else {
  11842. const err = await res.text();
  11843. showToast('Error', err, 'error');
  11844. }
  11845. } catch (err) {
  11846. showToast('Error', err.message, 'error');
  11847. }
  11848. }
  11849. async function deleteDHCPStaticLease(id) {
  11850. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  11851. try {
  11852. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11853. if (res.ok) {
  11854. showToast('Deleted', 'Static lease removed', 'success');
  11855. loadDHCPServer(false);
  11856. fetchData(false);
  11857. }
  11858. } catch (err) {
  11859. showToast('Error', err.message, 'error');
  11860. }
  11861. }
  11862. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  11863. try {
  11864. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  11865. method: 'POST',
  11866. headers: { 'Content-Type': 'application/json' },
  11867. body: JSON.stringify({
  11868. mac_address: mac,
  11869. address: ip,
  11870. hostname,
  11871. comment: comment || 'Converted to static'
  11872. })
  11873. });
  11874. if (res.ok) {
  11875. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  11876. loadDHCPServer(false);
  11877. fetchData(false);
  11878. } else {
  11879. const err = await res.text();
  11880. showToast('Error', err, 'error');
  11881. }
  11882. } catch (err) {
  11883. showToast('Error', err.message, 'error');
  11884. }
  11885. }
  11886. // ==================== MODALS & ACTIONS: OPTIONS ====================
  11887. function openAddDHCPOptionModal() {
  11888. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  11889. document.getElementById('dhcp-option-modal-id').value = '';
  11890. document.getElementById('dhcp-option-modal-name').value = '';
  11891. document.getElementById('dhcp-option-modal-code').value = '';
  11892. document.getElementById('dhcp-option-modal-value').value = '';
  11893. document.getElementById('dhcp-option-modal-comment').value = '';
  11894. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  11895. }
  11896. function openEditDHCPOptionModal(id) {
  11897. const o = (state.dhcpOptions || []).find(item => item.id === id);
  11898. if (!o) return;
  11899. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  11900. document.getElementById('dhcp-option-modal-id').value = o.id;
  11901. document.getElementById('dhcp-option-modal-name').value = o.name;
  11902. document.getElementById('dhcp-option-modal-code').value = o.code;
  11903. document.getElementById('dhcp-option-modal-value').value = o.value;
  11904. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  11905. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  11906. }
  11907. function closeDHCPOptionModal() {
  11908. document.getElementById('dhcp-option-modal').classList.add('hidden');
  11909. }
  11910. async function submitSaveDHCPOption(e) {
  11911. e.preventDefault();
  11912. const id = document.getElementById('dhcp-option-modal-id').value;
  11913. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  11914. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  11915. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  11916. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  11917. try {
  11918. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  11919. method: 'POST',
  11920. headers: { 'Content-Type': 'application/json' },
  11921. body: JSON.stringify({ id, name, code, value, comment })
  11922. });
  11923. if (res.ok) {
  11924. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  11925. closeDHCPOptionModal();
  11926. loadDHCPServer(false);
  11927. fetchData(false);
  11928. } else {
  11929. const err = await res.text();
  11930. showToast('Error', err, 'error');
  11931. }
  11932. } catch (err) {
  11933. showToast('Error', err.message, 'error');
  11934. }
  11935. }
  11936. async function deleteDHCPOption(id, name) {
  11937. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  11938. try {
  11939. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11940. if (res.ok) {
  11941. showToast('Deleted', `Option ${name} removed`, 'success');
  11942. loadDHCPServer(false);
  11943. fetchData(false);
  11944. }
  11945. } catch (err) {
  11946. showToast('Error', err.message, 'error');
  11947. }
  11948. }
  11949. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  11950. function openDHCPServerSetupModal() {
  11951. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  11952. onDHCPWizardIfaceChange();
  11953. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  11954. }
  11955. function closeDHCPServerSetupModal() {
  11956. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  11957. }
  11958. function onDHCPWizardIfaceChange() {
  11959. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  11960. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  11961. let ip = '192.168.88.1';
  11962. let prefix = '24';
  11963. if (iface && iface.ip_address) {
  11964. const parts = iface.ip_address.split('/');
  11965. ip = parts[0];
  11966. if (parts.length > 1) prefix = parts[1];
  11967. }
  11968. // Calculate subnet base (e.g. 192.168.88.0/24)
  11969. const ipParts = ip.split('.');
  11970. if (ipParts.length === 4) {
  11971. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  11972. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  11973. document.getElementById('dhcp-wizard-space').value = baseSpace;
  11974. document.getElementById('dhcp-wizard-gateway').value = ip;
  11975. document.getElementById('dhcp-wizard-pool').value = pool;
  11976. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  11977. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  11978. }
  11979. }
  11980. async function submitDHCPServerSetupWizard(e) {
  11981. e.preventDefault();
  11982. const iface = document.getElementById('dhcp-wizard-iface').value;
  11983. const space = document.getElementById('dhcp-wizard-space').value.trim();
  11984. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  11985. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  11986. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  11987. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  11988. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  11989. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  11990. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  11991. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  11992. try {
  11993. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  11994. method: 'POST',
  11995. headers: { 'Content-Type': 'application/json' },
  11996. body: JSON.stringify({
  11997. interface: iface,
  11998. address_space: space,
  11999. gateway: gw,
  12000. address_pool: pool,
  12001. dns_servers: dnsServers,
  12002. lease_time: leaseTime,
  12003. ntp_servers: ntpServers,
  12004. next_server: tftp
  12005. })
  12006. });
  12007. if (res.ok) {
  12008. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  12009. closeDHCPServerSetupModal();
  12010. loadDHCPServer(false);
  12011. fetchData(false);
  12012. } else {
  12013. const err = await res.text();
  12014. showToast('Error', err, 'error');
  12015. }
  12016. } catch (err) {
  12017. showToast('Error', err.message, 'error');
  12018. }
  12019. }
  12020. function populateDHCPIfaceSelect(elemId, selectedVal) {
  12021. const sel = document.getElementById(elemId);
  12022. if (!sel) return;
  12023. sel.innerHTML = '<option value="">Select interface...</option>';
  12024. const ifaces = state.interfaces || [];
  12025. ifaces.forEach(i => {
  12026. if (i.name === 'lo') return;
  12027. const opt = document.createElement('option');
  12028. opt.value = i.name;
  12029. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  12030. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  12031. if (i.name === selectedVal) opt.selected = true;
  12032. sel.appendChild(opt);
  12033. });
  12034. }
  12035. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  12036. function initTableSorting() {
  12037. document.querySelectorAll('table').forEach(setupSortableTable);
  12038. }
  12039. function setupSortableTable(table) {
  12040. const thead = table.querySelector('thead');
  12041. const tbody = table.querySelector('tbody');
  12042. if (!thead || !tbody) return;
  12043. const headerRows = thead.querySelectorAll('tr');
  12044. if (headerRows.length === 0) return;
  12045. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  12046. ths.forEach((th, colIdx) => {
  12047. if (th._sortBound) return;
  12048. th._sortBound = true;
  12049. const rawText = th.innerText.trim().toLowerCase();
  12050. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  12051. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  12052. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  12053. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  12054. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  12055. return;
  12056. }
  12057. th.classList.add('table-sortable', 'group');
  12058. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  12059. let icon = th.querySelector('.table-sort-icon');
  12060. if (!icon) {
  12061. icon = document.createElement('span');
  12062. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12063. icon.innerHTML = '⇅';
  12064. th.appendChild(icon);
  12065. }
  12066. th.addEventListener('click', (e) => {
  12067. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  12068. handleHeaderClick(table, th, colIdx);
  12069. });
  12070. });
  12071. if (!tbody._sortObserved) {
  12072. tbody._sortObserved = true;
  12073. let sortDebounceTimer = null;
  12074. const observer = new MutationObserver((mutations) => {
  12075. if (tbody._isSorting) return;
  12076. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  12077. if (!hasChildChanges) return;
  12078. clearTimeout(sortDebounceTimer);
  12079. sortDebounceTimer = setTimeout(() => {
  12080. if (tbody._isSorting) return;
  12081. if (table._activeSort && table._activeSort.dir !== 'none') {
  12082. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  12083. } else {
  12084. tagOriginalRowOrder(tbody);
  12085. }
  12086. }, 10);
  12087. });
  12088. observer.observe(tbody, { childList: true });
  12089. }
  12090. tagOriginalRowOrder(tbody);
  12091. }
  12092. function tagOriginalRowOrder(tbody) {
  12093. let idx = 0;
  12094. Array.from(tbody.children).forEach(tr => {
  12095. if (!tr.querySelector('td[colspan]')) {
  12096. if (!tr.hasAttribute('data-orig-idx')) {
  12097. tr.setAttribute('data-orig-idx', idx++);
  12098. }
  12099. }
  12100. });
  12101. }
  12102. function handleHeaderClick(table, th, colIdx) {
  12103. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  12104. let newDir = 'asc';
  12105. if (currentSort.colIdx === colIdx) {
  12106. if (currentSort.dir === 'asc') newDir = 'desc';
  12107. else if (currentSort.dir === 'desc') newDir = 'none';
  12108. else newDir = 'asc';
  12109. } else {
  12110. newDir = 'asc';
  12111. }
  12112. table._activeSort = { colIdx, dir: newDir };
  12113. updateHeaderIcons(table, colIdx, newDir);
  12114. applyTableSort(table, colIdx, newDir, true);
  12115. }
  12116. function updateHeaderIcons(table, activeColIdx, dir) {
  12117. const thead = table.querySelector('thead');
  12118. if (!thead) return;
  12119. const ths = thead.querySelectorAll('th');
  12120. ths.forEach((th, idx) => {
  12121. const icon = th.querySelector('.table-sort-icon');
  12122. if (!icon) return;
  12123. if (idx === activeColIdx && dir !== 'none') {
  12124. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  12125. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  12126. th.classList.add('table-sorted-active');
  12127. } else {
  12128. icon.innerHTML = '⇅';
  12129. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12130. th.classList.remove('table-sorted-active');
  12131. }
  12132. });
  12133. }
  12134. function applyTableSort(table, colIdx, dir, userInitiated) {
  12135. const tbody = table.querySelector('tbody');
  12136. if (!tbody || tbody.children.length <= 1) return;
  12137. tbody._isSorting = true;
  12138. tagOriginalRowOrder(tbody);
  12139. // Group parent rows and any attached drawer/sub-rows
  12140. const groups = [];
  12141. let currentGroup = null;
  12142. Array.from(tbody.children).forEach(tr => {
  12143. if (tr.querySelector('td[colspan]')) {
  12144. if (currentGroup) {
  12145. currentGroup.subRows.push(tr);
  12146. } else {
  12147. groups.push({ mainRow: tr, subRows: [] });
  12148. }
  12149. } else {
  12150. currentGroup = { mainRow: tr, subRows: [] };
  12151. groups.push(currentGroup);
  12152. }
  12153. });
  12154. if (dir === 'none') {
  12155. groups.sort((a, b) => {
  12156. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  12157. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  12158. return idxA - idxB;
  12159. });
  12160. } else {
  12161. groups.sort((a, b) => {
  12162. const cellA = a.mainRow.children[colIdx];
  12163. const cellB = b.mainRow.children[colIdx];
  12164. const res = compareTableCells(cellA, cellB);
  12165. return dir === 'asc' ? res : -res;
  12166. });
  12167. }
  12168. // Re-append rows in sorted order
  12169. groups.forEach(g => {
  12170. tbody.appendChild(g.mainRow);
  12171. g.subRows.forEach(sub => tbody.appendChild(sub));
  12172. });
  12173. tbody._isSorting = false;
  12174. }
  12175. function getCellRawText(cell) {
  12176. if (!cell) return '';
  12177. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  12178. const input = cell.querySelector('input, select');
  12179. if (input) {
  12180. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  12181. return input.value;
  12182. }
  12183. return cell.innerText.trim();
  12184. }
  12185. function parseTrafficToNumber(str) {
  12186. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  12187. if (!m) return null;
  12188. const num = parseFloat(m[1].replace(/,/g, ''));
  12189. if (isNaN(num)) return null;
  12190. const unit = m[2].toUpperCase();
  12191. let mult = 1;
  12192. if (unit.startsWith('K')) mult = 1024;
  12193. else if (unit.startsWith('M')) mult = 1024 * 1024;
  12194. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  12195. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  12196. return num * mult;
  12197. }
  12198. function parseIpToNumber(str) {
  12199. const clean = str.replace(/^[!~]/, '').trim();
  12200. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  12201. if (!m) return null;
  12202. const o1 = parseInt(m[1], 10);
  12203. const o2 = parseInt(m[2], 10);
  12204. const o3 = parseInt(m[3], 10);
  12205. const o4 = parseInt(m[4], 10);
  12206. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  12207. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  12208. }
  12209. function parseCompoundPackets(str) {
  12210. const m = str.match(/^([\d,]+)p/);
  12211. if (!m) return null;
  12212. return parseInt(m[1].replace(/,/g, ''), 10);
  12213. }
  12214. function compareTableCells(cellA, cellB) {
  12215. const a = getCellRawText(cellA);
  12216. const b = getCellRawText(cellB);
  12217. if (a === '' && b !== '') return 1;
  12218. if (b === '' && a !== '') return -1;
  12219. if (a === b) return 0;
  12220. // 1. IP Addresses / CIDR
  12221. const ipA = parseIpToNumber(a);
  12222. const ipB = parseIpToNumber(b);
  12223. if (ipA !== null && ipB !== null) return ipA - ipB;
  12224. // 2. Packet counts (e.g. "1,250p / 45 KB")
  12225. const pktA = parseCompoundPackets(a);
  12226. const pktB = parseCompoundPackets(b);
  12227. if (pktA !== null && pktB !== null) return pktA - pktB;
  12228. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  12229. const trafA = parseTrafficToNumber(a);
  12230. const trafB = parseTrafficToNumber(b);
  12231. if (trafA !== null && trafB !== null) return trafA - trafB;
  12232. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  12233. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  12234. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  12235. const numA = Number(cleanNumA);
  12236. const numB = Number(cleanNumB);
  12237. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  12238. return numA - numB;
  12239. }
  12240. // 5. Natural case-insensitive string compare
  12241. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  12242. }
  12243. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  12244. async function loadVRRP(showToastNotification = false) {
  12245. try {
  12246. const [instRes, sumRes] = await Promise.all([
  12247. fetch(`${API_BASE}/vrrp/instances`),
  12248. fetch(`${API_BASE}/vrrp/summary`)
  12249. ]);
  12250. if (instRes.ok) {
  12251. state.vrrpInstances = await instRes.json();
  12252. renderVRRP();
  12253. }
  12254. if (sumRes.ok) {
  12255. state.vrrpSummary = await sumRes.json();
  12256. renderVRRPSummary();
  12257. }
  12258. if (showToastNotification) {
  12259. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  12260. }
  12261. } catch (err) {
  12262. console.error('Failed to load VRRP:', err);
  12263. }
  12264. }
  12265. function renderVRRPSummary() {
  12266. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  12267. const elTotal = document.getElementById('vrrp-stat-total');
  12268. if (elTotal) elTotal.innerText = s.total_instances || 0;
  12269. const elMaster = document.getElementById('vrrp-stat-master');
  12270. if (elMaster) elMaster.innerText = s.master_instances || 0;
  12271. const elBackup = document.getElementById('vrrp-stat-backup');
  12272. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  12273. const bCount = document.getElementById('badge-vrrp-count');
  12274. if (bCount) bCount.innerText = s.total_instances || 0;
  12275. const dot = document.getElementById('badge-vrrp-dot');
  12276. if (dot) {
  12277. if (s.master_instances > 0) {
  12278. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  12279. } else if (s.backup_instances > 0) {
  12280. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  12281. } else {
  12282. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  12283. }
  12284. }
  12285. }
  12286. function renderVRRP() {
  12287. const tbody = document.getElementById('vrrp-table-tbody');
  12288. const empty = document.getElementById('vrrp-table-empty');
  12289. if (!tbody) return;
  12290. tbody.innerHTML = '';
  12291. const instances = state.vrrpInstances || [];
  12292. if (instances.length === 0) {
  12293. empty?.classList.remove('hidden');
  12294. return;
  12295. }
  12296. empty?.classList.add('hidden');
  12297. instances.forEach(inst => {
  12298. const tr = document.createElement('tr');
  12299. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  12300. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  12301. let flagHtml = `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-slate-800 text-slate-500 border border-slate-700">-</span>`;
  12302. if (inst.disabled) {
  12303. flagHtml = `<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>`;
  12304. } else if (inst.state === 'MASTER') {
  12305. flagHtml = `<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="Master (Holding VIP)">M</span>`;
  12306. } else if (inst.state === 'BACKUP') {
  12307. flagHtml = `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-sky-500/20 text-sky-400 border border-sky-500/40 shadow-sm" title="Backup (Standby)">B</span>`;
  12308. } else if (inst.state === 'FAULT') {
  12309. flagHtml = `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-amber-500/20 text-amber-400 border border-amber-500/40 shadow-sm" title="Fault (Interface Down)">F</span>`;
  12310. }
  12311. // Render State Badge
  12312. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  12313. if (!inst.disabled) {
  12314. if (inst.state === 'MASTER') {
  12315. stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 font-bold inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>MASTER</span>`;
  12316. } else if (inst.state === 'BACKUP') {
  12317. stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-sky-500/20 text-sky-300 border border-sky-500/40 font-bold inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-sky-400"></span>BACKUP</span>`;
  12318. } else if (inst.state === 'FAULT') {
  12319. stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-amber-500/20 text-amber-300 border border-amber-500/40 font-bold inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-amber-400"></span>FAULT</span>`;
  12320. }
  12321. }
  12322. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  12323. tr.innerHTML = `
  12324. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  12325. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  12326. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  12327. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  12328. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  12329. <td class="py-2.5 px-3 font-mono text-emerald-400 font-bold"><span class="px-2 py-0.5 rounded bg-emerald-500/10 border border-emerald-500/20">${escapeHtml(vipsStr)}</span></td>
  12330. <td class="py-2.5 px-3 font-mono text-center text-slate-300">${inst.preempt ? '<span class="text-emerald-400 font-semibold">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  12331. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  12332. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  12333. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  12334. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12335. <button onclick="toggleVRRPState('${inst.id}', ${!inst.disabled})" class="text-xs ${inst.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${inst.disabled ? 'Enable' : 'Disable'}</button>
  12336. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12337. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12338. </td>
  12339. `;
  12340. tbody.appendChild(tr);
  12341. });
  12342. }
  12343. function populateVRRPIfaceSelect(elemId, selectedIface) {
  12344. const sel = document.getElementById(elemId);
  12345. if (!sel) return;
  12346. sel.innerHTML = '<option value="">Select interface...</option>';
  12347. const ifaces = state.interfaces || [];
  12348. ifaces.forEach(i => {
  12349. const opt = document.createElement('option');
  12350. opt.value = i.name;
  12351. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  12352. if (selectedIface && selectedIface === i.name) opt.selected = true;
  12353. sel.appendChild(opt);
  12354. });
  12355. }
  12356. function openAddVRRPModal() {
  12357. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  12358. document.getElementById('modal-vrrp-id').value = '';
  12359. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  12360. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  12361. document.getElementById('modal-vrrp-priority').value = 100;
  12362. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  12363. document.getElementById('modal-vrrp-version').value = '3';
  12364. document.getElementById('modal-vrrp-interval').value = 1;
  12365. document.getElementById('modal-vrrp-authtype').value = 'none';
  12366. document.getElementById('modal-vrrp-authpass').value = '';
  12367. document.getElementById('modal-vrrp-comment').value = '';
  12368. document.getElementById('modal-vrrp-preempt').checked = true;
  12369. document.getElementById('modal-vrrp-disabled').checked = false;
  12370. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  12371. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  12372. }
  12373. function openEditVRRPModal(id) {
  12374. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  12375. if (!inst) return;
  12376. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  12377. document.getElementById('modal-vrrp-id').value = inst.id;
  12378. document.getElementById('modal-vrrp-name').value = inst.name;
  12379. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  12380. document.getElementById('modal-vrrp-priority').value = inst.priority;
  12381. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  12382. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  12383. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  12384. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  12385. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  12386. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  12387. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  12388. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  12389. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  12390. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  12391. }
  12392. function closeVRRPModal() {
  12393. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  12394. }
  12395. async function submitSaveVRRP(e) {
  12396. e.preventDefault();
  12397. const id = document.getElementById('modal-vrrp-id').value;
  12398. const name = document.getElementById('modal-vrrp-name').value.trim();
  12399. const iface = document.getElementById('modal-vrrp-iface').value;
  12400. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  12401. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  12402. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  12403. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  12404. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  12405. const authType = document.getElementById('modal-vrrp-authtype').value;
  12406. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  12407. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  12408. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  12409. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  12410. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  12411. try {
  12412. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  12413. method: 'POST',
  12414. headers: { 'Content-Type': 'application/json' },
  12415. body: JSON.stringify({
  12416. id,
  12417. name,
  12418. interface: iface,
  12419. vrid,
  12420. priority,
  12421. virtual_ips: vips,
  12422. version,
  12423. interval,
  12424. auth_type: authType,
  12425. auth_password: authPass,
  12426. comment,
  12427. preempt,
  12428. disabled
  12429. })
  12430. });
  12431. if (res.ok) {
  12432. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  12433. closeVRRPModal();
  12434. loadVRRP(false);
  12435. fetchData(false);
  12436. } else {
  12437. const err = await res.text();
  12438. showToast('Error', err, 'error');
  12439. }
  12440. } catch (err) {
  12441. showToast('Error', err.message, 'error');
  12442. }
  12443. }
  12444. async function deleteVRRP(id, name) {
  12445. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  12446. try {
  12447. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12448. if (res.ok) {
  12449. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  12450. loadVRRP(false);
  12451. fetchData(false);
  12452. } else {
  12453. const err = await res.text();
  12454. showToast('Error', err, 'error');
  12455. }
  12456. } catch (err) {
  12457. showToast('Error', err.message, 'error');
  12458. }
  12459. }
  12460. async function toggleVRRPState(id, disabled) {
  12461. try {
  12462. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  12463. method: 'POST',
  12464. headers: { 'Content-Type': 'application/json' },
  12465. body: JSON.stringify({ disabled })
  12466. });
  12467. if (res.ok) {
  12468. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  12469. loadVRRP(false);
  12470. fetchData(false);
  12471. } else {
  12472. const err = await res.text();
  12473. showToast('Error', err, 'error');
  12474. }
  12475. } catch (err) {
  12476. showToast('Error', err.message, 'error');
  12477. }
  12478. }
  12479. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  12480. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  12481. const docTableObserver = new MutationObserver((mutations) => {
  12482. let needsInit = false;
  12483. for (const m of mutations) {
  12484. for (const node of m.addedNodes) {
  12485. if (node.nodeType === 1) {
  12486. if (node.tagName === 'TABLE' || (node.querySelector && node.querySelector('table'))) {
  12487. needsInit = true;
  12488. break;
  12489. }
  12490. }
  12491. }
  12492. if (needsInit) break;
  12493. }
  12494. if (needsInit) {
  12495. initTableSorting();
  12496. }
  12497. });
  12498. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  12499. }
  12500. // =========================================================================
  12501. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  12502. // =========================================================================
  12503. const bwtestState = {
  12504. running: false,
  12505. pollTimer: null,
  12506. eventSource: null,
  12507. chartPoints: [],
  12508. maxChartPoints: 60,
  12509. serverConfig: null,
  12510. peakTx: 0,
  12511. peakRx: 0,
  12512. targetDuration: 10,
  12513. lastSampleIndex: 0
  12514. };
  12515. async function loadBwTestView() {
  12516. fetchBwTestServerStatus();
  12517. loadBwTestHistory();
  12518. resizeBwTestCanvas();
  12519. checkActiveBwTest();
  12520. }
  12521. async function fetchBwTestServerStatus() {
  12522. try {
  12523. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  12524. if (!res.ok) return;
  12525. const s = await res.json();
  12526. bwtestState.serverConfig = s;
  12527. // Update indicator and badges
  12528. const indicator = document.getElementById('bwtest-server-indicator');
  12529. const badge = document.getElementById('bwtest-server-badge');
  12530. const sideBadge = document.getElementById('badge-bwtest-server');
  12531. if (s.enabled && s.running) {
  12532. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  12533. if (badge) {
  12534. badge.innerText = `Port ${s.port} (Active)`;
  12535. badge.className = 'text-emerald-400 font-bold';
  12536. }
  12537. if (sideBadge) {
  12538. sideBadge.innerText = s.port;
  12539. sideBadge.className = 'text-[10px] bg-emerald-950 text-emerald-300 border border-emerald-800/40 px-1.5 py-0.2 rounded-full font-mono';
  12540. }
  12541. } else {
  12542. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  12543. if (badge) {
  12544. badge.innerText = `Disabled`;
  12545. badge.className = 'text-slate-500 font-bold';
  12546. }
  12547. if (sideBadge) {
  12548. sideBadge.innerText = 'Off';
  12549. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  12550. }
  12551. }
  12552. // Modal fields
  12553. const toggle = document.getElementById('bwtest-server-enable-toggle');
  12554. if (toggle) toggle.checked = !!s.enabled;
  12555. const portInp = document.getElementById('bwtest-server-port-input');
  12556. if (portInp) portInp.value = s.port || 2000;
  12557. const actSess = document.getElementById('bwtest-modal-active-sessions');
  12558. if (actSess) actSess.innerText = s.active_sessions || 0;
  12559. const totServ = document.getElementById('bwtest-modal-total-served');
  12560. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  12561. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  12562. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  12563. } catch (err) {
  12564. console.error('Failed to fetch BwTest server status:', err);
  12565. }
  12566. }
  12567. function openBwTestServerModal() {
  12568. fetchBwTestServerStatus();
  12569. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  12570. }
  12571. function closeBwTestServerModal() {
  12572. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  12573. }
  12574. async function submitBwTestServerSettings(e) {
  12575. e.preventDefault();
  12576. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  12577. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  12578. try {
  12579. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  12580. method: 'POST',
  12581. headers: { 'Content-Type': 'application/json' },
  12582. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  12583. });
  12584. if (!res.ok) {
  12585. const err = await res.json();
  12586. throw new Error(err.error || 'Failed to update server configuration');
  12587. }
  12588. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  12589. closeBwTestServerModal();
  12590. fetchBwTestServerStatus();
  12591. } catch (err) {
  12592. showToast('Server Configuration Error', err.message, 'error');
  12593. }
  12594. }
  12595. function setBwTestTarget(target) {
  12596. const inp = document.getElementById('bwtest-input-target');
  12597. if (inp) inp.value = target;
  12598. }
  12599. function setBwTestDirection(dir) {
  12600. const hiddenInp = document.getElementById('bwtest-input-direction');
  12601. if (hiddenInp) hiddenInp.value = dir;
  12602. const btnBoth = document.getElementById('bwtest-dir-both');
  12603. const btnTx = document.getElementById('bwtest-dir-tx');
  12604. const btnRx = document.getElementById('bwtest-dir-rx');
  12605. const activeCls = 'py-2 px-2 rounded-lg text-xs font-bold border transition text-center bg-emerald-600/20 border-emerald-500/50 text-emerald-300 shadow-sm';
  12606. const inactiveCls = 'py-2 px-2 rounded-lg text-xs font-medium border border-slate-800 bg-slate-950 text-slate-400 hover:text-white transition text-center';
  12607. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  12608. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  12609. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  12610. }
  12611. function setBwTestLimit(bps) {
  12612. const sel = document.getElementById('bwtest-input-limit');
  12613. if (sel) sel.value = String(bps);
  12614. }
  12615. async function checkActiveBwTest() {
  12616. try {
  12617. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  12618. if (!res.ok) return;
  12619. const st = await res.json();
  12620. if (st.running) {
  12621. setBwTestRunningUI(true);
  12622. if (st.current_sample) handleBwTestSample(st.current_sample);
  12623. startBwTestTelemetry();
  12624. }
  12625. } catch (err) {
  12626. console.error('Failed to check active BwTest:', err);
  12627. }
  12628. }
  12629. async function startBwTest(e) {
  12630. if (e && e.preventDefault) e.preventDefault();
  12631. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  12632. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  12633. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  12634. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  12635. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  12636. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  12637. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  12638. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  12639. bwtestState.targetDuration = duration;
  12640. bwtestState.chartPoints = [];
  12641. bwtestState.peakTx = 0;
  12642. bwtestState.peakRx = 0;
  12643. bwtestState.lastSampleIndex = 0;
  12644. // Clear UI elements
  12645. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  12646. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  12647. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  12648. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  12649. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  12650. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  12651. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  12652. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  12653. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  12654. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  12655. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  12656. const tbody = document.getElementById('bwtest-samples-tbody');
  12657. if (tbody) tbody.innerHTML = '';
  12658. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  12659. setBwTestRunningUI(true);
  12660. try {
  12661. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  12662. method: 'POST',
  12663. headers: { 'Content-Type': 'application/json' },
  12664. body: JSON.stringify({
  12665. target,
  12666. port,
  12667. direction,
  12668. protocol,
  12669. bandwidth_limit,
  12670. packet_size,
  12671. streams,
  12672. duration
  12673. })
  12674. });
  12675. if (!res.ok) {
  12676. const err = await res.json();
  12677. throw new Error(err.error || 'Failed to start bandwidth test');
  12678. }
  12679. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  12680. startBwTestTelemetry();
  12681. } catch (err) {
  12682. setBwTestRunningUI(false);
  12683. showToast('Start Failed', err.message, 'error');
  12684. }
  12685. }
  12686. function setBwTestRunningUI(running) {
  12687. bwtestState.running = running;
  12688. const startBtn = document.getElementById('bwtest-btn-start');
  12689. const stopBtn = document.getElementById('bwtest-btn-stop');
  12690. const badge = document.getElementById('bwtest-run-status-badge');
  12691. const ph = document.getElementById('bwtest-chart-placeholder');
  12692. if (running) {
  12693. if (startBtn) {
  12694. startBtn.disabled = true;
  12695. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  12696. }
  12697. if (stopBtn) {
  12698. stopBtn.disabled = false;
  12699. stopBtn.classList.remove('opacity-40');
  12700. }
  12701. if (badge) {
  12702. badge.innerText = 'TESTING...';
  12703. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 font-bold animate-pulse';
  12704. }
  12705. if (ph) ph.style.display = 'none';
  12706. } else {
  12707. if (startBtn) {
  12708. startBtn.disabled = false;
  12709. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  12710. }
  12711. if (stopBtn) {
  12712. stopBtn.disabled = true;
  12713. stopBtn.classList.add('opacity-40');
  12714. }
  12715. if (badge) {
  12716. badge.innerText = 'IDLE';
  12717. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  12718. }
  12719. }
  12720. }
  12721. async function stopBwTest() {
  12722. try {
  12723. await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  12724. showToast('Test Stopped', 'Bandwidth test terminated by user', 'info');
  12725. } catch (err) {
  12726. console.error('Failed to stop test:', err);
  12727. }
  12728. }
  12729. function startBwTestTelemetry() {
  12730. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  12731. bwtestState.pollTimer = setInterval(async () => {
  12732. try {
  12733. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  12734. if (!res.ok) return;
  12735. const st = await res.json();
  12736. if (st.recent_samples && st.recent_samples.length > 0) {
  12737. // Process new samples
  12738. const newSamples = st.recent_samples.slice(bwtestState.lastSampleIndex);
  12739. newSamples.forEach(s => handleBwTestSample(s));
  12740. bwtestState.lastSampleIndex = st.recent_samples.length;
  12741. }
  12742. if (!st.running) {
  12743. clearInterval(bwtestState.pollTimer);
  12744. bwtestState.pollTimer = null;
  12745. setBwTestRunningUI(false);
  12746. handleBwTestFinish(st.summary, st.error);
  12747. }
  12748. } catch (err) {
  12749. console.error('BwTest polling error:', err);
  12750. }
  12751. }, 400);
  12752. }
  12753. function handleBwTestSample(s) {
  12754. if (!s) return;
  12755. const txMbps = s.tx_mbps || 0;
  12756. const rxMbps = s.rx_mbps || 0;
  12757. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  12758. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  12759. // KPI updates
  12760. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  12761. if (elTx) elTx.innerText = txMbps.toFixed(2);
  12762. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  12763. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  12764. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  12765. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  12766. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  12767. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  12768. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  12769. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  12770. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  12771. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  12772. const elLoss = document.getElementById('bwtest-stat-loss');
  12773. if (elLoss) {
  12774. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  12775. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  12776. }
  12777. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  12778. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  12779. const elJitter = document.getElementById('bwtest-stat-jitter');
  12780. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  12781. const elTime = document.getElementById('bwtest-stat-time');
  12782. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  12783. const elData = document.getElementById('bwtest-stat-data');
  12784. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  12785. const elGraphRate = document.getElementById('bwtest-graph-rate');
  12786. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  12787. // Append point to chart buffer
  12788. bwtestState.chartPoints.push({
  12789. elapsed: s.elapsed_sec || 0,
  12790. tx: txMbps,
  12791. rx: rxMbps
  12792. });
  12793. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  12794. bwtestState.chartPoints.shift();
  12795. }
  12796. drawBwTestChart();
  12797. // Add row to breakdown table
  12798. const tbody = document.getElementById('bwtest-samples-tbody');
  12799. if (tbody) {
  12800. const tr = document.createElement('tr');
  12801. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  12802. tr.innerHTML = `
  12803. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  12804. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  12805. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  12806. <td class="py-1.5 px-3 ${(s.loss_pct > 1.0) ? 'text-rose-400 font-bold' : 'text-emerald-400'}">${(s.loss_pct || 0).toFixed(1)}%</td>
  12807. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  12808. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  12809. `;
  12810. tbody.insertBefore(tr, tbody.firstChild);
  12811. const countEl = document.getElementById('bwtest-sample-count');
  12812. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  12813. }
  12814. }
  12815. function handleBwTestFinish(summary, error) {
  12816. const badge = document.getElementById('bwtest-run-status-badge');
  12817. if (error) {
  12818. showToast('Benchmark Error', error, 'error');
  12819. if (badge) {
  12820. badge.innerText = 'ERROR';
  12821. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-rose-500/20 text-rose-300 border border-rose-500/40 font-bold';
  12822. }
  12823. } else if (summary) {
  12824. const avgTx = summary.avg_tx_mbps.toFixed(1);
  12825. const avgRx = summary.avg_rx_mbps.toFixed(1);
  12826. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  12827. if (badge) {
  12828. badge.innerText = 'COMPLETED';
  12829. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 font-bold';
  12830. }
  12831. }
  12832. loadBwTestHistory();
  12833. fetchBwTestServerStatus();
  12834. }
  12835. function resizeBwTestCanvas() {
  12836. const canvas = document.getElementById('bwtest-chart');
  12837. if (!canvas || !canvas.parentElement) return;
  12838. const rect = canvas.parentElement.getBoundingClientRect();
  12839. const dpr = window.devicePixelRatio || 1;
  12840. canvas.width = rect.width * dpr;
  12841. canvas.height = rect.height * dpr;
  12842. const ctx = canvas.getContext('2d');
  12843. ctx.scale(dpr, dpr);
  12844. drawBwTestChart();
  12845. }
  12846. window.addEventListener('resize', () => {
  12847. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  12848. });
  12849. function drawBwTestChart() {
  12850. const canvas = document.getElementById('bwtest-chart');
  12851. if (!canvas) return;
  12852. const ctx = canvas.getContext('2d');
  12853. const dpr = window.devicePixelRatio || 1;
  12854. const width = canvas.width / dpr;
  12855. const height = canvas.height / dpr;
  12856. ctx.clearRect(0, 0, width, height);
  12857. const points = bwtestState.chartPoints;
  12858. if (!points || points.length === 0) return;
  12859. // Determine scale ceiling
  12860. let maxRate = 10;
  12861. for (const p of points) {
  12862. if (p.tx > maxRate) maxRate = p.tx;
  12863. if (p.rx > maxRate) maxRate = p.rx;
  12864. }
  12865. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  12866. const paddingLeft = 55;
  12867. const paddingBottom = 24;
  12868. const paddingTop = 12;
  12869. const paddingRight = 16;
  12870. const chartW = width - paddingLeft - paddingRight;
  12871. const chartH = height - paddingTop - paddingBottom;
  12872. // Grid Lines and Y-Axis labels
  12873. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  12874. ctx.lineWidth = 1;
  12875. ctx.fillStyle = '#94a3b8';
  12876. ctx.font = '10px monospace';
  12877. ctx.textAlign = 'right';
  12878. const gridSteps = 4;
  12879. for (let i = 0; i <= gridSteps; i++) {
  12880. const val = (maxRate / gridSteps) * i;
  12881. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  12882. ctx.beginPath();
  12883. ctx.moveTo(paddingLeft, y);
  12884. ctx.lineTo(width - paddingRight, y);
  12885. ctx.stroke();
  12886. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  12887. }
  12888. // Draw TX Line (Cyan #22d3ee)
  12889. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  12890. // Draw RX Line (Purple #a855f7)
  12891. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  12892. }
  12893. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  12894. if (points.length < 2) return;
  12895. const stepX = w / Math.max(points.length - 1, 1);
  12896. // Gradient area fill
  12897. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  12898. grad.addColorStop(0, fillColor);
  12899. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  12900. ctx.beginPath();
  12901. points.forEach((p, idx) => {
  12902. const x = left + idx * stepX;
  12903. const val = valFn(p);
  12904. const y = top + h - (val / maxVal) * h;
  12905. if (idx === 0) {
  12906. ctx.moveTo(x, y);
  12907. } else {
  12908. ctx.lineTo(x, y);
  12909. }
  12910. });
  12911. // Complete path for fill
  12912. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  12913. ctx.lineTo(left, top + h);
  12914. ctx.closePath();
  12915. ctx.fillStyle = grad;
  12916. ctx.fill();
  12917. // Draw line stroke
  12918. ctx.beginPath();
  12919. ctx.lineWidth = 2.5;
  12920. ctx.strokeStyle = strokeColor;
  12921. points.forEach((p, idx) => {
  12922. const x = left + idx * stepX;
  12923. const val = valFn(p);
  12924. const y = top + h - (val / maxVal) * h;
  12925. if (idx === 0) {
  12926. ctx.moveTo(x, y);
  12927. } else {
  12928. ctx.lineTo(x, y);
  12929. }
  12930. });
  12931. ctx.stroke();
  12932. // Draw end point halo
  12933. const lastP = points[points.length - 1];
  12934. const lastX = left + (points.length - 1) * stepX;
  12935. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  12936. ctx.fillStyle = strokeColor;
  12937. ctx.beginPath();
  12938. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  12939. ctx.fill();
  12940. }
  12941. async function loadBwTestHistory() {
  12942. try {
  12943. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  12944. if (!res.ok) return;
  12945. const list = await res.json();
  12946. renderBwTestHistory(Array.isArray(list) ? list : []);
  12947. } catch (err) {
  12948. console.error('Failed to load BwTest history:', err);
  12949. }
  12950. }
  12951. function renderBwTestHistory(list) {
  12952. const tbody = document.getElementById('bwtest-history-tbody');
  12953. if (!tbody) return;
  12954. if (list.length === 0) {
  12955. tbody.innerHTML = `<tr><td colspan="10" class="p-6 text-center text-slate-500 text-xs font-sans">No past benchmark runs recorded yet.</td></tr>`;
  12956. return;
  12957. }
  12958. tbody.innerHTML = '';
  12959. list.forEach(item => {
  12960. const s = item.summary || {};
  12961. const tr = document.createElement('tr');
  12962. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  12963. const dirBadge = item.direction === 'both'
  12964. ? `<span class="px-1.5 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 uppercase font-semibold">Both</span>`
  12965. : item.direction === 'tx'
  12966. ? `<span class="px-1.5 py-0.5 rounded text-[10px] bg-cyan-500/20 text-cyan-300 border border-cyan-500/30 uppercase font-semibold">TX Only</span>`
  12967. : `<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-500/20 text-purple-300 border border-purple-500/30 uppercase font-semibold">RX Only</span>`;
  12968. const protoBadge = item.protocol === 'tcp'
  12969. ? `<span class="px-1.5 py-0.5 rounded text-[10px] bg-blue-500/20 text-blue-300 border border-blue-500/30 font-semibold uppercase">TCP</span>`
  12970. : `<span class="px-1.5 py-0.5 rounded text-[10px] bg-amber-500/20 text-amber-300 border border-amber-500/30 font-semibold uppercase">UDP</span>`;
  12971. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  12972. tr.innerHTML = `
  12973. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  12974. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  12975. <td class="py-2.5 px-4">${protoBadge}</td>
  12976. <td class="py-2.5 px-4">${dirBadge}</td>
  12977. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  12978. <td class="py-2.5 px-4 font-bold text-cyan-400 font-mono">${(s.avg_tx_mbps || 0).toFixed(1)} / ${(s.peak_tx_mbps || 0).toFixed(1)} <span class="text-[10px] text-slate-400 font-normal">Mbps</span></td>
  12979. <td class="py-2.5 px-4 font-bold text-purple-400 font-mono">${(s.avg_rx_mbps || 0).toFixed(1)} / ${(s.peak_rx_mbps || 0).toFixed(1)} <span class="text-[10px] text-slate-400 font-normal">Mbps</span></td>
  12980. <td class="py-2.5 px-4 ${(s.avg_loss_pct > 1.0) ? 'text-rose-400 font-bold' : 'text-emerald-400'} font-mono">${(s.avg_loss_pct || 0).toFixed(1)}% <span class="text-[10px] text-slate-400 font-normal">(${s.total_lost_packets || 0})</span></td>
  12981. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  12982. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  12983. `;
  12984. tbody.appendChild(tr);
  12985. });
  12986. }