app.js 587 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887
  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. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  130. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' }
  131. };
  132. const header = titles[tabName] || titles.dashboard;
  133. const pTitle = document.getElementById('page-title');
  134. if (pTitle) pTitle.innerText = header.title;
  135. const pSub = document.getElementById('page-subtitle');
  136. if (pSub) pSub.innerText = header.sub;
  137. // Toggle sections dynamically for all section elements
  138. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  139. if (el.id === `section-${tabName}`) {
  140. el.classList.remove('hidden');
  141. } else {
  142. el.classList.add('hidden');
  143. }
  144. });
  145. if (tabName === 'bridge') loadBridge();
  146. if (tabName === 'firewall') loadFirewall();
  147. if (tabName === 'routes') loadRoutes();
  148. if (tabName === 'bgp') {
  149. loadDynamicRouting();
  150. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  151. }
  152. if (tabName === 'ospf') {
  153. loadDynamicRouting();
  154. switchOspfTab(state.activeOspfTab || 'instances');
  155. }
  156. if (tabName === 'routing-filters') loadDynamicRouting();
  157. if (tabName === 'dynamic-routing') loadDynamicRouting();
  158. if (tabName === 'ppp') loadPPP();
  159. if (tabName === 'eoip') loadEoIP();
  160. if (tabName === 'aerotun') loadAeroTUN();
  161. if (tabName === 'persistence') loadDebianConfig();
  162. if (tabName === 'pppoe') loadPPPoE();
  163. if (tabName === 'wireguard') loadWireGuard();
  164. if (tabName === 'ipsec') loadIPSec();
  165. if (tabName === 'l2tp') loadL2TP();
  166. if (tabName === 'pptp') loadPPTP();
  167. if (tabName === 'tools') loadToolsView();
  168. if (tabName === 'dhcp-client') loadDHCPClients();
  169. if (tabName === 'dhcp-server') loadDHCPServer();
  170. if (tabName === 'vrrp') loadVRRP();
  171. setTimeout(initTableSorting, 50);
  172. }
  173. // Fetch all core system, network and VPN telemetry
  174. async function fetchData(isManual = false) {
  175. const spinner = document.getElementById('refresh-spinner');
  176. if (isManual && spinner) spinner.classList.add('animate-spin');
  177. try {
  178. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes] = await Promise.all([
  179. fetch(`${API_BASE}/system/status`),
  180. fetch(`${API_BASE}/interfaces`),
  181. fetch(`${API_BASE}/vlans`),
  182. fetch(`${API_BASE}/vpn/status`),
  183. fetch(`${API_BASE}/firewall/summary`),
  184. fetch(`${API_BASE}/routing/dynamic/summary`),
  185. fetch(`${API_BASE}/bridge/summary`),
  186. fetch(`${API_BASE}/dhcp/clients/summary`),
  187. fetch(`${API_BASE}/dhcp/clients`),
  188. fetch(`${API_BASE}/vrrp/summary`).catch(() => null)
  189. ]);
  190. if (vrrpSumRes && vrrpSumRes.ok) {
  191. state.vrrpSummary = await vrrpSumRes.json();
  192. renderVRRPSummary();
  193. }
  194. if (dhcpSumRes && dhcpSumRes.ok) {
  195. state.dhcpSummary = await dhcpSumRes.json();
  196. const bDhcp = document.getElementById('badge-dhcp-client-count');
  197. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  198. }
  199. if (dhcpClientsRes && dhcpClientsRes.ok) {
  200. state.dhcpClients = await dhcpClientsRes.json();
  201. }
  202. if (brSummaryRes.ok) {
  203. state.bridgeSummary = await brSummaryRes.json();
  204. const bBridge = document.getElementById('badge-bridge-count');
  205. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  206. const sBr = document.getElementById('bridge-stat-bridges');
  207. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  208. const sPorts = document.getElementById('bridge-stat-ports');
  209. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  210. const sHosts = document.getElementById('bridge-stat-hosts');
  211. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  212. }
  213. if (statusRes.ok) state.systemStatus = await statusRes.json();
  214. if (ifacesRes.ok) {
  215. const ifacesData = await ifacesRes.json();
  216. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  217. state.interfaces = rawIfaces.filter(i => {
  218. if (!i.name) return false;
  219. if (i.name.startsWith('ep_')) return false;
  220. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  221. });
  222. try { populateToolsInterfaces(); } catch (e) {}
  223. }
  224. if (vlansRes.ok) {
  225. const vlansData = await vlansRes.json();
  226. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  227. }
  228. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  229. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  230. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  231. updateSystemMetrics();
  232. updateBadges();
  233. if (state.activeTab === 'dashboard') renderDashboard();
  234. if (state.activeTab === 'interfaces') renderInterfacesList();
  235. if (state.activeTab === 'vlans') renderVlansList();
  236. if (state.activeTab === 'firewall') loadFirewall(false);
  237. if (state.activeTab === 'routes') loadRoutes(false);
  238. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  239. if (state.activeTab === 'ppp') loadPPP(false);
  240. if (state.activeTab === 'eoip') loadEoIP(false);
  241. if (state.activeTab === 'aerotun') loadAeroTUN(false);
  242. if (state.activeTab === 'pppoe') loadPPPoE(false);
  243. if (state.activeTab === 'wireguard') loadWireGuard(false);
  244. if (state.activeTab === 'ipsec') loadIPSec(false);
  245. if (state.activeTab === 'l2tp') loadL2TP(false);
  246. if (state.activeTab === 'pptp') loadPPTP(false);
  247. if (state.activeTab === 'dhcp-client') loadDHCPClients(false);
  248. if (state.activeTab === 'dhcp-server') loadDHCPServer(false);
  249. if (state.activeTab === 'vrrp') loadVRRP(false);
  250. } catch (err) {
  251. console.error('Failed to fetch router state:', err);
  252. } finally {
  253. if (isManual && spinner) {
  254. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  255. }
  256. }
  257. }
  258. // Update Top KPI and Sidebar Telemetry
  259. function updateSystemMetrics() {
  260. const s = state.systemStatus;
  261. const v = state.vpnStatus;
  262. if (!s) return;
  263. // Sidebar Host & Uptime
  264. const sideHost = document.getElementById('side-hostname');
  265. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  266. const sideUp = document.getElementById('side-uptime');
  267. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  268. const sideGw = document.getElementById('side-gateway-ip');
  269. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  270. // Compute CPU Metrics
  271. let cpuPct = 0;
  272. if (s.cpu_pct !== undefined) {
  273. cpuPct = s.cpu_pct;
  274. } else if (s.cpu_load && s.cpu_load.length > 0) {
  275. const cores = s.cpu_cores || 1;
  276. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  277. }
  278. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  279. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  280. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  281. // Sidebar CPU
  282. const sideCpuVal = document.getElementById('side-cpu-val');
  283. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  284. const sideCpuBar = document.getElementById('side-cpu-bar');
  285. if (sideCpuBar) {
  286. sideCpuBar.style.width = cpuWidth;
  287. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  288. }
  289. // Dashboard CPU Card
  290. const dashCpuVal = document.getElementById('dash-cpu-val');
  291. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  292. const dashCpuBar = document.getElementById('dash-cpu-bar');
  293. if (dashCpuBar) {
  294. dashCpuBar.style.width = cpuWidth;
  295. if (cpuPct > 85) {
  296. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  297. } else if (cpuPct > 65) {
  298. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  299. } else {
  300. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  301. }
  302. }
  303. const dashCpuCores = document.getElementById('dash-cpu-cores');
  304. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  305. const dashCpuLoad = document.getElementById('dash-cpu-load');
  306. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  307. const dashCpuStatus = document.getElementById('dash-cpu-status');
  308. if (dashCpuStatus) {
  309. if (cpuPct > 85) {
  310. dashCpuStatus.innerText = 'High';
  311. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  312. } else if (cpuPct > 65) {
  313. dashCpuStatus.innerText = 'Heavy';
  314. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  315. } else {
  316. dashCpuStatus.innerText = 'Normal';
  317. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  318. }
  319. }
  320. // Compute RAM Metrics
  321. const memPct = Math.round(s.mem_usage_pct || 0);
  322. const memPctStr = `${memPct}%`;
  323. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  324. const usedMB = s.mem_used_mb || 0;
  325. const totalMB = s.mem_total_mb || 0;
  326. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  327. function fmtMemMB(mb) {
  328. if (mb >= 1024) {
  329. return `${(mb / 1024).toFixed(1)} GB`;
  330. }
  331. return `${mb} MB`;
  332. }
  333. // Sidebar RAM
  334. const sideRamVal = document.getElementById('side-ram-val');
  335. if (sideRamVal) sideRamVal.innerText = memPctStr;
  336. const sideRamBar = document.getElementById('side-ram-bar');
  337. if (sideRamBar) sideRamBar.style.width = memWidth;
  338. // Dashboard RAM Card
  339. const dashRamVal = document.getElementById('dash-ram-val');
  340. if (dashRamVal) dashRamVal.innerText = memPctStr;
  341. const dashRamBar = document.getElementById('dash-ram-bar');
  342. if (dashRamBar) {
  343. dashRamBar.style.width = memWidth;
  344. if (memPct > 85) {
  345. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  346. } else if (memPct > 70) {
  347. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  348. } else {
  349. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  350. }
  351. }
  352. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  353. if (dashRamUsedTotal) {
  354. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  355. }
  356. const dashRamFree = document.getElementById('dash-ram-free');
  357. if (dashRamFree) {
  358. dashRamFree.innerText = fmtMemMB(freeMB);
  359. }
  360. const dashRamStatus = document.getElementById('dash-ram-status');
  361. if (dashRamStatus) {
  362. if (memPct > 85) {
  363. dashRamStatus.innerText = 'High';
  364. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  365. } else {
  366. dashRamStatus.innerText = 'Active';
  367. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  368. }
  369. }
  370. // Legacy Dashboard Stats (Safe checks)
  371. const elIfacesUp = document.getElementById('stat-ifaces-up');
  372. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  373. const elIfacesTot = document.getElementById('stat-ifaces-total');
  374. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  375. const elIfacesDown = document.getElementById('stat-ifaces-down');
  376. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  377. const elVlans = document.getElementById('stat-vlans-count');
  378. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  379. // VPN Status Indicators
  380. if (v) {
  381. const totalActive = v.total_active_tunnels || 0;
  382. const statVpnActive = document.getElementById('stat-vpn-active');
  383. if (statVpnActive) statVpnActive.innerText = totalActive;
  384. const tunnelsDot = document.getElementById('tunnels-dot');
  385. const tunnelsLabel = document.getElementById('tunnels-label');
  386. if (tunnelsDot && tunnelsLabel) {
  387. if (totalActive > 0) {
  388. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  389. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  390. } else {
  391. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  392. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  393. }
  394. }
  395. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  396. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  397. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  398. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  399. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  400. }
  401. // Total Live Bandwidth Rate
  402. let totalRx = 0;
  403. let totalTx = 0;
  404. (state.interfaces || []).forEach(i => {
  405. if (i.rate) {
  406. totalRx += i.rate.rx_bytes_sec || 0;
  407. totalTx += i.rate.tx_bytes_sec || 0;
  408. }
  409. });
  410. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  411. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  412. }
  413. function setDotBadge(id, active) {
  414. const el = document.getElementById(id);
  415. if (!el) return;
  416. if (active) {
  417. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  418. } else {
  419. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  420. }
  421. }
  422. function updateBadges() {
  423. const bIfaces = document.getElementById('badge-ifaces-count');
  424. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  425. const bVlans = document.getElementById('badge-vlans-count');
  426. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  427. if (state.fwSummary) {
  428. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  429. const badgeFw = document.getElementById('badge-firewall-count');
  430. if (badgeFw) badgeFw.innerText = totalFwRules;
  431. }
  432. if (state.vpnStatus) {
  433. const v = state.vpnStatus;
  434. const bEoIP = document.getElementById('badge-eoip-count');
  435. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  436. const bAero = document.getElementById('badge-aerotun-count');
  437. if (bAero) bAero.innerText = v.total_aerotun || 0;
  438. const bPPPSess = document.getElementById('badge-ppp-sessions');
  439. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  440. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  441. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  442. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  443. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  444. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  445. }
  446. if (state.dynSummary) {
  447. const d = state.dynSummary;
  448. setDotBadge('badge-bgp-dot', d.bgp_running);
  449. setDotBadge('badge-ospf-dot', d.ospf_running);
  450. const bBgp = document.getElementById('badge-bgp-count');
  451. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  452. const bOspf = document.getElementById('badge-ospf-count');
  453. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  454. const bFilters = document.getElementById('badge-filters-count');
  455. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  456. }
  457. const bDhcpServer = document.getElementById('badge-dhcp-server-count');
  458. if (bDhcpServer) {
  459. bDhcpServer.innerText = state.dhcpServerSummary ? (state.dhcpServerSummary.active_leases || state.dhcpServerSummary.total_servers || 0) : (state.dhcpServers || []).length;
  460. }
  461. }
  462. // Render Dashboard View
  463. function renderDashboard() {
  464. const matrix = document.getElementById('port-matrix');
  465. matrix.innerHTML = '';
  466. (state.interfaces || []).forEach(iface => {
  467. const isUp = iface.state === 'UP';
  468. const isVlan = iface.is_vlan;
  469. const portCard = document.createElement('div');
  470. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  471. isUp
  472. ? (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')
  473. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  474. }`;
  475. portCard.onclick = () => openIfaceModal(iface.name);
  476. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  477. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  478. portCard.innerHTML = `
  479. <div class="flex items-center justify-between mb-2">
  480. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  481. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  482. </div>
  483. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  484. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  485. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  486. <span>${iface.rate?.rx_human || '0 B/s'}</span>
  487. </div>
  488. `;
  489. matrix.appendChild(portCard);
  490. });
  491. const ifaceTbody = document.getElementById('quick-interfaces-table');
  492. if (ifaceTbody) {
  493. ifaceTbody.innerHTML = '';
  494. (state.interfaces || []).forEach(i => {
  495. const isUp = i.state === 'UP';
  496. const tr = document.createElement('tr');
  497. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  498. tr.onclick = () => openIfaceModal(i.name);
  499. const rxStr = i.rate?.rx_human || '0 B/s';
  500. const txStr = i.rate?.tx_human || '0 B/s';
  501. tr.innerHTML = `
  502. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  503. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  504. <span>${i.name}</span>
  505. </td>
  506. <td class="py-2.5 text-slate-300 font-sans">
  507. <span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 font-medium">${i.role || i.type || 'Ethernet'}</span>
  508. </td>
  509. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  510. <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>
  511. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  512. <span class="text-emerald-400">↓ ${rxStr}</span> <span class="text-slate-600">•</span> <span class="text-cyan-400">↑ ${txStr}</span>
  513. </td>
  514. <td class="py-2.5 text-right font-sans font-semibold">
  515. <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>
  516. </td>
  517. `;
  518. ifaceTbody.appendChild(tr);
  519. });
  520. }
  521. const vlanTbody = document.getElementById('quick-vlans-table');
  522. if (vlanTbody) {
  523. vlanTbody.innerHTML = '';
  524. }
  525. }
  526. // Expand / Collapse Handlers
  527. function toggleExpand(parentName) {
  528. if (state.expandedParents.has(parentName)) {
  529. state.expandedParents.delete(parentName);
  530. } else {
  531. state.expandedParents.add(parentName);
  532. }
  533. renderInterfacesList();
  534. }
  535. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  536. function supportsVLAN(iface) {
  537. if (!iface) return false;
  538. if (iface.is_vlan) return false;
  539. const name = (iface.name || '').toLowerCase();
  540. const type = (iface.type || '').toLowerCase();
  541. const role = (iface.role || '').toLowerCase();
  542. // Exclude loopback
  543. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  544. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  545. if (type === 'wireguard' || name.startsWith('wg')) return false;
  546. // Exclude PPP / PPPoE
  547. if (type === 'ppp' || name.startsWith('ppp')) return false;
  548. // Exclude other Layer 3 tunnels and dummy devices
  549. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  550. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  551. return false;
  552. }
  553. // If name already contains a dot, it's already a sub-interface
  554. if (name.includes('.')) return false;
  555. return true;
  556. }
  557. // Expand / Collapse Handlers
  558. function toggleExpand(parentName) {
  559. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  560. if (childVlans.length === 0) {
  561. // Cannot expand an interface with no VLANs
  562. state.expandedParents.delete(parentName);
  563. return;
  564. }
  565. if (state.expandedParents.has(parentName)) {
  566. state.expandedParents.delete(parentName);
  567. } else {
  568. state.expandedParents.add(parentName);
  569. }
  570. renderInterfacesList();
  571. }
  572. function expandAllIfaces(expand) {
  573. if (expand) {
  574. (state.interfaces || []).forEach(i => {
  575. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  576. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  577. });
  578. } else {
  579. state.expandedParents.clear();
  580. }
  581. renderInterfacesList();
  582. }
  583. // Filter and Render Hierarchical Interfaces List
  584. function filterIfaces(filter) {
  585. state.ifaceFilter = filter || 'all';
  586. renderInterfacesList();
  587. }
  588. function renderInterfacesList() {
  589. const tbody = document.getElementById('interfaces-tree-tbody');
  590. const emptyState = document.getElementById('interfaces-empty-state');
  591. const summary = document.getElementById('ifaces-list-summary');
  592. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  593. tbody.innerHTML = '';
  594. const allIfaces = state.interfaces || [];
  595. const allVlans = state.vlans || [];
  596. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  597. const filteredParents = parentIfaces.filter(parent => {
  598. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  599. if (query) {
  600. const matchName = parent.name.toLowerCase().includes(query);
  601. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  602. const matchRole = (parent.role || '').toLowerCase().includes(query);
  603. const matchType = (parent.type || '').toLowerCase().includes(query);
  604. const matchVlan = childVlans.some(v =>
  605. v.name.toLowerCase().includes(query) ||
  606. String(v.vlan_id).includes(query) ||
  607. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  608. (v.description || '').toLowerCase().includes(query)
  609. );
  610. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  611. }
  612. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  613. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  614. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  615. return true;
  616. });
  617. if (summary) {
  618. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  619. }
  620. if (filteredParents.length === 0) {
  621. emptyState?.classList.remove('hidden');
  622. return;
  623. }
  624. emptyState?.classList.add('hidden');
  625. filteredParents.forEach(parent => {
  626. const isUp = parent.state === 'UP';
  627. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  628. const hasVlans = childVlans.length > 0;
  629. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  630. const canHaveVlan = supportsVLAN(parent);
  631. const parentRow = document.createElement('tr');
  632. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  633. parentRow.innerHTML = `
  634. <td class="py-3 px-3 text-center">
  635. ${hasVlans ? `
  636. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  637. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  638. <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">
  639. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  640. </svg>
  641. </button>
  642. ` : `
  643. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  644. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  645. </div>
  646. `}
  647. </td>
  648. <td class="py-3 px-4">
  649. <div class="flex items-center space-x-2.5">
  650. <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">
  651. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  652. </div>
  653. <div>
  654. <div class="flex items-center gap-2">
  655. ${hasVlans ? `
  656. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400" onclick="toggleExpand('${parent.name}')">${parent.name}</span>
  657. <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>
  658. ` : `
  659. <span class="font-bold text-white text-sm">${parent.name}</span>
  660. <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>
  661. `}
  662. </div>
  663. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  664. </div>
  665. </div>
  666. </td>
  667. <td class="py-3 px-4 font-sans">
  668. <div class="flex items-center gap-1.5">
  669. <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>
  670. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  671. </div>
  672. </td>
  673. <td class="py-3 px-4">
  674. ${parent.ipv4 && parent.ipv4.length > 0
  675. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  676. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  677. }
  678. ${(() => {
  679. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  680. if (!c) return '';
  681. 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');
  682. 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>`;
  683. })()}
  684. </td>
  685. <td class="py-3 px-4 text-slate-400 text-[11px]">
  686. <div>${parent.mac || 'N/A'}</div>
  687. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  688. </td>
  689. <td class="py-3 px-4 text-[11px]">
  690. <div class="flex items-center space-x-2">
  691. <span class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  692. <span class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  693. </div>
  694. </td>
  695. <td class="py-3 px-4 font-sans">
  696. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  697. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  698. 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'
  699. }" title="Click to toggle link status">
  700. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  701. <span>${parent.state}</span>
  702. </button>
  703. </td>
  704. <td class="py-3 px-4 text-right space-x-2 font-sans">
  705. ${(() => {
  706. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  707. if (c) {
  708. 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>`;
  709. }
  710. 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>`;
  711. })()}
  712. ${canHaveVlan ? `
  713. <button onclick="openVlanModal('${parent.name}')"
  714. 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">
  715. + Add VLAN
  716. </button>
  717. ` : ''}
  718. <button onclick="openIfaceModal('${parent.name}')"
  719. 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">
  720. Configure
  721. </button>
  722. </td>
  723. `;
  724. tbody.appendChild(parentRow);
  725. if (isExpanded) {
  726. const drawerRow = document.createElement('tr');
  727. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  728. const drawerCell = document.createElement('td');
  729. drawerCell.colSpan = 8;
  730. drawerCell.className = 'p-0';
  731. drawerCell.innerHTML = `
  732. <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">
  733. <div class="flex items-center justify-between mb-3">
  734. <div class="flex items-center space-x-3">
  735. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  736. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  737. </span>
  738. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  739. ${childVlans.length} Attached
  740. </span>
  741. </div>
  742. <button onclick="openVlanModal('${parent.name}')"
  743. 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">
  744. <span>+ Create VLAN on ${parent.name}</span>
  745. </button>
  746. </div>
  747. ${childVlans.length === 0 ? `
  748. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  749. <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>
  750. <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">
  751. <span>+ Create Your First VLAN on ${parent.name}</span>
  752. </button>
  753. </div>
  754. ` : `
  755. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  756. <table class="w-full text-left text-xs font-mono">
  757. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  758. <tr>
  759. <th class="py-2.5 px-4">VLAN ID</th>
  760. <th class="py-2.5 px-4">Interface Device</th>
  761. <th class="py-2.5 px-4">Subnet Gateway</th>
  762. <th class="py-2.5 px-4">Role / Alias</th>
  763. <th class="py-2.5 px-4">MTU</th>
  764. <th class="py-2.5 px-4">Throughput</th>
  765. <th class="py-2.5 px-4">Status</th>
  766. <th class="py-2.5 px-4 text-right">Actions</th>
  767. </tr>
  768. </thead>
  769. <tbody class="divide-y divide-slate-800/70">
  770. ${childVlans.map(v => {
  771. const isVlanUp = v.state === 'UP';
  772. return `
  773. <tr class="hover:bg-slate-800/40 transition">
  774. <td class="py-2.5 px-4">
  775. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  776. VLAN ${v.vlan_id}
  777. </span>
  778. </td>
  779. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  780. <span class="text-cyan-500">└─</span>
  781. <span>${v.name}</span>
  782. </td>
  783. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  784. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  785. ${(() => {
  786. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  787. if (!c) return '';
  788. 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';
  789. 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>`;
  790. })()}
  791. </td>
  792. <td class="py-2.5 px-4 font-sans text-slate-300">
  793. <span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 mr-1.5">${v.role || 'VLAN'}</span>
  794. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  795. </td>
  796. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  797. <td class="py-2.5 px-4 text-[11px]">
  798. <span class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  799. <span class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  800. </td>
  801. <td class="py-2.5 px-4 font-sans">
  802. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  803. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  804. 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'
  805. }">
  806. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  807. <span>${v.state}</span>
  808. </button>
  809. </td>
  810. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  811. ${(() => {
  812. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  813. if (c) {
  814. 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>`;
  815. }
  816. 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>`;
  817. })()}
  818. <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>
  819. <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>
  820. </td>
  821. </tr>
  822. `;
  823. }).join('')}
  824. </tbody>
  825. </table>
  826. </div>
  827. `}
  828. </div>
  829. `;
  830. drawerRow.appendChild(drawerCell);
  831. tbody.appendChild(drawerRow);
  832. }
  833. });
  834. }
  835. // Render VLANs Dedicated View
  836. function renderVlansList() {
  837. const tbody = document.getElementById('vlans-table-body');
  838. if (!tbody) return;
  839. const emptyState = document.getElementById('vlans-empty-state');
  840. const countBadge = document.getElementById('vlans-table-count');
  841. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  842. tbody.innerHTML = '';
  843. const allVlans = state.vlans || [];
  844. if (countBadge) countBadge.innerText = allVlans.length;
  845. const filtered = allVlans.filter(v => {
  846. if (!query) return true;
  847. return v.name.toLowerCase().includes(query) ||
  848. String(v.vlan_id).includes(query) ||
  849. (v.description || '').toLowerCase().includes(query) ||
  850. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  851. });
  852. if (allVlans.length === 0) {
  853. emptyState.classList.remove('hidden');
  854. return;
  855. }
  856. emptyState.classList.add('hidden');
  857. filtered.forEach(v => {
  858. const isUp = v.state === 'UP';
  859. const tr = document.createElement('tr');
  860. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  861. tr.innerHTML = `
  862. <td class="py-3 px-4">
  863. <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">
  864. VLAN ${v.vlan_id}
  865. </span>
  866. </td>
  867. <td class="py-3 px-4 font-bold text-white">${v.name}</td>
  868. <td class="py-3 px-4 text-slate-300">
  869. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  870. </td>
  871. <td class="py-3 px-4 text-emerald-400 font-medium">
  872. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  873. </td>
  874. <td class="py-3 px-4 text-slate-300 font-sans">
  875. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  876. </td>
  877. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  878. <td class="py-3 px-4 font-sans">
  879. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  880. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  881. 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'
  882. }">
  883. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  884. <span>${v.state}</span>
  885. </button>
  886. </td>
  887. <td class="py-3 px-4 text-right space-x-2 font-sans">
  888. <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>
  889. <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>
  890. </td>
  891. `;
  892. tbody.appendChild(tr);
  893. });
  894. }
  895. // Toggle interface UP / DOWN
  896. async function toggleInterfaceState(name, newState) {
  897. try {
  898. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  899. method: 'POST',
  900. headers: { 'Content-Type': 'application/json' },
  901. body: JSON.stringify({ state: newState })
  902. });
  903. const data = await res.json();
  904. if (res.ok) {
  905. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  906. fetchData(false);
  907. } else {
  908. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  909. }
  910. } catch (err) {
  911. showToast('Error', err.message, 'error');
  912. }
  913. }
  914. // ---------------- MikroTik Flag & Utilities ----------------
  915. function renderMikroTikFlag(running, disabled) {
  916. if (running) {
  917. 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>`;
  918. }
  919. if (disabled) {
  920. 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>`;
  921. }
  922. 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>`;
  923. }
  924. function copyToClipboard(text, label = 'Text') {
  925. navigator.clipboard.writeText(text).then(() => {
  926. showToast('Copied', `${label} copied to clipboard`, 'success');
  927. }).catch(() => {
  928. prompt('Copy value:', text);
  929. });
  930. }
  931. // ======================== PPP Profiles Shared Helper ========================
  932. async function fetchPPPProfilesList() {
  933. try {
  934. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  935. if (res.ok) {
  936. state.pppProfiles = await res.json();
  937. }
  938. } catch (err) {
  939. console.error('Failed to load PPP profiles:', err);
  940. }
  941. }
  942. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  943. const sel = document.getElementById(selectId);
  944. if (!sel) return;
  945. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  946. { name: 'default', use_encryption: 'no' },
  947. { name: 'default-encryption', use_encryption: 'required' }
  948. ];
  949. sel.innerHTML = '';
  950. profiles.forEach(p => {
  951. const opt = document.createElement('option');
  952. opt.value = p.name;
  953. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  954. opt.innerText = `${p.name}${encBadge}`;
  955. sel.appendChild(opt);
  956. });
  957. if (selectedVal) {
  958. sel.value = selectedVal;
  959. } else {
  960. sel.value = defaultVal;
  961. }
  962. if (!sel.value && sel.options.length > 0) {
  963. sel.selectedIndex = 0;
  964. }
  965. }
  966. // ======================== PPPoE Multi-Instance ========================
  967. async function loadPPPoE(populateInputs = true) {
  968. try {
  969. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  970. await fetchPPPProfilesList();
  971. }
  972. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  973. const list = await res.json();
  974. state.pppoeList = Array.isArray(list) ? list : [];
  975. const badge = document.getElementById('pppoe-count-badge');
  976. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  977. const tbody = document.getElementById('pppoe-table-body');
  978. const empty = document.getElementById('pppoe-empty');
  979. if (!tbody) return;
  980. tbody.innerHTML = '';
  981. if (state.pppoeList.length === 0) {
  982. if (empty) empty.classList.remove('hidden');
  983. } else {
  984. if (empty) empty.classList.add('hidden');
  985. state.pppoeList.forEach(inst => {
  986. const tr = document.createElement('tr');
  987. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  988. tr.innerHTML = `
  989. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  990. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  991. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  992. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  993. <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>
  994. <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>
  995. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  996. <td class="py-2.5 px-3 text-center">
  997. <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'}">
  998. ${inst.default_route ? 'Yes' : 'No'}
  999. </span>
  1000. </td>
  1001. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1002. ${inst.running ? `
  1003. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1004. ` : `
  1005. <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>
  1006. `}
  1007. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1008. ${inst.disabled ? 'Enable' : 'Disable'}
  1009. </button>
  1010. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1011. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1012. </td>
  1013. `;
  1014. tbody.appendChild(tr);
  1015. });
  1016. }
  1017. } catch (err) {
  1018. console.error('Failed to load PPPoE:', err);
  1019. }
  1020. }
  1021. function openAddPPPoEModal() {
  1022. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  1023. document.getElementById('pppoe-modal-edit-orig').value = '';
  1024. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  1025. document.getElementById('pppoe-modal-name').readOnly = false;
  1026. document.getElementById('pppoe-modal-user').value = '';
  1027. document.getElementById('pppoe-modal-pass').value = '';
  1028. document.getElementById('pppoe-modal-service').value = '';
  1029. document.getElementById('pppoe-modal-mtu').value = '1492';
  1030. document.getElementById('pppoe-modal-defroute').checked = true;
  1031. document.getElementById('pppoe-modal-reconnect').checked = true;
  1032. document.getElementById('pppoe-modal-disabled').checked = false;
  1033. // Populate profiles
  1034. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1035. // Populate interfaces
  1036. const sel = document.getElementById('pppoe-modal-iface');
  1037. sel.innerHTML = '';
  1038. (state.interfaces || []).forEach(i => {
  1039. if (i.name === 'lo') return;
  1040. const opt = document.createElement('option');
  1041. opt.value = i.name;
  1042. opt.innerText = `${i.name} (${i.role || i.type})`;
  1043. sel.appendChild(opt);
  1044. });
  1045. document.getElementById('pppoe-modal').classList.remove('hidden');
  1046. }
  1047. function openEditPPPoEModal(name) {
  1048. const inst = (state.pppoeList || []).find(i => i.name === name);
  1049. if (!inst) return;
  1050. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1051. document.getElementById('pppoe-modal-edit-orig').value = name;
  1052. document.getElementById('pppoe-modal-name').value = inst.name;
  1053. document.getElementById('pppoe-modal-name').readOnly = true;
  1054. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1055. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1056. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1057. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1058. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1059. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1060. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1061. // Populate profiles
  1062. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1063. const sel = document.getElementById('pppoe-modal-iface');
  1064. sel.innerHTML = '';
  1065. (state.interfaces || []).forEach(i => {
  1066. if (i.name === 'lo') return;
  1067. const opt = document.createElement('option');
  1068. opt.value = i.name;
  1069. opt.innerText = `${i.name} (${i.role || i.type})`;
  1070. if (i.name === inst.interface) opt.selected = true;
  1071. sel.appendChild(opt);
  1072. });
  1073. document.getElementById('pppoe-modal').classList.remove('hidden');
  1074. }
  1075. function closePPPoEModal() {
  1076. document.getElementById('pppoe-modal').classList.add('hidden');
  1077. }
  1078. async function submitSavePPPoE(e) {
  1079. e.preventDefault();
  1080. const name = document.getElementById('pppoe-modal-name').value.trim();
  1081. const iface = document.getElementById('pppoe-modal-iface').value;
  1082. const user = document.getElementById('pppoe-modal-user').value.trim();
  1083. const pass = document.getElementById('pppoe-modal-pass').value;
  1084. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1085. const service = document.getElementById('pppoe-modal-service').value.trim();
  1086. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1087. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1088. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1089. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1090. try {
  1091. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1092. method: 'POST',
  1093. headers: { 'Content-Type': 'application/json' },
  1094. body: JSON.stringify({
  1095. name,
  1096. interface: iface,
  1097. username: user,
  1098. password: pass,
  1099. profile: profile,
  1100. service_name: service,
  1101. mtu,
  1102. default_route: defRoute,
  1103. auto_reconnect: reconnect,
  1104. disabled
  1105. })
  1106. });
  1107. if (res.ok) {
  1108. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1109. closePPPoEModal();
  1110. loadPPPoE(false);
  1111. fetchData(false);
  1112. } else {
  1113. const err = await res.json();
  1114. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1115. }
  1116. } catch (err) {
  1117. showToast('Error', err.message, 'error');
  1118. }
  1119. }
  1120. async function connectPPPoEInstance(name) {
  1121. try {
  1122. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1123. if (res.ok) {
  1124. showToast('Connecting', `Dialing ${name}...`, 'info');
  1125. setTimeout(() => loadPPPoE(false), 2000);
  1126. }
  1127. } catch (err) {
  1128. showToast('Error', err.message, 'error');
  1129. }
  1130. }
  1131. async function disconnectPPPoEInstance(name) {
  1132. try {
  1133. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1134. if (res.ok) {
  1135. showToast('Disconnected', `${name} session terminated`, 'info');
  1136. setTimeout(() => loadPPPoE(false), 1000);
  1137. }
  1138. } catch (err) {
  1139. showToast('Error', err.message, 'error');
  1140. }
  1141. }
  1142. async function togglePPPoEState(name, enable) {
  1143. try {
  1144. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1145. method: 'POST',
  1146. headers: { 'Content-Type': 'application/json' },
  1147. body: JSON.stringify({ enabled: enable })
  1148. });
  1149. if (res.ok) {
  1150. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1151. loadPPPoE(false);
  1152. }
  1153. } catch (err) {
  1154. showToast('Error', err.message, 'error');
  1155. }
  1156. }
  1157. async function deletePPPoEInstance(name) {
  1158. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1159. try {
  1160. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1161. if (res.ok) {
  1162. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1163. loadPPPoE(false);
  1164. fetchData(false);
  1165. }
  1166. } catch (err) {
  1167. showToast('Error', err.message, 'error');
  1168. }
  1169. }
  1170. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1171. state.wgSubTab = 'ifaces';
  1172. function switchWGSubTab(tab) {
  1173. state.wgSubTab = tab;
  1174. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1175. const peersPanel = document.getElementById('wg-subtab-peers');
  1176. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1177. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1178. if (tab === 'ifaces') {
  1179. ifacesPanel?.classList.remove('hidden');
  1180. peersPanel?.classList.add('hidden');
  1181. 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';
  1182. 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';
  1183. } else {
  1184. ifacesPanel?.classList.add('hidden');
  1185. peersPanel?.classList.remove('hidden');
  1186. 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';
  1187. 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';
  1188. renderWGPeers();
  1189. }
  1190. }
  1191. async function loadWireGuard(populateInputs = true) {
  1192. try {
  1193. const [ifacesRes, peersRes] = await Promise.all([
  1194. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1195. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1196. ]);
  1197. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1198. const peers = peersRes.ok ? await peersRes.json() : [];
  1199. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1200. state.wgPeers = Array.isArray(peers) ? peers : [];
  1201. // Badges
  1202. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1203. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1204. const peersCountBadge = document.getElementById('wg-peers-count');
  1205. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1206. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1207. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1208. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1209. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1210. // Render Interfaces
  1211. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1212. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1213. if (ifacesTbody) {
  1214. ifacesTbody.innerHTML = '';
  1215. if (state.wgInterfaces.length === 0) {
  1216. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1217. } else {
  1218. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1219. state.wgInterfaces.forEach(iface => {
  1220. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1221. const tr = document.createElement('tr');
  1222. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1223. tr.innerHTML = `
  1224. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1225. <td class="py-2.5 px-3">
  1226. <div class="flex items-center gap-1.5">
  1227. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1228. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1229. </div>
  1230. </td>
  1231. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1232. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1233. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1234. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1235. ${(iface.public_key || '').substring(0, 10)}... 📋
  1236. </span>
  1237. </td>
  1238. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1239. <td class="py-2.5 px-3 text-center">
  1240. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1241. </td>
  1242. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1243. ${iface.running ? `
  1244. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1245. ` : `
  1246. <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>
  1247. `}
  1248. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1249. ${iface.disabled ? 'Enable' : 'Disable'}
  1250. </button>
  1251. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1252. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1253. </td>
  1254. `;
  1255. ifacesTbody.appendChild(tr);
  1256. });
  1257. }
  1258. }
  1259. // Populate filter dropdown in peers tab
  1260. const filterSel = document.getElementById('wg-peers-filter-iface');
  1261. if (filterSel) {
  1262. const currentVal = filterSel.value;
  1263. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1264. state.wgInterfaces.forEach(i => {
  1265. const opt = document.createElement('option');
  1266. opt.value = i.name;
  1267. opt.innerText = i.name;
  1268. if (i.name === currentVal) opt.selected = true;
  1269. filterSel.appendChild(opt);
  1270. });
  1271. }
  1272. renderWGPeers();
  1273. } catch (err) {
  1274. console.error('Failed to load WireGuard:', err);
  1275. }
  1276. }
  1277. function renderWGPeers() {
  1278. const filterSel = document.getElementById('wg-peers-filter-iface');
  1279. const selectedIface = filterSel ? filterSel.value : '';
  1280. const tbody = document.getElementById('wg-peers-table-body');
  1281. const empty = document.getElementById('wg-peers-empty');
  1282. if (!tbody) return;
  1283. tbody.innerHTML = '';
  1284. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1285. if (filtered.length === 0) {
  1286. if (empty) empty.classList.remove('hidden');
  1287. } else {
  1288. if (empty) empty.classList.add('hidden');
  1289. filtered.forEach(p => {
  1290. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1291. const tr = document.createElement('tr');
  1292. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1293. tr.innerHTML = `
  1294. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1295. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1296. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1297. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1298. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1299. ${(p.public_key || '').substring(0, 10)}... 📋
  1300. </span>
  1301. </td>
  1302. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1303. <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>
  1304. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1305. <td class="py-2.5 px-3 font-mono text-[11px]">
  1306. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1307. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1308. </td>
  1309. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1310. <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">
  1311. ${p.disabled ? 'Enable' : 'Disable'}
  1312. </button>
  1313. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1314. <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>
  1315. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1316. </td>
  1317. `;
  1318. tbody.appendChild(tr);
  1319. });
  1320. }
  1321. }
  1322. function openAddWGInterfaceModal() {
  1323. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1324. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1325. const nameEl = document.getElementById('wg-iface-modal-name');
  1326. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1327. nameEl.readOnly = false;
  1328. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1329. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1330. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1331. document.getElementById('wg-iface-modal-comment').value = '';
  1332. document.getElementById('wg-iface-modal-pubkey').value = '';
  1333. document.getElementById('wg-iface-modal-privkey').value = '';
  1334. document.getElementById('wg-iface-modal-disabled').checked = false;
  1335. generateWGInterfaceKeys();
  1336. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1337. }
  1338. function openEditWGInterfaceModal(name) {
  1339. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1340. if (!iface) return;
  1341. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1342. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1343. const nameEl = document.getElementById('wg-iface-modal-name');
  1344. nameEl.value = iface.name;
  1345. nameEl.readOnly = false; // ALLOW RENAMING
  1346. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1347. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1348. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1349. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1350. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1351. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1352. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1353. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1354. }
  1355. function closeAddWGInterfaceModal() {
  1356. document.getElementById('wg-iface-modal').classList.add('hidden');
  1357. }
  1358. async function generateWGInterfaceKeys() {
  1359. try {
  1360. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1361. const keys = await res.json();
  1362. if (res.ok) {
  1363. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1364. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1365. }
  1366. } catch (err) {
  1367. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1368. }
  1369. }
  1370. async function onWGInterfacePrivKeyInput() {
  1371. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1372. if (!privKey) return;
  1373. try {
  1374. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1375. method: 'POST',
  1376. headers: { 'Content-Type': 'application/json' },
  1377. body: JSON.stringify({ private_key: privKey })
  1378. });
  1379. if (res.ok) {
  1380. const data = await res.json();
  1381. if (data.public_key) {
  1382. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1383. }
  1384. }
  1385. } catch (err) {
  1386. // Ignore while typing
  1387. }
  1388. }
  1389. function toggleWGPrivKeyVisibility() {
  1390. const el = document.getElementById('wg-iface-modal-privkey');
  1391. const btn = document.getElementById('btn-toggle-wg-privkey');
  1392. if (el.type === 'password') {
  1393. el.type = 'text';
  1394. btn.innerText = '🙈 Hide';
  1395. } else {
  1396. el.type = 'password';
  1397. btn.innerText = '👁️ Show';
  1398. }
  1399. }
  1400. function copyWGInterfacePubKey() {
  1401. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1402. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1403. }
  1404. async function submitSaveWGInterface(e) {
  1405. e.preventDefault();
  1406. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1407. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1408. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1409. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1410. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1411. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1412. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1413. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1414. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1415. try {
  1416. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1417. method: 'POST',
  1418. headers: { 'Content-Type': 'application/json' },
  1419. body: JSON.stringify({
  1420. orig_name: origName,
  1421. name,
  1422. listen_port: port,
  1423. address: addr,
  1424. mtu,
  1425. comment,
  1426. public_key: pub,
  1427. private_key: priv,
  1428. disabled
  1429. })
  1430. });
  1431. const data = await res.json();
  1432. if (res.ok) {
  1433. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1434. closeAddWGInterfaceModal();
  1435. loadWireGuard(false);
  1436. fetchData(false);
  1437. } else {
  1438. showToast('Error', data.error || 'Failed to save interface', 'error');
  1439. }
  1440. } catch (err) {
  1441. showToast('Error', err.message, 'error');
  1442. }
  1443. }
  1444. async function startWGInterface(name) {
  1445. try {
  1446. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1447. if (res.ok) {
  1448. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1449. loadWireGuard(false);
  1450. fetchData(false);
  1451. }
  1452. } catch (err) {
  1453. showToast('Error', err.message, 'error');
  1454. }
  1455. }
  1456. async function stopWGInterface(name) {
  1457. try {
  1458. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1459. if (res.ok) {
  1460. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1461. loadWireGuard(false);
  1462. fetchData(false);
  1463. }
  1464. } catch (err) {
  1465. showToast('Error', err.message, 'error');
  1466. }
  1467. }
  1468. async function toggleWGInterfaceState(name, enable) {
  1469. try {
  1470. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1471. method: 'POST',
  1472. headers: { 'Content-Type': 'application/json' },
  1473. body: JSON.stringify({ enabled: enable })
  1474. });
  1475. if (res.ok) {
  1476. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1477. loadWireGuard(false);
  1478. fetchData(false);
  1479. }
  1480. } catch (err) {
  1481. showToast('Error', err.message, 'error');
  1482. }
  1483. }
  1484. async function deleteWGInterface(name) {
  1485. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1486. try {
  1487. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1488. if (res.ok) {
  1489. showToast('Deleted', `Interface ${name} removed`, 'success');
  1490. loadWireGuard(false);
  1491. fetchData(false);
  1492. }
  1493. } catch (err) {
  1494. showToast('Error', err.message, 'error');
  1495. }
  1496. }
  1497. function populateWGPeerIfaceSelect(selectedIface = '') {
  1498. const sel = document.getElementById('wg-peer-modal-iface');
  1499. if (!sel) return;
  1500. sel.innerHTML = '';
  1501. (state.wgInterfaces || []).forEach(i => {
  1502. const opt = document.createElement('option');
  1503. opt.value = i.name;
  1504. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1505. if (i.name === selectedIface) opt.selected = true;
  1506. sel.appendChild(opt);
  1507. });
  1508. }
  1509. function openAddWGPeerModal() {
  1510. if ((state.wgInterfaces || []).length === 0) {
  1511. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1512. openAddWGInterfaceModal();
  1513. return;
  1514. }
  1515. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  1516. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  1517. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  1518. populateWGPeerIfaceSelect();
  1519. document.getElementById('wg-peer-modal-name').value = '';
  1520. document.getElementById('wg-peer-modal-pubkey').value = '';
  1521. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1522. document.getElementById('wg-peer-modal-endpoint').value = '';
  1523. document.getElementById('wg-peer-modal-port').value = '';
  1524. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1525. document.getElementById('wg-peer-modal-preshared').value = '';
  1526. document.getElementById('wg-peer-modal-disabled').checked = false;
  1527. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1528. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1529. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1530. }
  1531. function openEditWGPeerModal(ifaceName, pubKey) {
  1532. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  1533. if (!peer) {
  1534. showToast('Not Found', 'Peer not found', 'warning');
  1535. return;
  1536. }
  1537. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  1538. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  1539. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  1540. populateWGPeerIfaceSelect(peer.interface);
  1541. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  1542. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  1543. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  1544. document.getElementById('wg-peer-modal-endpoint').value = peer.endpoint_address || '';
  1545. document.getElementById('wg-peer-modal-port').value = peer.endpoint_port || '';
  1546. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  1547. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  1548. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  1549. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1550. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1551. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1552. }
  1553. function closeAddWGPeerModal() {
  1554. document.getElementById('wg-peer-modal').classList.add('hidden');
  1555. }
  1556. async function generatePeerKeypairHelper() {
  1557. try {
  1558. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1559. const keys = await res.json();
  1560. if (res.ok) {
  1561. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  1562. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  1563. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  1564. checkWGPeerKeyValidity();
  1565. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  1566. }
  1567. } catch (err) {
  1568. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1569. }
  1570. }
  1571. function copyGeneratedPeerPrivKey() {
  1572. const priv = document.getElementById('wg-peer-gen-privkey').value;
  1573. if (priv) copyToClipboard(priv, 'Client Private Key');
  1574. }
  1575. async function generatePeerPSK() {
  1576. try {
  1577. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1578. const keys = await res.json();
  1579. if (res.ok && keys.private_key) {
  1580. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  1581. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  1582. }
  1583. } catch (err) {
  1584. showToast('Error', err.message, 'error');
  1585. }
  1586. }
  1587. function checkWGPeerKeyValidity() {
  1588. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  1589. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1590. const warningEl = document.getElementById('wg-peer-key-warning');
  1591. if (!warningEl) return;
  1592. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  1593. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  1594. warningEl.classList.remove('hidden');
  1595. } else {
  1596. warningEl.classList.add('hidden');
  1597. }
  1598. }
  1599. async function submitSaveWGPeer(e) {
  1600. e.preventDefault();
  1601. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  1602. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  1603. const iface = document.getElementById('wg-peer-modal-iface').value;
  1604. const name = document.getElementById('wg-peer-modal-name').value.trim();
  1605. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1606. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  1607. .split(',')
  1608. .map(s => s.trim())
  1609. .filter(s => s.length > 0);
  1610. const epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  1611. const epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  1612. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  1613. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  1614. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  1615. // Validation
  1616. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  1617. if (targetIface && targetIface.public_key === pub) {
  1618. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  1619. return;
  1620. }
  1621. try {
  1622. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  1623. method: 'POST',
  1624. headers: { 'Content-Type': 'application/json' },
  1625. body: JSON.stringify({
  1626. orig_interface: origIface,
  1627. orig_public_key: origPubKey,
  1628. interface: iface,
  1629. name,
  1630. public_key: pub,
  1631. allowed_ips: allowed,
  1632. endpoint_address: epHost,
  1633. endpoint_port: epPort,
  1634. persistent_keepalive: keepalive,
  1635. preshared_key: psk,
  1636. disabled
  1637. })
  1638. });
  1639. const data = await res.json();
  1640. if (res.ok) {
  1641. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  1642. closeAddWGPeerModal();
  1643. loadWireGuard(false);
  1644. } else {
  1645. showToast('Error', data.error || 'Failed to save peer', 'error');
  1646. }
  1647. } catch (err) {
  1648. showToast('Error', err.message, 'error');
  1649. }
  1650. }
  1651. async function toggleWGPeerState(iface, pubkey, enable) {
  1652. try {
  1653. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  1654. method: 'POST',
  1655. headers: { 'Content-Type': 'application/json' },
  1656. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  1657. });
  1658. const data = await res.json();
  1659. if (res.ok) {
  1660. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  1661. loadWireGuard(false);
  1662. } else {
  1663. showToast('Error', data.error || 'Failed to update peer state', 'error');
  1664. }
  1665. } catch (err) {
  1666. showToast('Error', err.message, 'error');
  1667. }
  1668. }
  1669. async function deleteWGPeer(iface, pubkey) {
  1670. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  1671. try {
  1672. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  1673. method: 'POST',
  1674. headers: { 'Content-Type': 'application/json' },
  1675. body: JSON.stringify({ interface: iface, public_key: pubkey })
  1676. });
  1677. const data = await res.json();
  1678. if (res.ok) {
  1679. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  1680. loadWireGuard(false);
  1681. } else {
  1682. showToast('Error', data.error || 'Failed to remove peer', 'error');
  1683. }
  1684. } catch (err) {
  1685. showToast('Error', err.message, 'error');
  1686. }
  1687. }
  1688. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  1689. function switchIpsecModalTab(tab) {
  1690. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  1691. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  1692. const p1Content = document.getElementById('ipsec-tab-content-p1');
  1693. const p2Content = document.getElementById('ipsec-tab-content-p2');
  1694. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  1695. if (tab === 'p1') {
  1696. if (p1Tab) {
  1697. 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';
  1698. }
  1699. if (p2Tab) {
  1700. 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';
  1701. }
  1702. if (p1Content) p1Content.classList.remove('hidden');
  1703. if (p2Content) p2Content.classList.add('hidden');
  1704. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  1705. } else {
  1706. if (p1Tab) {
  1707. 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';
  1708. }
  1709. if (p2Tab) {
  1710. 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';
  1711. }
  1712. if (p1Content) p1Content.classList.add('hidden');
  1713. if (p2Content) p2Content.classList.remove('hidden');
  1714. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  1715. }
  1716. }
  1717. function toggleIpsecPhaseStep() {
  1718. const p1Content = document.getElementById('ipsec-tab-content-p1');
  1719. if (p1Content && !p1Content.classList.contains('hidden')) {
  1720. switchIpsecModalTab('p2');
  1721. } else {
  1722. switchIpsecModalTab('p1');
  1723. }
  1724. }
  1725. function toggleIpsecPskVisibility() {
  1726. const pskInput = document.getElementById('ipsec-modal-psk');
  1727. if (!pskInput) return;
  1728. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  1729. }
  1730. function addIpsecLocalSubnet(val = '') {
  1731. const container = document.getElementById('ipsec-modal-local-subnets-container');
  1732. if (!container) return;
  1733. const row = document.createElement('div');
  1734. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  1735. row.innerHTML = `
  1736. <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">
  1737. <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>
  1738. `;
  1739. container.appendChild(row);
  1740. }
  1741. function addIpsecRemoteSubnet(val = '') {
  1742. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  1743. if (!container) return;
  1744. const row = document.createElement('div');
  1745. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  1746. row.innerHTML = `
  1747. <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">
  1748. <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>
  1749. `;
  1750. container.appendChild(row);
  1751. }
  1752. function updateIpsecEspProposalFromPFS(val) {
  1753. const prop = document.getElementById('ipsec-modal-espprop');
  1754. if (!prop) return;
  1755. if (val === 'none') {
  1756. prop.value = 'aes256-sha256,aes128-sha256,default';
  1757. } else {
  1758. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  1759. }
  1760. }
  1761. function updateIpsecIkeProposalFromDH(dh) {
  1762. const el = document.getElementById('ipsec-modal-ikeprop');
  1763. if (el) {
  1764. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  1765. }
  1766. }
  1767. function safeSetVal(id, val) {
  1768. const el = document.getElementById(id);
  1769. if (el) el.value = val;
  1770. }
  1771. function safeSetChecked(id, val) {
  1772. const el = document.getElementById(id);
  1773. if (el) el.checked = !!val;
  1774. }
  1775. function safeGetVal(id, def = '') {
  1776. const el = document.getElementById(id);
  1777. return el ? el.value : def;
  1778. }
  1779. async function loadIPSec(populateInputs = true) {
  1780. try {
  1781. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1782. const list = await res.json();
  1783. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1784. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1785. const badge = document.getElementById('ipsec-sas-badge');
  1786. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1787. const tbody = document.getElementById('ipsec-table-body');
  1788. const empty = document.getElementById('ipsec-empty');
  1789. if (!tbody) return;
  1790. tbody.innerHTML = '';
  1791. if (state.ipsecTunnels.length === 0) {
  1792. if (empty) empty.classList.remove('hidden');
  1793. } else {
  1794. if (empty) empty.classList.add('hidden');
  1795. state.ipsecTunnels.forEach(c => {
  1796. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1797. const tr = document.createElement('tr');
  1798. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  1799. // Local subnets tags
  1800. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  1801. 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('');
  1802. // Remote subnets tags
  1803. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  1804. 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('');
  1805. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  1806. const p2Name = c.phase2_name || `${c.name}_p2`;
  1807. tr.innerHTML = `
  1808. <td class="py-2.5 px-3 text-center">
  1809. ${isEstablished ? `
  1810. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  1811. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  1812. <span>UP</span>
  1813. </span>
  1814. ` : (c.disabled ? `
  1815. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  1816. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  1817. <span>DOWN</span>
  1818. </span>
  1819. ` : `
  1820. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  1821. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  1822. <span>IDLE</span>
  1823. </span>
  1824. `)}
  1825. </td>
  1826. <td class="py-2.5 px-4 font-bold text-white">
  1827. <div class="flex items-center gap-2">
  1828. <span class="text-amber-400">🛡</span>
  1829. <div>
  1830. <div>${escapeHtml(c.name)}</div>
  1831. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  1832. </div>
  1833. </div>
  1834. </td>
  1835. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  1836. <td class="py-2.5 px-4 font-sans">
  1837. <div class="flex items-center gap-1.5">
  1838. <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>
  1839. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  1840. </div>
  1841. </td>
  1842. <td class="py-2.5 px-4">
  1843. <div class="space-y-1">
  1844. <div class="flex items-center flex-wrap gap-1">
  1845. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  1846. ${localBadges}
  1847. </div>
  1848. <div class="flex items-center flex-wrap gap-1">
  1849. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  1850. ${remoteBadges}
  1851. </div>
  1852. </div>
  1853. </td>
  1854. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  1855. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  1856. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  1857. </div>
  1858. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  1859. </td>
  1860. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  1861. ${isEstablished ? `
  1862. <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>
  1863. ` : `
  1864. <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>
  1865. `}
  1866. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1867. ${c.disabled ? 'Enable' : 'Disable'}
  1868. </button>
  1869. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  1870. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1871. </td>
  1872. `;
  1873. tbody.appendChild(tr);
  1874. });
  1875. }
  1876. } catch (err) {
  1877. console.error('Failed to load IPSec:', err);
  1878. }
  1879. }
  1880. function openAddIPSecModal() {
  1881. const modal = document.getElementById('ipsec-modal');
  1882. if (!modal) return;
  1883. const title = document.getElementById('ipsec-modal-title');
  1884. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  1885. // Phase 1 Fields
  1886. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  1887. const nameEl = document.getElementById('ipsec-modal-name');
  1888. if (nameEl) nameEl.readOnly = false;
  1889. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  1890. safeSetVal('ipsec-modal-ikever', 'ikev2');
  1891. safeSetVal('ipsec-modal-remotegw', '');
  1892. safeSetVal('ipsec-modal-localaddrs', '');
  1893. safeSetVal('ipsec-modal-comments', '');
  1894. safeSetVal('ipsec-modal-psk', '');
  1895. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  1896. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  1897. safeSetVal('ipsec-modal-ikekeylife', '86400');
  1898. safeSetVal('ipsec-modal-localid', '');
  1899. safeSetVal('ipsec-modal-remoteid', '');
  1900. safeSetVal('ipsec-modal-dpd', 'on-demand');
  1901. // Phase 2 Fields
  1902. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  1903. safeSetVal('ipsec-modal-espkeylife', '28800');
  1904. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  1905. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  1906. safeSetChecked('ipsec-modal-autostart', true);
  1907. safeSetChecked('ipsec-modal-disabled', false);
  1908. // Clear & Populate default dynamic subnets
  1909. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  1910. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  1911. if (localContainer) {
  1912. localContainer.innerHTML = '';
  1913. addIpsecLocalSubnet('192.168.10.0/24');
  1914. }
  1915. if (remoteContainer) {
  1916. remoteContainer.innerHTML = '';
  1917. addIpsecRemoteSubnet('192.168.20.0/24');
  1918. }
  1919. switchIpsecModalTab('p1');
  1920. modal.classList.remove('hidden');
  1921. }
  1922. function openEditIPSecModal(name) {
  1923. const modal = document.getElementById('ipsec-modal');
  1924. if (!modal) return;
  1925. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  1926. if (!conn) return;
  1927. const title = document.getElementById('ipsec-modal-title');
  1928. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  1929. // Phase 1 Fields
  1930. safeSetVal('ipsec-modal-name', conn.name);
  1931. const nameEl = document.getElementById('ipsec-modal-name');
  1932. if (nameEl) nameEl.readOnly = true;
  1933. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  1934. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  1935. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  1936. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  1937. safeSetVal('ipsec-modal-comments', conn.comment || '');
  1938. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  1939. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  1940. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  1941. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  1942. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  1943. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  1944. // Phase 2 Fields
  1945. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  1946. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  1947. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  1948. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  1949. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  1950. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  1951. // Populate dynamic subnets
  1952. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  1953. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  1954. if (localContainer) {
  1955. localContainer.innerHTML = '';
  1956. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  1957. locals.forEach(s => addIpsecLocalSubnet(s));
  1958. }
  1959. if (remoteContainer) {
  1960. remoteContainer.innerHTML = '';
  1961. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  1962. remotes.forEach(s => addIpsecRemoteSubnet(s));
  1963. }
  1964. switchIpsecModalTab('p1');
  1965. modal.classList.remove('hidden');
  1966. }
  1967. function closeAddIPSecModal() {
  1968. const modal = document.getElementById('ipsec-modal');
  1969. if (modal) modal.classList.add('hidden');
  1970. }
  1971. async function submitSaveIPSec(e) {
  1972. if (e) e.preventDefault();
  1973. const name = safeGetVal('ipsec-modal-name').trim();
  1974. if (!name) {
  1975. showToast('Error', 'Tunnel name is required', 'error');
  1976. return;
  1977. }
  1978. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  1979. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  1980. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  1981. const comments = safeGetVal('ipsec-modal-comments').trim();
  1982. const psk = safeGetVal('ipsec-modal-psk');
  1983. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  1984. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  1985. const localId = safeGetVal('ipsec-modal-localid').trim();
  1986. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  1987. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  1988. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  1989. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  1990. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  1991. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  1992. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  1993. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  1994. // Scrape dynamic local and remote subnets
  1995. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  1996. const localSubnets = [];
  1997. localInputs.forEach(inp => {
  1998. const v = inp.value.trim();
  1999. if (v) localSubnets.push(v);
  2000. });
  2001. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  2002. const remoteSubnets = [];
  2003. remoteInputs.forEach(inp => {
  2004. const v = inp.value.trim();
  2005. if (v) remoteSubnets.push(v);
  2006. });
  2007. try {
  2008. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  2009. method: 'POST',
  2010. headers: { 'Content-Type': 'application/json' },
  2011. body: JSON.stringify({
  2012. name,
  2013. comment: comments,
  2014. ike_version: ikeVersion,
  2015. local_addrs: localAddrs,
  2016. remote_addrs: remotegw,
  2017. preshared_key: psk,
  2018. ike_proposals: ikeProposals,
  2019. ike_keylife: ikeKeylife,
  2020. local_id: localId,
  2021. remote_id: remoteId,
  2022. dpd: dpd,
  2023. phase2_name: phase2Name,
  2024. esp_proposals: espProposals,
  2025. esp_keylife: espKeylife,
  2026. pfs_group: pfsGroup,
  2027. pfs: pfsGroup !== 'none',
  2028. local_subnets: localSubnets,
  2029. remote_subnets: remoteSubnets,
  2030. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2031. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2032. auto_start: autostart,
  2033. disabled
  2034. })
  2035. });
  2036. if (res.ok) {
  2037. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2038. closeAddIPSecModal();
  2039. loadIPSec(false);
  2040. } else {
  2041. const err = await res.json();
  2042. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2043. }
  2044. } catch (err) {
  2045. showToast('Error', err.message, 'error');
  2046. }
  2047. }
  2048. async function startIPSecTunnel(name) {
  2049. try {
  2050. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2051. if (res.ok) {
  2052. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2053. setTimeout(() => loadIPSec(false), 2000);
  2054. }
  2055. } catch (err) {
  2056. showToast('Error', err.message, 'error');
  2057. }
  2058. }
  2059. async function stopIPSecTunnel(name) {
  2060. try {
  2061. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2062. if (res.ok) {
  2063. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2064. loadIPSec(false);
  2065. }
  2066. } catch (err) {
  2067. showToast('Error', err.message, 'error');
  2068. }
  2069. }
  2070. async function toggleIPSecState(name, enable) {
  2071. try {
  2072. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2073. method: 'POST',
  2074. headers: { 'Content-Type': 'application/json' },
  2075. body: JSON.stringify({ enabled: enable })
  2076. });
  2077. if (res.ok) {
  2078. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2079. loadIPSec(false);
  2080. }
  2081. } catch (err) {
  2082. showToast('Error', err.message, 'error');
  2083. }
  2084. }
  2085. async function deleteIPSecConn(name) {
  2086. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2087. try {
  2088. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2089. if (res.ok) {
  2090. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2091. loadIPSec(false);
  2092. fetchData(false);
  2093. }
  2094. } catch (err) {
  2095. showToast('Error', err.message, 'error');
  2096. }
  2097. }
  2098. // ======================== L2TP Multi-Instance ========================
  2099. async function loadL2TP(populateInputs = true) {
  2100. try {
  2101. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2102. await fetchPPPProfilesList();
  2103. }
  2104. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2105. const list = await res.json();
  2106. state.l2tpList = Array.isArray(list) ? list : [];
  2107. const badge = document.getElementById('l2tp-count-badge');
  2108. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2109. const tbody = document.getElementById('l2tp-table-body');
  2110. const empty = document.getElementById('l2tp-empty');
  2111. if (!tbody) return;
  2112. tbody.innerHTML = '';
  2113. if (state.l2tpList.length === 0) {
  2114. if (empty) empty.classList.remove('hidden');
  2115. } else {
  2116. if (empty) empty.classList.add('hidden');
  2117. state.l2tpList.forEach(inst => {
  2118. const tr = document.createElement('tr');
  2119. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2120. tr.innerHTML = `
  2121. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2122. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2123. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2124. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2125. <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>
  2126. <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>
  2127. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2128. <td class="py-2.5 px-3 text-center">
  2129. <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'}">
  2130. ${inst.default_route ? 'Yes' : 'No'}
  2131. </span>
  2132. </td>
  2133. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2134. ${inst.running ? `
  2135. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2136. ` : `
  2137. <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>
  2138. `}
  2139. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2140. ${inst.disabled ? 'Enable' : 'Disable'}
  2141. </button>
  2142. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2143. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2144. </td>
  2145. `;
  2146. tbody.appendChild(tr);
  2147. });
  2148. }
  2149. } catch (err) {
  2150. console.error('Failed to load L2TP:', err);
  2151. }
  2152. }
  2153. async function openAddL2TPModal() {
  2154. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2155. await fetchPPPProfilesList();
  2156. }
  2157. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2158. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2159. document.getElementById('l2tp-modal-name').readOnly = false;
  2160. document.getElementById('l2tp-modal-server').value = '';
  2161. document.getElementById('l2tp-modal-user').value = '';
  2162. document.getElementById('l2tp-modal-pass').value = '';
  2163. document.getElementById('l2tp-modal-ipsec').value = '';
  2164. document.getElementById('l2tp-modal-defroute').checked = true;
  2165. document.getElementById('l2tp-modal-disabled').checked = false;
  2166. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2167. document.getElementById('l2tp-modal').classList.remove('hidden');
  2168. }
  2169. async function openEditL2TPModal(name) {
  2170. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2171. await fetchPPPProfilesList();
  2172. }
  2173. const inst = (state.l2tpList || []).find(i => i.name === name);
  2174. if (!inst) return;
  2175. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2176. document.getElementById('l2tp-modal-name').value = inst.name;
  2177. document.getElementById('l2tp-modal-name').readOnly = true;
  2178. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2179. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2180. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2181. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2182. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2183. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2184. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2185. document.getElementById('l2tp-modal').classList.remove('hidden');
  2186. }
  2187. function closeL2TPModal() {
  2188. document.getElementById('l2tp-modal').classList.add('hidden');
  2189. }
  2190. async function submitSaveL2TP(e) {
  2191. e.preventDefault();
  2192. const name = document.getElementById('l2tp-modal-name').value.trim();
  2193. const server = document.getElementById('l2tp-modal-server').value.trim();
  2194. const user = document.getElementById('l2tp-modal-user').value.trim();
  2195. const pass = document.getElementById('l2tp-modal-pass').value;
  2196. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2197. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2198. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2199. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2200. try {
  2201. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2202. method: 'POST',
  2203. headers: { 'Content-Type': 'application/json' },
  2204. body: JSON.stringify({
  2205. name,
  2206. connect_to: server,
  2207. username: user,
  2208. password: pass,
  2209. profile: profile,
  2210. ipsec_secret: ipsec,
  2211. default_route: defRoute,
  2212. disabled
  2213. })
  2214. });
  2215. if (res.ok) {
  2216. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2217. closeL2TPModal();
  2218. loadL2TP(false);
  2219. fetchData(false);
  2220. }
  2221. } catch (err) {
  2222. showToast('Error', err.message, 'error');
  2223. }
  2224. }
  2225. async function connectL2TPInstance(name) {
  2226. try {
  2227. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2228. if (res.ok) {
  2229. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2230. setTimeout(() => loadL2TP(false), 2000);
  2231. }
  2232. } catch (err) {
  2233. showToast('Error', err.message, 'error');
  2234. }
  2235. }
  2236. async function disconnectL2TPInstance(name) {
  2237. try {
  2238. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2239. if (res.ok) {
  2240. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2241. loadL2TP(false);
  2242. }
  2243. } catch (err) {
  2244. showToast('Error', err.message, 'error');
  2245. }
  2246. }
  2247. async function toggleL2TPState(name, enable) {
  2248. try {
  2249. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2250. method: 'POST',
  2251. headers: { 'Content-Type': 'application/json' },
  2252. body: JSON.stringify({ enabled: enable })
  2253. });
  2254. if (res.ok) {
  2255. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2256. loadL2TP(false);
  2257. }
  2258. } catch (err) {
  2259. showToast('Error', err.message, 'error');
  2260. }
  2261. }
  2262. async function deleteL2TPInstance(name) {
  2263. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2264. try {
  2265. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2266. if (res.ok) {
  2267. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2268. loadL2TP(false);
  2269. fetchData(false);
  2270. }
  2271. } catch (err) {
  2272. showToast('Error', err.message, 'error');
  2273. }
  2274. }
  2275. // ======================== PPTP Multi-Instance ========================
  2276. async function loadPPTP(populateInputs = true) {
  2277. try {
  2278. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2279. await fetchPPPProfilesList();
  2280. }
  2281. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2282. const list = await res.json();
  2283. state.pptpList = Array.isArray(list) ? list : [];
  2284. const badge = document.getElementById('pptp-count-badge');
  2285. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2286. const tbody = document.getElementById('pptp-table-body');
  2287. const empty = document.getElementById('pptp-empty');
  2288. if (!tbody) return;
  2289. tbody.innerHTML = '';
  2290. if (state.pptpList.length === 0) {
  2291. if (empty) empty.classList.remove('hidden');
  2292. } else {
  2293. if (empty) empty.classList.add('hidden');
  2294. state.pptpList.forEach(inst => {
  2295. const tr = document.createElement('tr');
  2296. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2297. tr.innerHTML = `
  2298. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2299. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2300. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2301. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2302. <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>
  2303. <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>
  2304. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2305. <td class="py-2.5 px-3 text-center">
  2306. <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'}">
  2307. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2308. </span>
  2309. </td>
  2310. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2311. ${inst.running ? `
  2312. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2313. ` : `
  2314. <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>
  2315. `}
  2316. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2317. ${inst.disabled ? 'Enable' : 'Disable'}
  2318. </button>
  2319. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2320. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2321. </td>
  2322. `;
  2323. tbody.appendChild(tr);
  2324. });
  2325. }
  2326. } catch (err) {
  2327. console.error('Failed to load PPTP:', err);
  2328. }
  2329. }
  2330. async function openAddPPTPModal() {
  2331. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2332. await fetchPPPProfilesList();
  2333. }
  2334. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2335. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2336. document.getElementById('pptp-modal-name').readOnly = false;
  2337. document.getElementById('pptp-modal-server').value = '';
  2338. document.getElementById('pptp-modal-user').value = '';
  2339. document.getElementById('pptp-modal-pass').value = '';
  2340. document.getElementById('pptp-modal-mppe').checked = true;
  2341. document.getElementById('pptp-modal-defroute').checked = true;
  2342. document.getElementById('pptp-modal-disabled').checked = false;
  2343. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2344. document.getElementById('pptp-modal').classList.remove('hidden');
  2345. }
  2346. async function openEditPPTPModal(name) {
  2347. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2348. await fetchPPPProfilesList();
  2349. }
  2350. const inst = (state.pptpList || []).find(i => i.name === name);
  2351. if (!inst) return;
  2352. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2353. document.getElementById('pptp-modal-name').value = inst.name;
  2354. document.getElementById('pptp-modal-name').readOnly = true;
  2355. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2356. document.getElementById('pptp-modal-user').value = inst.username || '';
  2357. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2358. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2359. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2360. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2361. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2362. document.getElementById('pptp-modal').classList.remove('hidden');
  2363. }
  2364. function closePPTPModal() {
  2365. document.getElementById('pptp-modal').classList.add('hidden');
  2366. }
  2367. async function submitSavePPTP(e) {
  2368. e.preventDefault();
  2369. const name = document.getElementById('pptp-modal-name').value.trim();
  2370. const server = document.getElementById('pptp-modal-server').value.trim();
  2371. const user = document.getElementById('pptp-modal-user').value.trim();
  2372. const pass = document.getElementById('pptp-modal-pass').value;
  2373. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  2374. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2375. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2376. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2377. try {
  2378. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2379. method: 'POST',
  2380. headers: { 'Content-Type': 'application/json' },
  2381. body: JSON.stringify({
  2382. name,
  2383. connect_to: server,
  2384. username: user,
  2385. password: pass,
  2386. profile: profile,
  2387. require_mppe: mppe,
  2388. default_route: defRoute,
  2389. auto_reconnect: true,
  2390. disabled
  2391. })
  2392. });
  2393. if (res.ok) {
  2394. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2395. closePPTPModal();
  2396. loadPPTP(false);
  2397. fetchData(false);
  2398. }
  2399. } catch (err) {
  2400. showToast('Error', err.message, 'error');
  2401. }
  2402. }
  2403. async function connectPPTPInstance(name) {
  2404. try {
  2405. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2406. if (res.ok) {
  2407. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2408. setTimeout(() => loadPPTP(false), 2000);
  2409. }
  2410. } catch (err) {
  2411. showToast('Error', err.message, 'error');
  2412. }
  2413. }
  2414. async function disconnectPPTPInstance(name) {
  2415. try {
  2416. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2417. if (res.ok) {
  2418. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2419. loadPPTP(false);
  2420. }
  2421. } catch (err) {
  2422. showToast('Error', err.message, 'error');
  2423. }
  2424. }
  2425. async function togglePPTPState(name, enable) {
  2426. try {
  2427. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2428. method: 'POST',
  2429. headers: { 'Content-Type': 'application/json' },
  2430. body: JSON.stringify({ enabled: enable })
  2431. });
  2432. if (res.ok) {
  2433. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2434. loadPPTP(false);
  2435. }
  2436. } catch (err) {
  2437. showToast('Error', err.message, 'error');
  2438. }
  2439. }
  2440. async function deletePPTPInstance(name) {
  2441. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2442. try {
  2443. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2444. if (res.ok) {
  2445. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2446. loadPPTP(false);
  2447. fetchData(false);
  2448. }
  2449. } catch (err) {
  2450. showToast('Error', err.message, 'error');
  2451. }
  2452. }
  2453. // ---------------- Modal & Helper Functions ----------------
  2454. function openVlanModal(defaultParent = '') {
  2455. const select = document.getElementById('vlan-parent');
  2456. select.innerHTML = '';
  2457. const allIfaces = state.interfaces || [];
  2458. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2459. if (eligible.length === 0) {
  2460. const opt = document.createElement('option');
  2461. opt.value = '';
  2462. opt.innerText = 'No VLAN-capable interfaces available';
  2463. select.appendChild(opt);
  2464. } else {
  2465. eligible.forEach(i => {
  2466. const opt = document.createElement('option');
  2467. opt.value = i.name;
  2468. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2469. if (i.name === defaultParent) opt.selected = true;
  2470. select.appendChild(opt);
  2471. });
  2472. }
  2473. document.getElementById('vlan-id').value = '';
  2474. document.getElementById('vlan-name').value = '';
  2475. document.getElementById('vlan-ip').value = '';
  2476. document.getElementById('vlan-desc').value = '';
  2477. autoSuggestVlanName();
  2478. document.getElementById('vlan-modal').classList.remove('hidden');
  2479. }
  2480. function closeVlanModal() {
  2481. document.getElementById('vlan-modal').classList.add('hidden');
  2482. }
  2483. function autoSuggestVlanName() {
  2484. const parent = document.getElementById('vlan-parent').value;
  2485. if (!parent) return;
  2486. const id = document.getElementById('vlan-id').value;
  2487. const nameInput = document.getElementById('vlan-name');
  2488. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  2489. }
  2490. function setSubnetPreset(cidr) {
  2491. const ipInput = document.getElementById('vlan-ip');
  2492. const id = document.getElementById('vlan-id').value || '10';
  2493. ipInput.value = `192.168.${id}.1${cidr}`;
  2494. }
  2495. async function submitCreateVlan(e) {
  2496. e.preventDefault();
  2497. const btn = document.getElementById('vlan-submit-btn');
  2498. btn.disabled = true;
  2499. btn.innerText = 'Creating...';
  2500. const parent = document.getElementById('vlan-parent').value;
  2501. if (!parent) {
  2502. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  2503. btn.disabled = false;
  2504. btn.innerText = 'Create VLAN';
  2505. return;
  2506. }
  2507. const id = parseInt(document.getElementById('vlan-id').value, 10);
  2508. const name = document.getElementById('vlan-name').value.trim();
  2509. const ip = document.getElementById('vlan-ip').value.trim();
  2510. const role = document.getElementById('vlan-role').value;
  2511. const desc = document.getElementById('vlan-desc').value.trim();
  2512. try {
  2513. const res = await fetch(`${API_BASE}/vlans`, {
  2514. method: 'POST',
  2515. headers: { 'Content-Type': 'application/json' },
  2516. body: JSON.stringify({
  2517. parent_name: parent,
  2518. vlan_id: id,
  2519. name: name,
  2520. ip_address: ip,
  2521. role: role,
  2522. description: desc,
  2523. mtu: 1500,
  2524. auto_up: true
  2525. })
  2526. });
  2527. const data = await res.json();
  2528. if (res.ok) {
  2529. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  2530. state.expandedParents.add(parent);
  2531. closeVlanModal();
  2532. await fetchData(true);
  2533. if (state.activeTab !== 'interfaces') navigate('interfaces');
  2534. } else {
  2535. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  2536. }
  2537. } catch (err) {
  2538. showToast('Error', err.message, 'error');
  2539. } finally {
  2540. btn.disabled = false;
  2541. btn.innerText = 'Create VLAN';
  2542. }
  2543. }
  2544. async function confirmDeleteVlan(name) {
  2545. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  2546. try {
  2547. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2548. if (res.ok) {
  2549. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  2550. closeIfaceModal();
  2551. fetchData(true);
  2552. }
  2553. } catch (err) {
  2554. showToast('Error', err.message, 'error');
  2555. }
  2556. }
  2557. function openIfaceModal(name) {
  2558. const iface = (state.interfaces || []).find(i => i.name === name);
  2559. if (!iface) return;
  2560. state.currentModalIface = iface.name;
  2561. document.getElementById('modal-iface-name').innerText = iface.name;
  2562. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  2563. document.getElementById('modal-iface-mtu').value = iface.mtu;
  2564. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  2565. document.getElementById('modal-iface-desc').value = iface.description || '';
  2566. const delBtn = document.getElementById('modal-delete-vlan-btn');
  2567. if (iface.is_vlan) {
  2568. delBtn.classList.remove('hidden');
  2569. } else {
  2570. delBtn.classList.add('hidden');
  2571. }
  2572. renderModalIPs(iface);
  2573. document.getElementById('iface-modal').classList.remove('hidden');
  2574. }
  2575. function renderModalIPs(iface) {
  2576. const container = document.getElementById('modal-ip-list');
  2577. container.innerHTML = '';
  2578. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  2579. if (addrs.length === 0) {
  2580. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  2581. return;
  2582. }
  2583. addrs.forEach(addr => {
  2584. const row = document.createElement('div');
  2585. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  2586. row.innerHTML = `
  2587. <span class="text-white">${addr}</span>
  2588. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  2589. `;
  2590. container.appendChild(row);
  2591. });
  2592. }
  2593. function closeIfaceModal() {
  2594. document.getElementById('iface-modal').classList.add('hidden');
  2595. state.currentModalIface = null;
  2596. }
  2597. async function setIfaceState(name, newState) {
  2598. await toggleInterfaceState(name, newState);
  2599. const updated = (state.interfaces || []).find(i => i.name === name);
  2600. if (updated) openIfaceModal(name);
  2601. }
  2602. async function applyMTU() {
  2603. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  2604. try {
  2605. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  2606. method: 'POST',
  2607. headers: { 'Content-Type': 'application/json' },
  2608. body: JSON.stringify({ mtu })
  2609. });
  2610. if (res.ok) {
  2611. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  2612. fetchData(false);
  2613. }
  2614. } catch (err) {
  2615. showToast('Error', err.message, 'error');
  2616. }
  2617. }
  2618. async function addInterfaceIP() {
  2619. const ip = document.getElementById('modal-new-ip').value.trim();
  2620. if (!ip) return;
  2621. try {
  2622. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2623. method: 'POST',
  2624. headers: { 'Content-Type': 'application/json' },
  2625. body: JSON.stringify({ ip })
  2626. });
  2627. if (res.ok) {
  2628. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  2629. document.getElementById('modal-new-ip').value = '';
  2630. await fetchData(false);
  2631. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2632. if (iface) renderModalIPs(iface);
  2633. } else {
  2634. const err = await res.json();
  2635. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  2636. }
  2637. } catch (err) {
  2638. showToast('Error', err.message, 'error');
  2639. }
  2640. }
  2641. async function removeInterfaceIP(ip) {
  2642. if (!confirm(`Remove IP ${ip}?`)) return;
  2643. try {
  2644. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2645. method: 'DELETE',
  2646. headers: { 'Content-Type': 'application/json' },
  2647. body: JSON.stringify({ ip })
  2648. });
  2649. if (res.ok) {
  2650. showToast('IP Removed', `Removed ${ip}`, 'success');
  2651. await fetchData(false);
  2652. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2653. if (iface) renderModalIPs(iface);
  2654. }
  2655. } catch (err) {
  2656. showToast('Error', err.message, 'error');
  2657. }
  2658. }
  2659. async function saveInterfaceMetadata() {
  2660. const role = document.getElementById('modal-iface-role').value;
  2661. const desc = document.getElementById('modal-iface-desc').value.trim();
  2662. try {
  2663. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/metadata`, {
  2664. method: 'POST',
  2665. headers: { 'Content-Type': 'application/json' },
  2666. body: JSON.stringify({ role, description: desc })
  2667. });
  2668. if (res.ok) {
  2669. showToast('Saved', 'Metadata updated', 'success');
  2670. closeIfaceModal();
  2671. fetchData(false);
  2672. }
  2673. } catch (err) {
  2674. showToast('Error', err.message, 'error');
  2675. }
  2676. }
  2677. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  2678. state.fwSubTab = 'filter';
  2679. state.routesSubTab = 'routes';
  2680. function renderRuleFlag(disabled, hasComment) {
  2681. let flags = '';
  2682. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  2683. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  2684. return flags || '<span class="text-slate-600">-</span>';
  2685. }
  2686. function renderActionBadge(action) {
  2687. const act = (action || '').toLowerCase();
  2688. let color = 'bg-slate-800 text-slate-300';
  2689. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  2690. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  2691. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  2692. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  2693. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  2694. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  2695. }
  2696. function switchFWSubTab(tab) {
  2697. state.fwSubTab = tab;
  2698. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  2699. tabs.forEach(t => {
  2700. const panel = document.getElementById(`fw-subtab-${t}`);
  2701. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  2702. if (panel) {
  2703. if (t === tab) panel.classList.remove('hidden');
  2704. else panel.classList.add('hidden');
  2705. }
  2706. if (btn) {
  2707. if (t === tab) {
  2708. 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';
  2709. } else {
  2710. 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';
  2711. }
  2712. }
  2713. });
  2714. const addBtn = document.getElementById('fw-primary-add-btn');
  2715. if (addBtn) {
  2716. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  2717. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  2718. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  2719. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  2720. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  2721. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  2722. }
  2723. if (tab === 'geo') loadGeoIP();
  2724. if (tab === 'connections') loadConnections();
  2725. setTimeout(initTableSorting, 50);
  2726. }
  2727. function openCurrentFWModal() {
  2728. if (state.fwSubTab === 'filter') openAddFilterModal();
  2729. else if (state.fwSubTab === 'nat') openAddNATModal();
  2730. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  2731. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  2732. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  2733. else if (state.fwSubTab === 'connections') loadConnections();
  2734. }
  2735. async function loadFirewall(populateDropdowns = true) {
  2736. try {
  2737. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  2738. fetch(`${API_BASE}/firewall/summary`),
  2739. fetch(`${API_BASE}/firewall/filter`),
  2740. fetch(`${API_BASE}/firewall/nat`),
  2741. fetch(`${API_BASE}/firewall/mangle`),
  2742. fetch(`${API_BASE}/firewall/address-lists`),
  2743. fetch(`${API_BASE}/firewall/geoip/status`),
  2744. fetch(`${API_BASE}/firewall/geoip/countries`)
  2745. ]);
  2746. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  2747. if (filterRes.ok) state.filterRules = await filterRes.json();
  2748. if (natRes.ok) state.natRules = await natRes.json();
  2749. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  2750. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  2751. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  2752. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  2753. // Badges
  2754. const bFilter = document.getElementById('fw-badge-filter');
  2755. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  2756. const bNat = document.getElementById('fw-badge-nat');
  2757. if (bNat) bNat.innerText = (state.natRules || []).length;
  2758. const bMangle = document.getElementById('fw-badge-mangle');
  2759. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  2760. const bAddr = document.getElementById('fw-badge-addrlist');
  2761. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  2762. const bGeo = document.getElementById('fw-badge-geo');
  2763. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  2764. renderFilterRules();
  2765. renderNATRules();
  2766. renderMangleRules();
  2767. renderAddressLists();
  2768. renderGeoCountries();
  2769. if (state.fwSubTab === 'connections') {
  2770. loadConnections();
  2771. }
  2772. } catch (err) {
  2773. console.error('Failed to load firewall:', err);
  2774. }
  2775. }
  2776. // ----------------- Filter Rules -----------------
  2777. function renderFilterRules() {
  2778. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  2779. const tbody = document.getElementById('filter-table-body');
  2780. const empty = document.getElementById('filter-empty');
  2781. if (!tbody) return;
  2782. tbody.innerHTML = '';
  2783. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2784. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2785. if (rules.length === 0) {
  2786. empty?.classList.remove('hidden');
  2787. return;
  2788. }
  2789. empty?.classList.add('hidden');
  2790. rules.forEach((r, idx) => {
  2791. const tr = document.createElement('tr');
  2792. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2793. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2794. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2795. let actionExtra = '';
  2796. if (r.action === 'reject') {
  2797. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  2798. } else if (r.action === 'jump') {
  2799. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  2800. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  2801. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  2802. } else if (r.action === 'log' && r.log_prefix) {
  2803. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  2804. }
  2805. tr.innerHTML = `
  2806. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2807. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2808. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2809. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2810. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2811. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2812. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2813. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2814. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  2815. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2816. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2817. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2818. </td>
  2819. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2820. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2821. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2822. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2823. <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>
  2824. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2825. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2826. </td>
  2827. `;
  2828. tbody.appendChild(tr);
  2829. });
  2830. }
  2831. function formatTarget(addr, list, geo) {
  2832. const parts = [];
  2833. if (addr) parts.push(`<span>${addr}</span>`);
  2834. if (list) {
  2835. const inv = list.startsWith('!') ? '!' : '';
  2836. const clean = list.replace(/^!/, '');
  2837. 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>`);
  2838. }
  2839. if (geo) {
  2840. const inv = geo.startsWith('!') ? '!' : '';
  2841. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  2842. 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>`);
  2843. }
  2844. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  2845. return parts.join(' ');
  2846. }
  2847. function populateInterfaceSelect(selectId, currentVal = '') {
  2848. const sel = document.getElementById(selectId);
  2849. if (!sel) return;
  2850. sel.innerHTML = '<option value="">(Any Interface)</option>';
  2851. (state.interfaces || []).forEach(i => {
  2852. const opt = document.createElement('option');
  2853. opt.value = i.name;
  2854. opt.innerText = `${i.name} (${i.role || i.type})`;
  2855. if (i.name === currentVal) opt.selected = true;
  2856. sel.appendChild(opt);
  2857. });
  2858. }
  2859. function populateAddressListSelect(selectId, currentVal = '') {
  2860. const sel = document.getElementById(selectId);
  2861. if (!sel) return;
  2862. sel.innerHTML = '<option value="">(None)</option>';
  2863. const cleanVal = (currentVal || '').replace(/^!/, '');
  2864. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  2865. customNames.forEach(name => {
  2866. const count = (state.addressLists || []).filter(a => a.name === name).length;
  2867. const opt = document.createElement('option');
  2868. opt.value = name;
  2869. opt.innerText = `${name} (${count} entries)`;
  2870. if (name === cleanVal) opt.selected = true;
  2871. sel.appendChild(opt);
  2872. });
  2873. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  2874. const opt = document.createElement('option');
  2875. opt.value = cleanVal;
  2876. opt.innerText = cleanVal;
  2877. opt.selected = true;
  2878. sel.appendChild(opt);
  2879. }
  2880. populateCommonAddrListDatalist();
  2881. }
  2882. function populateCommonAddrListDatalist() {
  2883. const dl = document.getElementById('fw-addrlist-datalist');
  2884. if (!dl) return;
  2885. dl.innerHTML = '';
  2886. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  2887. names.forEach(name => {
  2888. const opt = document.createElement('option');
  2889. opt.value = name;
  2890. dl.appendChild(opt);
  2891. });
  2892. }
  2893. function populateGeoIPSelect(selectId, currentVal = '') {
  2894. const sel = document.getElementById(selectId);
  2895. if (!sel) return;
  2896. sel.innerHTML = '<option value="">(None)</option>';
  2897. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  2898. // Presets optgroup
  2899. const grpPresets = document.createElement('optgroup');
  2900. grpPresets.label = '⚡ Regional Presets';
  2901. const presets = [
  2902. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  2903. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  2904. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  2905. ];
  2906. presets.forEach(p => {
  2907. const opt = document.createElement('option');
  2908. opt.value = p.code;
  2909. opt.innerText = p.label;
  2910. if (p.code === cleanVal) opt.selected = true;
  2911. grpPresets.appendChild(opt);
  2912. });
  2913. sel.appendChild(grpPresets);
  2914. // All Countries optgroup
  2915. const grpCountries = document.createElement('optgroup');
  2916. grpCountries.label = '🌍 All Countries';
  2917. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  2918. countries.forEach(c => {
  2919. const opt = document.createElement('option');
  2920. opt.value = c.code;
  2921. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  2922. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  2923. if (c.code === cleanVal) opt.selected = true;
  2924. grpCountries.appendChild(opt);
  2925. });
  2926. sel.appendChild(grpCountries);
  2927. }
  2928. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  2929. function switchFwRuleTab(tab) {
  2930. state.activeFwRuleTab = tab;
  2931. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  2932. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  2933. btn.classList.add('text-slate-400', 'border-transparent');
  2934. });
  2935. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  2936. if (activeBtn) {
  2937. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  2938. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  2939. }
  2940. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  2941. const activePane = document.getElementById(`fw-pane-${tab}`);
  2942. if (activePane) activePane.classList.remove('hidden');
  2943. if (tab === 'statistics') {
  2944. startFwStatPolling();
  2945. } else {
  2946. stopFwStatPolling();
  2947. }
  2948. }
  2949. function toggleFwField(fieldKey, expand) {
  2950. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  2951. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  2952. if (!plusBtn || !fieldBox) return;
  2953. if (expand) {
  2954. plusBtn.classList.add('hidden');
  2955. fieldBox.classList.remove('hidden');
  2956. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2957. if (valInput) valInput.focus();
  2958. } else {
  2959. fieldBox.classList.add('hidden');
  2960. plusBtn.classList.remove('hidden');
  2961. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2962. if (valInput) {
  2963. if (valInput.tagName === 'SELECT') {
  2964. valInput.selectedIndex = 0;
  2965. } else {
  2966. valInput.value = '';
  2967. }
  2968. }
  2969. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  2970. if (invInput) invInput.checked = false;
  2971. if (fieldKey === 'cs') {
  2972. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  2973. const el = document.getElementById(id);
  2974. if (el) el.checked = false;
  2975. });
  2976. }
  2977. if (fieldKey === 'natstate') {
  2978. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  2979. const el = document.getElementById(id);
  2980. if (el) el.checked = false;
  2981. });
  2982. }
  2983. if (fieldKey === 'days') {
  2984. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  2985. const el = document.getElementById(`fw-day-${d}`);
  2986. if (el) el.checked = true;
  2987. });
  2988. }
  2989. }
  2990. }
  2991. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  2992. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  2993. toggleFwField(fieldKey, true);
  2994. let strVal = String(value);
  2995. if (hasInvert) {
  2996. const inv = strVal.startsWith('!');
  2997. if (inv) strVal = strVal.slice(1);
  2998. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  2999. if (invEl) invEl.checked = inv;
  3000. }
  3001. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3002. if (valEl) valEl.value = strVal;
  3003. } else {
  3004. toggleFwField(fieldKey, false);
  3005. }
  3006. }
  3007. function getFwFieldVal(fieldKey, hasInvert = false) {
  3008. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3009. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3010. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3011. let v = valEl ? valEl.value.trim() : '';
  3012. if (!v) return '';
  3013. if (hasInvert) {
  3014. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3015. if (invEl && invEl.checked) {
  3016. v = '!' + v.replace(/^!/, '');
  3017. }
  3018. }
  3019. return v;
  3020. }
  3021. function toggleMaximizeFilterModal() {
  3022. const win = document.getElementById('filter-modal-window');
  3023. if (!win) return;
  3024. if (win.classList.contains('max-w-[720px]')) {
  3025. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3026. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3027. } else {
  3028. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3029. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3030. }
  3031. }
  3032. function openAddFilterModal() {
  3033. switchFwRuleTab('general');
  3034. const badge = document.getElementById('fw-modal-badge');
  3035. if (badge) badge.innerText = 'New...';
  3036. document.getElementById('filter-modal-id').value = '';
  3037. document.getElementById('filter-modal-enabled').checked = true;
  3038. document.getElementById('filter-modal-comment').value = '';
  3039. document.getElementById('filter-modal-chain').value = 'forward';
  3040. document.getElementById('filter-modal-action').value = 'accept';
  3041. document.getElementById('filter-modal-log').checked = false;
  3042. populateInterfaceSelect('fw-val-iniface');
  3043. populateInterfaceSelect('fw-val-outiface');
  3044. populateAddressListSelect('fw-val-srclist');
  3045. populateAddressListSelect('fw-val-dstlist');
  3046. populateGeoIPSelect('fw-val-srcgeo');
  3047. populateGeoIPSelect('fw-val-dstgeo');
  3048. const allFieldKeys = [
  3049. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3050. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3051. 'routingmark', 'conntype', 'cs', 'natstate',
  3052. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3053. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3054. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3055. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3056. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3057. ];
  3058. allFieldKeys.forEach(k => toggleFwField(k, false));
  3059. resetCurrentRuleCounters();
  3060. toggleFilterActionFields();
  3061. document.getElementById('filter-modal').classList.remove('hidden');
  3062. }
  3063. function openEditFilterModal(id) {
  3064. const r = (state.filterRules || []).find(rule => rule.id === id);
  3065. if (!r) return;
  3066. switchFwRuleTab('general');
  3067. const badge = document.getElementById('fw-modal-badge');
  3068. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3069. document.getElementById('filter-modal-id').value = r.id;
  3070. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  3071. document.getElementById('filter-modal-comment').value = r.comment || '';
  3072. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  3073. document.getElementById('filter-modal-action').value = r.action || 'accept';
  3074. document.getElementById('filter-modal-log').checked = !!r.log;
  3075. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3076. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3077. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3078. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3079. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  3080. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  3081. setFwFieldVal('src', r.src_address, true);
  3082. setFwFieldVal('dst', r.dst_address, true);
  3083. setFwFieldVal('srclist', r.src_address_list, true);
  3084. setFwFieldVal('dstlist', r.dst_address_list, true);
  3085. setFwFieldVal('srcgeo', r.src_geoip, true);
  3086. setFwFieldVal('dstgeo', r.dst_geoip, true);
  3087. if (r.protocol && r.protocol !== 'all') {
  3088. setFwFieldVal('proto', r.protocol, true);
  3089. } else {
  3090. toggleFwField('proto', false);
  3091. }
  3092. setFwFieldVal('sport', r.src_port, true);
  3093. setFwFieldVal('dport', r.dst_port, true);
  3094. setFwFieldVal('anyport', r.any_port, true);
  3095. setFwFieldVal('iniface', r.in_interface, true);
  3096. setFwFieldVal('outiface', r.out_interface, true);
  3097. setFwFieldVal('inifacelist', r.in_interface_list, true);
  3098. setFwFieldVal('outifacelist', r.out_interface_list, true);
  3099. setFwFieldVal('pktmark', r.packet_mark, true);
  3100. setFwFieldVal('connmark', r.connection_mark, true);
  3101. setFwFieldVal('routingmark', r.routing_mark, true);
  3102. setFwFieldVal('conntype', r.connection_type, false);
  3103. const states = r.connection_state || [];
  3104. if (states.length > 0) {
  3105. toggleFwField('cs', true);
  3106. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  3107. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  3108. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  3109. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  3110. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  3111. } else {
  3112. toggleFwField('cs', false);
  3113. }
  3114. const natStates = r.connection_nat_state || [];
  3115. if (natStates.length > 0) {
  3116. toggleFwField('natstate', true);
  3117. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  3118. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  3119. } else {
  3120. toggleFwField('natstate', false);
  3121. }
  3122. // Advanced tab fields
  3123. setFwFieldVal('layer7', r.layer7_protocol, false);
  3124. setFwFieldVal('content', r.content, false);
  3125. setFwFieldVal('connbytes', r.connection_bytes, false);
  3126. setFwFieldVal('connrate', r.connection_rate, false);
  3127. setFwFieldVal('pcc', r.pcc, false);
  3128. setFwFieldVal('srcmac', r.src_mac_address, true);
  3129. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  3130. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  3131. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3132. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3133. setFwFieldVal('ipsec', r.ipsec_policy, false);
  3134. setFwFieldVal('tlshost', r.tls_host, false);
  3135. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  3136. setFwFieldVal('priority', r.priority, false);
  3137. setFwFieldVal('dscp', r.dscp, false);
  3138. setFwFieldVal('tcpmss', r.tcp_mss, false);
  3139. if (r.tos) {
  3140. const tosEl = document.getElementById('fw-val-tos');
  3141. if (tosEl) tosEl.value = r.tos;
  3142. }
  3143. setFwFieldVal('pktsize', r.packet_size, false);
  3144. setFwFieldVal('random', r.random, false);
  3145. setFwFieldVal('tcpflags', r.tcp_flags, false);
  3146. setFwFieldVal('icmpoptions', r.icmp_options, false);
  3147. setFwFieldVal('ipv4options', r.ipv4_options, false);
  3148. setFwFieldVal('ttl', r.ttl, false);
  3149. // Extra tab fields
  3150. setFwFieldVal('time', r.time, false);
  3151. if (r.days) {
  3152. toggleFwField('days', true);
  3153. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3154. const chk = document.getElementById(`fw-day-${d}`);
  3155. if (chk) chk.checked = r.days.includes(d);
  3156. });
  3157. } else {
  3158. toggleFwField('days', false);
  3159. }
  3160. setFwFieldVal('limit', r.limit, false);
  3161. setFwFieldVal('dstlimit', r.dst_limit, false);
  3162. setFwFieldVal('psd', r.psd, false);
  3163. // Action fields
  3164. if (r.reject_with) {
  3165. const rwEl = document.getElementById('filter-modal-rejectwith');
  3166. if (rwEl) rwEl.value = r.reject_with;
  3167. }
  3168. if (r.jump_target) {
  3169. const jtEl = document.getElementById('filter-modal-jumptarget');
  3170. if (jtEl) jtEl.value = r.jump_target;
  3171. }
  3172. if (r.address_list) {
  3173. const alEl = document.getElementById('filter-modal-action-addrlist');
  3174. if (alEl) alEl.value = r.address_list;
  3175. }
  3176. if (r.address_list_timeout) {
  3177. const toEl = document.getElementById('filter-modal-action-timeout');
  3178. if (toEl) toEl.value = r.address_list_timeout;
  3179. }
  3180. setFwFieldVal('logprefix', r.log_prefix, false);
  3181. // Statistics
  3182. const bEl = document.getElementById('fw-stat-bytes');
  3183. const pEl = document.getElementById('fw-stat-packets');
  3184. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3185. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3186. state.fwLastBytes = r.bytes || 0;
  3187. state.fwLastPackets = r.packets || 0;
  3188. state.fwLastTimestamp = Date.now();
  3189. state.fwStatRateHistory = new Array(30).fill(0);
  3190. state.fwStatPktHistory = new Array(30).fill(0);
  3191. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3192. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3193. toggleFilterActionFields();
  3194. document.getElementById('filter-modal').classList.remove('hidden');
  3195. }
  3196. function closeFilterModal() {
  3197. stopFwStatPolling();
  3198. document.getElementById('filter-modal').classList.add('hidden');
  3199. }
  3200. function toggleFilterActionFields() {
  3201. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  3202. const rejectBox = document.getElementById('filter-action-reject-box');
  3203. const jumpBox = document.getElementById('filter-action-jump-box');
  3204. const addrBox = document.getElementById('filter-action-addrlist-box');
  3205. if (rejectBox) {
  3206. if (act === 'reject') rejectBox.classList.remove('hidden');
  3207. else rejectBox.classList.add('hidden');
  3208. }
  3209. if (jumpBox) {
  3210. if (act === 'jump') jumpBox.classList.remove('hidden');
  3211. else jumpBox.classList.add('hidden');
  3212. }
  3213. if (addrBox) {
  3214. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  3215. addrBox.classList.remove('hidden');
  3216. } else {
  3217. addrBox.classList.add('hidden');
  3218. }
  3219. }
  3220. if (act === 'log') {
  3221. const logEl = document.getElementById('filter-modal-log');
  3222. if (logEl) logEl.checked = true;
  3223. toggleFwField('logprefix', true);
  3224. }
  3225. }
  3226. function toggleFwLogPrefix() {
  3227. const isLog = document.getElementById('filter-modal-log')?.checked;
  3228. toggleFwField('logprefix', !!isLog);
  3229. }
  3230. function copyFilterRule() {
  3231. document.getElementById('filter-modal-id').value = '';
  3232. const badge = document.getElementById('fw-modal-badge');
  3233. if (badge) badge.innerText = 'New...';
  3234. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  3235. }
  3236. function resetCurrentRuleCounters() {
  3237. state.fwStatRateHistory = new Array(30).fill(0);
  3238. state.fwStatPktHistory = new Array(30).fill(0);
  3239. state.fwLastBytes = 0;
  3240. state.fwLastPackets = 0;
  3241. state.fwLastTimestamp = Date.now();
  3242. const bEl = document.getElementById('fw-stat-bytes');
  3243. const pEl = document.getElementById('fw-stat-packets');
  3244. const rEl = document.getElementById('fw-stat-rate');
  3245. const prEl = document.getElementById('fw-stat-pktrate');
  3246. if (bEl) bEl.value = '0 B';
  3247. if (pEl) pEl.value = '0';
  3248. if (rEl) rEl.value = '0 bps';
  3249. if (prEl) prEl.value = '0 p/s';
  3250. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3251. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3252. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  3253. }
  3254. async function resetAllFwCounters() {
  3255. try {
  3256. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3257. if (res.ok) {
  3258. resetCurrentRuleCounters();
  3259. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  3260. loadFirewall(false);
  3261. }
  3262. } catch (err) {
  3263. showToast('Error', err.message, 'error');
  3264. }
  3265. }
  3266. async function applyFilterRule(closeAfter = false) {
  3267. const id = document.getElementById('filter-modal-id').value;
  3268. const chain = document.getElementById('filter-modal-chain').value;
  3269. const action = document.getElementById('filter-modal-action').value;
  3270. const comment = document.getElementById('filter-modal-comment').value.trim();
  3271. const enabled = document.getElementById('filter-modal-enabled').checked;
  3272. const src = getFwFieldVal('src', true);
  3273. const dst = getFwFieldVal('dst', true);
  3274. const srclist = getFwFieldVal('srclist', true);
  3275. const dstlist = getFwFieldVal('dstlist', true);
  3276. const srcgeo = getFwFieldVal('srcgeo', true);
  3277. const dstgeo = getFwFieldVal('dstgeo', true);
  3278. const proto = getFwFieldVal('proto', true);
  3279. const sport = getFwFieldVal('sport', true);
  3280. const dport = getFwFieldVal('dport', true);
  3281. const anyport = getFwFieldVal('anyport', true);
  3282. const iniface = getFwFieldVal('iniface', true);
  3283. const outiface = getFwFieldVal('outiface', true);
  3284. const inifacelist = getFwFieldVal('inifacelist', true);
  3285. const outifacelist = getFwFieldVal('outifacelist', true);
  3286. const pktmark = getFwFieldVal('pktmark', true);
  3287. const connmark = getFwFieldVal('connmark', true);
  3288. const routingmark = getFwFieldVal('routingmark', true);
  3289. const conntype = getFwFieldVal('conntype', false);
  3290. const states = [];
  3291. const csBox = document.getElementById('fw-field-cs');
  3292. if (csBox && !csBox.classList.contains('hidden')) {
  3293. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  3294. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  3295. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  3296. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  3297. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  3298. }
  3299. const natStates = [];
  3300. const natBox = document.getElementById('fw-field-natstate');
  3301. if (natBox && !natBox.classList.contains('hidden')) {
  3302. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  3303. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  3304. }
  3305. const payload = {
  3306. id,
  3307. chain,
  3308. action,
  3309. protocol: proto || 'all',
  3310. src_address: src,
  3311. dst_address: dst,
  3312. src_port: sport,
  3313. dst_port: dport,
  3314. any_port: anyport,
  3315. in_interface: iniface,
  3316. out_interface: outiface,
  3317. in_interface_list: inifacelist,
  3318. out_interface_list: outifacelist,
  3319. packet_mark: pktmark,
  3320. connection_mark: connmark,
  3321. routing_mark: routingmark,
  3322. connection_type: conntype,
  3323. connection_state: states,
  3324. connection_nat_state: natStates,
  3325. src_address_list: srclist,
  3326. dst_address_list: dstlist,
  3327. src_geoip: srcgeo,
  3328. dst_geoip: dstgeo,
  3329. comment,
  3330. disabled: !enabled,
  3331. // Advanced tab
  3332. layer7_protocol: getFwFieldVal('layer7', false),
  3333. content: getFwFieldVal('content', false),
  3334. connection_bytes: getFwFieldVal('connbytes', false),
  3335. connection_rate: getFwFieldVal('connrate', false),
  3336. pcc: getFwFieldVal('pcc', false),
  3337. src_mac_address: getFwFieldVal('srcmac', true),
  3338. out_bridge_port: getFwFieldVal('outbridgeport', false),
  3339. in_bridge_port: getFwFieldVal('inbridgeport', false),
  3340. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  3341. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  3342. ipsec_policy: getFwFieldVal('ipsec', false),
  3343. tls_host: getFwFieldVal('tlshost', false),
  3344. ingress_priority: getFwFieldVal('ingresspriority', false),
  3345. priority: getFwFieldVal('priority', false),
  3346. dscp: getFwFieldVal('dscp', false),
  3347. tcp_mss: getFwFieldVal('tcpmss', false),
  3348. tos: document.getElementById('fw-val-tos')?.value || '',
  3349. packet_size: getFwFieldVal('pktsize', false),
  3350. random: getFwFieldVal('random', false),
  3351. tcp_flags: getFwFieldVal('tcpflags', false),
  3352. icmp_options: getFwFieldVal('icmpoptions', false),
  3353. ipv4_options: getFwFieldVal('ipv4options', false),
  3354. ttl: getFwFieldVal('ttl', false),
  3355. // Extra tab
  3356. time: getFwFieldVal('time', false),
  3357. limit: getFwFieldVal('limit', false),
  3358. dst_limit: getFwFieldVal('dstlimit', false),
  3359. psd: getFwFieldVal('psd', false),
  3360. // Action tab
  3361. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  3362. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  3363. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  3364. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  3365. log: document.getElementById('filter-modal-log')?.checked || false,
  3366. log_prefix: getFwFieldVal('logprefix', false)
  3367. };
  3368. try {
  3369. const res = await fetch(`${API_BASE}/firewall/filter`, {
  3370. method: 'POST',
  3371. headers: { 'Content-Type': 'application/json' },
  3372. body: JSON.stringify(payload)
  3373. });
  3374. if (res.ok) {
  3375. const data = await res.json();
  3376. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  3377. loadFirewall(false);
  3378. if (closeAfter) {
  3379. closeFilterModal();
  3380. } else {
  3381. if (data.id) {
  3382. document.getElementById('filter-modal-id').value = data.id;
  3383. const badge = document.getElementById('fw-modal-badge');
  3384. if (badge) badge.innerText = `#${data.id}`;
  3385. }
  3386. }
  3387. } else {
  3388. const err = await res.json();
  3389. showToast('Error', err.message || 'Failed to save rule', 'error');
  3390. }
  3391. } catch (err) {
  3392. showToast('Error', err.message, 'error');
  3393. }
  3394. }
  3395. function submitSaveFilterRule(e) {
  3396. if (e && e.preventDefault) e.preventDefault();
  3397. return applyFilterRule(true);
  3398. }
  3399. function startFwStatPolling() {
  3400. stopFwStatPolling();
  3401. pollRuleStats();
  3402. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  3403. }
  3404. function stopFwStatPolling() {
  3405. if (state.fwStatInterval) {
  3406. clearInterval(state.fwStatInterval);
  3407. state.fwStatInterval = null;
  3408. }
  3409. }
  3410. async function pollRuleStats() {
  3411. const id = document.getElementById('filter-modal-id')?.value;
  3412. if (!id) {
  3413. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  3414. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  3415. return;
  3416. }
  3417. try {
  3418. const res = await fetch(`${API_BASE}/firewall/filter`);
  3419. if (!res.ok) return;
  3420. const rules = await res.json();
  3421. const r = rules.find(x => x.id === id);
  3422. if (!r) return;
  3423. const now = Date.now();
  3424. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  3425. state.fwLastTimestamp = now;
  3426. const curBytes = r.bytes || 0;
  3427. const curPackets = r.packets || 0;
  3428. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  3429. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  3430. state.fwLastBytes = curBytes;
  3431. state.fwLastPackets = curPackets;
  3432. const rateBps = Math.round((deltaBytes * 8) / dt);
  3433. const ratePkt = Math.round(deltaPkts / dt);
  3434. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  3435. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  3436. state.fwStatRateHistory.push(rateBps);
  3437. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  3438. state.fwStatPktHistory.push(ratePkt);
  3439. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  3440. const bEl = document.getElementById('fw-stat-bytes');
  3441. const pEl = document.getElementById('fw-stat-packets');
  3442. const rEl = document.getElementById('fw-stat-rate');
  3443. const prEl = document.getElementById('fw-stat-pktrate');
  3444. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  3445. if (pEl) pEl.value = curPackets.toLocaleString();
  3446. if (rEl) rEl.value = formatBps(rateBps);
  3447. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  3448. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3449. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3450. } catch (e) {
  3451. console.error('Error polling rule stats', e);
  3452. }
  3453. }
  3454. function formatBps(bps) {
  3455. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  3456. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  3457. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  3458. return bps + ' bps';
  3459. }
  3460. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  3461. const svg = document.getElementById(svgId);
  3462. if (!svg) return;
  3463. const w = 500;
  3464. const h = 100;
  3465. const paddingRight = 45;
  3466. const graphWidth = w - paddingRight;
  3467. const maxVal = Math.max(5, ...dataArray);
  3468. const currentVal = dataArray[dataArray.length - 1] || 0;
  3469. const leg = document.getElementById(legendId);
  3470. if (leg) {
  3471. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  3472. }
  3473. let gridLines = '';
  3474. for (let i = 0; i <= 5; i++) {
  3475. const y = 8 + (i * (h - 18) / 5);
  3476. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  3477. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  3478. gridLines += `
  3479. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  3480. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  3481. `;
  3482. }
  3483. const step = graphWidth / (dataArray.length - 1);
  3484. const points = dataArray.map((val, idx) => {
  3485. const x = idx * step;
  3486. const y = (h - 10) - (val / maxVal) * (h - 20);
  3487. return `${x.toFixed(1)},${y.toFixed(1)}`;
  3488. });
  3489. const polylineStr = points.join(' ');
  3490. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  3491. svg.innerHTML = `
  3492. ${gridLines}
  3493. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  3494. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  3495. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  3496. `;
  3497. }
  3498. async function moveFilterRule(id, dir) {
  3499. try {
  3500. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  3501. method: 'POST',
  3502. headers: { 'Content-Type': 'application/json' },
  3503. body: JSON.stringify({ direction: dir })
  3504. });
  3505. if (res.ok) loadFirewall(false);
  3506. } catch (err) {
  3507. showToast('Error', err.message, 'error');
  3508. }
  3509. }
  3510. async function toggleFilterRuleState(id, disabled) {
  3511. try {
  3512. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  3513. method: 'POST',
  3514. headers: { 'Content-Type': 'application/json' },
  3515. body: JSON.stringify({ disabled })
  3516. });
  3517. if (res.ok) loadFirewall(false);
  3518. } catch (err) {
  3519. showToast('Error', err.message, 'error');
  3520. }
  3521. }
  3522. async function deleteFilterRule(id) {
  3523. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  3524. try {
  3525. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3526. if (res.ok) {
  3527. showToast('Deleted', 'Filter rule removed', 'success');
  3528. loadFirewall(false);
  3529. }
  3530. } catch (err) {
  3531. showToast('Error', err.message, 'error');
  3532. }
  3533. }
  3534. // ----------------- NAT Rules -----------------
  3535. function renderNATRules() {
  3536. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  3537. const tbody = document.getElementById('nat-table-body');
  3538. const empty = document.getElementById('nat-empty');
  3539. if (!tbody) return;
  3540. tbody.innerHTML = '';
  3541. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3542. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  3543. if (rules.length === 0) {
  3544. empty?.classList.remove('hidden');
  3545. return;
  3546. }
  3547. empty?.classList.add('hidden');
  3548. rules.forEach((r, idx) => {
  3549. const tr = document.createElement('tr');
  3550. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3551. let toTarget = '-';
  3552. if (r.action === 'jump') {
  3553. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  3554. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3555. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  3556. } else if (r.action === 'redirect') {
  3557. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  3558. } else if (r.action === 'masquerade') {
  3559. 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>`;
  3560. } else if (r.action === 'log') {
  3561. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  3562. } else {
  3563. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  3564. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  3565. }
  3566. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  3567. tr.innerHTML = `
  3568. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3569. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3570. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  3571. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3572. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3573. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  3574. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3575. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  3576. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  3577. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3578. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3579. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3580. </td>
  3581. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3582. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3583. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3584. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3585. <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>
  3586. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3587. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3588. </td>
  3589. `;
  3590. tbody.appendChild(tr);
  3591. });
  3592. }
  3593. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3594. function switchNATRuleTab(tab) {
  3595. state.activeNATRuleTab = tab;
  3596. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  3597. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3598. btn.classList.add('text-slate-400', 'border-transparent');
  3599. });
  3600. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  3601. if (activeBtn) {
  3602. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3603. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3604. }
  3605. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  3606. const activePane = document.getElementById(`nat-pane-${tab}`);
  3607. if (activePane) activePane.classList.remove('hidden');
  3608. if (tab === 'statistics') {
  3609. startNATStatPolling();
  3610. } else {
  3611. stopNATStatPolling();
  3612. }
  3613. }
  3614. function toggleNATField(fieldKey, expand) {
  3615. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  3616. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3617. if (!plusBtn || !fieldBox) return;
  3618. if (expand) {
  3619. plusBtn.classList.add('hidden');
  3620. fieldBox.classList.remove('hidden');
  3621. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3622. if (valInput) valInput.focus();
  3623. } else {
  3624. fieldBox.classList.add('hidden');
  3625. plusBtn.classList.remove('hidden');
  3626. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3627. if (valInput) {
  3628. if (valInput.tagName === 'SELECT') {
  3629. valInput.selectedIndex = 0;
  3630. } else {
  3631. valInput.value = '';
  3632. }
  3633. }
  3634. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  3635. if (invInput) invInput.checked = false;
  3636. if (fieldKey === 'days') {
  3637. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3638. const el = document.getElementById(`nat-day-${d}`);
  3639. if (el) el.checked = true;
  3640. });
  3641. }
  3642. }
  3643. }
  3644. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  3645. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3646. toggleNATField(fieldKey, true);
  3647. let strVal = String(value);
  3648. if (hasInvert) {
  3649. const inv = strVal.startsWith('!');
  3650. if (inv) strVal = strVal.slice(1);
  3651. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3652. if (invEl) invEl.checked = inv;
  3653. }
  3654. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3655. if (valEl) valEl.value = strVal;
  3656. } else {
  3657. toggleNATField(fieldKey, false);
  3658. }
  3659. }
  3660. function getNATFieldVal(fieldKey, hasInvert = false) {
  3661. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3662. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3663. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3664. let v = valEl ? valEl.value.trim() : '';
  3665. if (!v) return '';
  3666. if (hasInvert) {
  3667. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3668. if (invEl && invEl.checked) {
  3669. v = '!' + v.replace(/^!/, '');
  3670. }
  3671. }
  3672. return v;
  3673. }
  3674. function toggleMaximizeNATModal() {
  3675. const win = document.getElementById('nat-modal-window');
  3676. if (!win) return;
  3677. if (win.classList.contains('max-w-[720px]')) {
  3678. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3679. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3680. } else {
  3681. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3682. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3683. }
  3684. }
  3685. function handleNATChainChange() {
  3686. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  3687. const actSel = document.getElementById('nat-modal-action');
  3688. if (actSel) {
  3689. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  3690. actSel.value = 'masquerade';
  3691. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  3692. actSel.value = 'dst-nat';
  3693. }
  3694. }
  3695. toggleNATActionFields();
  3696. }
  3697. function toggleNATActionFields() {
  3698. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  3699. const rowAddr = document.getElementById('nat-row-toaddr');
  3700. const rowPort = document.getElementById('nat-row-toport');
  3701. const jumpBox = document.getElementById('nat-action-jump-box');
  3702. const addrBox = document.getElementById('nat-action-addrlist-box');
  3703. // Hide all dynamic rows first
  3704. if (rowAddr) rowAddr.classList.add('hidden');
  3705. if (rowPort) rowPort.classList.add('hidden');
  3706. if (jumpBox) jumpBox.classList.add('hidden');
  3707. if (addrBox) addrBox.classList.add('hidden');
  3708. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  3709. if (rowAddr) rowAddr.classList.remove('hidden');
  3710. if (rowPort) rowPort.classList.remove('hidden');
  3711. } else if (act === 'redirect' || act === 'masquerade') {
  3712. if (rowPort) rowPort.classList.remove('hidden');
  3713. } else if (act === 'jump') {
  3714. if (jumpBox) jumpBox.classList.remove('hidden');
  3715. } else if (act.includes('address-list') || act.includes('address list')) {
  3716. if (addrBox) addrBox.classList.remove('hidden');
  3717. }
  3718. if (act === 'log') {
  3719. const logEl = document.getElementById('nat-modal-log');
  3720. if (logEl) logEl.checked = true;
  3721. toggleNATField('logprefix', true);
  3722. }
  3723. }
  3724. function toggleNATLogPrefix() {
  3725. const isLog = document.getElementById('nat-modal-log')?.checked;
  3726. toggleNATField('logprefix', !!isLog);
  3727. }
  3728. function openAddNATModal() {
  3729. switchNATRuleTab('general');
  3730. const badge = document.getElementById('nat-modal-badge');
  3731. if (badge) badge.innerText = 'New...';
  3732. document.getElementById('nat-modal-id').value = '';
  3733. document.getElementById('nat-modal-enabled').checked = true;
  3734. document.getElementById('nat-modal-comment').value = '';
  3735. document.getElementById('nat-modal-chain').value = 'srcnat';
  3736. document.getElementById('nat-modal-action').value = 'masquerade';
  3737. document.getElementById('nat-modal-toaddr').value = '';
  3738. document.getElementById('nat-modal-toport').value = '';
  3739. document.getElementById('nat-modal-log').checked = false;
  3740. populateInterfaceSelect('nat-val-iniface');
  3741. populateInterfaceSelect('nat-val-outiface');
  3742. populateAddressListSelect('nat-val-srclist');
  3743. populateAddressListSelect('nat-val-dstlist');
  3744. populateGeoIPSelect('nat-val-srcgeo');
  3745. populateGeoIPSelect('nat-val-dstgeo');
  3746. const allFieldKeys = [
  3747. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3748. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3749. 'routingmark', 'conntype',
  3750. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3751. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3752. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3753. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  3754. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3755. ];
  3756. allFieldKeys.forEach(k => toggleNATField(k, false));
  3757. resetCurrentNATRuleCounters();
  3758. toggleNATActionFields();
  3759. document.getElementById('nat-modal').classList.remove('hidden');
  3760. }
  3761. function openEditNATModal(id) {
  3762. const r = (state.natRules || []).find(rule => rule.id === id);
  3763. if (!r) return;
  3764. switchNATRuleTab('general');
  3765. const badge = document.getElementById('nat-modal-badge');
  3766. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3767. document.getElementById('nat-modal-id').value = r.id;
  3768. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  3769. document.getElementById('nat-modal-comment').value = r.comment || '';
  3770. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  3771. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  3772. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  3773. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  3774. document.getElementById('nat-modal-log').checked = !!r.log;
  3775. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3776. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3777. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3778. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3779. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  3780. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  3781. setNATFieldVal('src', r.src_address, true);
  3782. setNATFieldVal('dst', r.dst_address, true);
  3783. setNATFieldVal('srclist', r.src_address_list, true);
  3784. setNATFieldVal('dstlist', r.dst_address_list, true);
  3785. setNATFieldVal('srcgeo', r.src_geoip, true);
  3786. setNATFieldVal('dstgeo', r.dst_geoip, true);
  3787. if (r.protocol && r.protocol !== 'all') {
  3788. setNATFieldVal('proto', r.protocol, true);
  3789. } else {
  3790. toggleNATField('proto', false);
  3791. }
  3792. setNATFieldVal('sport', r.src_port, true);
  3793. setNATFieldVal('dport', r.dst_port, true);
  3794. setNATFieldVal('anyport', r.any_port, true);
  3795. setNATFieldVal('iniface', r.in_interface, true);
  3796. setNATFieldVal('outiface', r.out_interface, true);
  3797. setNATFieldVal('inifacelist', r.in_interface_list, true);
  3798. setNATFieldVal('outifacelist', r.out_interface_list, true);
  3799. setNATFieldVal('pktmark', r.packet_mark, true);
  3800. setNATFieldVal('connmark', r.connection_mark, true);
  3801. setNATFieldVal('routingmark', r.routing_mark, true);
  3802. setNATFieldVal('conntype', r.connection_type, false);
  3803. // Advanced tab fields
  3804. setNATFieldVal('layer7', r.layer7_protocol, false);
  3805. setNATFieldVal('content', r.content, false);
  3806. setNATFieldVal('connbytes', r.connection_bytes, false);
  3807. setNATFieldVal('connrate', r.connection_rate, false);
  3808. setNATFieldVal('pcc', r.pcc, false);
  3809. setNATFieldVal('srcmac', r.src_mac_address, true);
  3810. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  3811. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  3812. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3813. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3814. setNATFieldVal('ipsec', r.ipsec_policy, false);
  3815. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  3816. setNATFieldVal('priority', r.priority, false);
  3817. setNATFieldVal('dscp', r.dscp, false);
  3818. setNATFieldVal('tcpmss', r.tcp_mss, false);
  3819. if (r.tos) {
  3820. const tosEl = document.getElementById('nat-val-tos');
  3821. if (tosEl) tosEl.value = r.tos;
  3822. }
  3823. setNATFieldVal('pktsize', r.packet_size, false);
  3824. setNATFieldVal('random', r.random, false);
  3825. setNATFieldVal('icmpoptions', r.icmp_options, false);
  3826. setNATFieldVal('ipv4options', r.ipv4_options, false);
  3827. setNATFieldVal('ttl', r.ttl, false);
  3828. // Extra tab fields
  3829. setNATFieldVal('time', r.time, false);
  3830. if (r.days) {
  3831. toggleNATField('days', true);
  3832. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3833. const chk = document.getElementById(`nat-day-${d}`);
  3834. if (chk) chk.checked = r.days.includes(d);
  3835. });
  3836. } else {
  3837. toggleNATField('days', false);
  3838. }
  3839. setNATFieldVal('limit', r.limit, false);
  3840. setNATFieldVal('dstlimit', r.dst_limit, false);
  3841. setNATFieldVal('psd', r.psd, false);
  3842. // Action fields
  3843. if (r.jump_target) {
  3844. const jtEl = document.getElementById('nat-modal-jumptarget');
  3845. if (jtEl) jtEl.value = r.jump_target;
  3846. }
  3847. if (r.address_list) {
  3848. const alEl = document.getElementById('nat-modal-action-addrlist');
  3849. if (alEl) alEl.value = r.address_list;
  3850. }
  3851. if (r.address_list_timeout) {
  3852. const toEl = document.getElementById('nat-modal-action-timeout');
  3853. if (toEl) toEl.value = r.address_list_timeout;
  3854. }
  3855. setNATFieldVal('logprefix', r.log_prefix, false);
  3856. // Statistics
  3857. const bEl = document.getElementById('nat-stat-bytes');
  3858. const pEl = document.getElementById('nat-stat-packets');
  3859. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3860. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3861. state.natLastBytes = r.bytes || 0;
  3862. state.natLastPackets = r.packets || 0;
  3863. state.natLastTimestamp = Date.now();
  3864. state.natStatRateHistory = new Array(30).fill(0);
  3865. state.natStatPktHistory = new Array(30).fill(0);
  3866. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3867. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3868. toggleNATActionFields();
  3869. document.getElementById('nat-modal').classList.remove('hidden');
  3870. }
  3871. function closeNATModal() {
  3872. stopNATStatPolling();
  3873. document.getElementById('nat-modal').classList.add('hidden');
  3874. }
  3875. function copyNATRule() {
  3876. document.getElementById('nat-modal-id').value = '';
  3877. const badge = document.getElementById('nat-modal-badge');
  3878. if (badge) badge.innerText = 'New...';
  3879. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  3880. }
  3881. function resetCurrentNATRuleCounters() {
  3882. state.natStatRateHistory = new Array(30).fill(0);
  3883. state.natStatPktHistory = new Array(30).fill(0);
  3884. state.natLastBytes = 0;
  3885. state.natLastPackets = 0;
  3886. state.natLastTimestamp = Date.now();
  3887. const bEl = document.getElementById('nat-stat-bytes');
  3888. const pEl = document.getElementById('nat-stat-packets');
  3889. const rEl = document.getElementById('nat-stat-rate');
  3890. const prEl = document.getElementById('nat-stat-pktrate');
  3891. if (bEl) bEl.value = '0 B';
  3892. if (pEl) pEl.value = '0';
  3893. if (rEl) rEl.value = '0 bps';
  3894. if (prEl) prEl.value = '0 p/s';
  3895. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3896. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3897. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  3898. }
  3899. async function applyNATRule(closeAfter = false) {
  3900. const id = document.getElementById('nat-modal-id').value;
  3901. const chain = document.getElementById('nat-modal-chain').value;
  3902. const action = document.getElementById('nat-modal-action').value;
  3903. const comment = document.getElementById('nat-modal-comment').value.trim();
  3904. const enabled = document.getElementById('nat-modal-enabled').checked;
  3905. const src = getNATFieldVal('src', true);
  3906. const dst = getNATFieldVal('dst', true);
  3907. const srclist = getNATFieldVal('srclist', true);
  3908. const dstlist = getNATFieldVal('dstlist', true);
  3909. const srcgeo = getNATFieldVal('srcgeo', true);
  3910. const dstgeo = getNATFieldVal('dstgeo', true);
  3911. const proto = getNATFieldVal('proto', true);
  3912. const sport = getNATFieldVal('sport', true);
  3913. const dport = getNATFieldVal('dport', true);
  3914. const anyport = getNATFieldVal('anyport', true);
  3915. const iniface = getNATFieldVal('iniface', true);
  3916. const outiface = getNATFieldVal('outiface', true);
  3917. const inifacelist = getNATFieldVal('inifacelist', true);
  3918. const outifacelist = getNATFieldVal('outifacelist', true);
  3919. const pktmark = getNATFieldVal('pktmark', true);
  3920. const connmark = getNATFieldVal('connmark', true);
  3921. const routingmark = getNATFieldVal('routingmark', true);
  3922. const conntype = getNATFieldVal('conntype', false);
  3923. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  3924. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  3925. const payload = {
  3926. id,
  3927. chain,
  3928. action,
  3929. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  3930. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  3931. protocol: proto || 'all',
  3932. src_address: src,
  3933. dst_address: dst,
  3934. src_port: sport,
  3935. dst_port: dport,
  3936. any_port: anyport,
  3937. in_interface: iniface,
  3938. out_interface: outiface,
  3939. in_interface_list: inifacelist,
  3940. out_interface_list: outifacelist,
  3941. packet_mark: pktmark,
  3942. connection_mark: connmark,
  3943. routing_mark: routingmark,
  3944. connection_type: conntype,
  3945. src_address_list: srclist,
  3946. dst_address_list: dstlist,
  3947. src_geoip: srcgeo,
  3948. dst_geoip: dstgeo,
  3949. comment,
  3950. disabled: !enabled,
  3951. // Advanced tab
  3952. layer7_protocol: getNATFieldVal('layer7', false),
  3953. content: getNATFieldVal('content', false),
  3954. connection_bytes: getNATFieldVal('connbytes', false),
  3955. connection_rate: getNATFieldVal('connrate', false),
  3956. pcc: getNATFieldVal('pcc', false),
  3957. src_mac_address: getNATFieldVal('srcmac', true),
  3958. out_bridge_port: getNATFieldVal('outbridgeport', false),
  3959. in_bridge_port: getNATFieldVal('inbridgeport', false),
  3960. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  3961. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  3962. ipsec_policy: getNATFieldVal('ipsec', false),
  3963. ingress_priority: getNATFieldVal('ingresspriority', false),
  3964. priority: getNATFieldVal('priority', false),
  3965. dscp: getNATFieldVal('dscp', false),
  3966. tcp_mss: getNATFieldVal('tcpmss', false),
  3967. tos: document.getElementById('nat-val-tos')?.value || '',
  3968. packet_size: getNATFieldVal('pktsize', false),
  3969. random: getNATFieldVal('random', false),
  3970. icmp_options: getNATFieldVal('icmpoptions', false),
  3971. ipv4_options: getNATFieldVal('ipv4options', false),
  3972. ttl: getNATFieldVal('ttl', false),
  3973. // Extra tab
  3974. time: getNATFieldVal('time', false),
  3975. limit: getNATFieldVal('limit', false),
  3976. dst_limit: getNATFieldVal('dstlimit', false),
  3977. psd: getNATFieldVal('psd', false),
  3978. // Action tab
  3979. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  3980. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  3981. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  3982. log: document.getElementById('nat-modal-log')?.checked || false,
  3983. log_prefix: getNATFieldVal('logprefix', false)
  3984. };
  3985. try {
  3986. const res = await fetch(`${API_BASE}/firewall/nat`, {
  3987. method: 'POST',
  3988. headers: { 'Content-Type': 'application/json' },
  3989. body: JSON.stringify(payload)
  3990. });
  3991. if (res.ok) {
  3992. const data = await res.json();
  3993. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  3994. loadFirewall(false);
  3995. if (closeAfter) {
  3996. closeNATModal();
  3997. } else {
  3998. if (data.id) {
  3999. document.getElementById('nat-modal-id').value = data.id;
  4000. const badge = document.getElementById('nat-modal-badge');
  4001. if (badge) badge.innerText = `#${data.id}`;
  4002. }
  4003. }
  4004. } else {
  4005. const err = await res.json();
  4006. showToast('Error', err.message || 'Failed to save rule', 'error');
  4007. }
  4008. } catch (err) {
  4009. showToast('Error', err.message, 'error');
  4010. }
  4011. }
  4012. function submitSaveNATRule(e) {
  4013. if (e && e.preventDefault) e.preventDefault();
  4014. return applyNATRule(true);
  4015. }
  4016. function startNATStatPolling() {
  4017. stopNATStatPolling();
  4018. pollNATRuleStats();
  4019. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  4020. }
  4021. function stopNATStatPolling() {
  4022. if (state.natStatInterval) {
  4023. clearInterval(state.natStatInterval);
  4024. state.natStatInterval = null;
  4025. }
  4026. }
  4027. async function pollNATRuleStats() {
  4028. const id = document.getElementById('nat-modal-id')?.value;
  4029. if (!id) {
  4030. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  4031. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  4032. return;
  4033. }
  4034. try {
  4035. const res = await fetch(`${API_BASE}/firewall/nat`);
  4036. if (!res.ok) return;
  4037. const rules = await res.json();
  4038. const r = rules.find(x => x.id === id);
  4039. if (!r) return;
  4040. const now = Date.now();
  4041. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  4042. state.natLastTimestamp = now;
  4043. const curBytes = r.bytes || 0;
  4044. const curPackets = r.packets || 0;
  4045. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  4046. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  4047. state.natLastBytes = curBytes;
  4048. state.natLastPackets = curPackets;
  4049. const rateBps = Math.round((deltaBytes * 8) / dt);
  4050. const ratePkt = Math.round(deltaPkts / dt);
  4051. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  4052. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  4053. state.natStatRateHistory.push(rateBps);
  4054. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  4055. state.natStatPktHistory.push(ratePkt);
  4056. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  4057. const bEl = document.getElementById('nat-stat-bytes');
  4058. const pEl = document.getElementById('nat-stat-packets');
  4059. const rEl = document.getElementById('nat-stat-rate');
  4060. const prEl = document.getElementById('nat-stat-pktrate');
  4061. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4062. if (pEl) pEl.value = curPackets.toLocaleString();
  4063. if (rEl) rEl.value = formatBps(rateBps);
  4064. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4065. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4066. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4067. } catch (e) {
  4068. console.error('Error polling NAT rule stats', e);
  4069. }
  4070. }
  4071. async function moveNATRule(id, dir) {
  4072. try {
  4073. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  4074. method: 'POST',
  4075. headers: { 'Content-Type': 'application/json' },
  4076. body: JSON.stringify({ direction: dir })
  4077. });
  4078. if (res.ok) loadFirewall(false);
  4079. } catch (err) {
  4080. showToast('Error', err.message, 'error');
  4081. }
  4082. }
  4083. async function toggleNATRuleState(id, disabled) {
  4084. try {
  4085. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  4086. method: 'POST',
  4087. headers: { 'Content-Type': 'application/json' },
  4088. body: JSON.stringify({ disabled })
  4089. });
  4090. if (res.ok) loadFirewall(false);
  4091. } catch (err) {
  4092. showToast('Error', err.message, 'error');
  4093. }
  4094. }
  4095. async function deleteNATRule(id) {
  4096. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  4097. try {
  4098. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4099. if (res.ok) {
  4100. showToast('Deleted', 'NAT rule removed', 'success');
  4101. loadFirewall(false);
  4102. }
  4103. } catch (err) {
  4104. showToast('Error', err.message, 'error');
  4105. }
  4106. }
  4107. // ----------------- Mangle Rules -----------------
  4108. function renderMangleRules() {
  4109. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  4110. const tbody = document.getElementById('mangle-table-body');
  4111. const empty = document.getElementById('mangle-empty');
  4112. if (!tbody) return;
  4113. tbody.innerHTML = '';
  4114. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4115. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  4116. if (rules.length === 0) {
  4117. empty?.classList.remove('hidden');
  4118. return;
  4119. }
  4120. empty?.classList.add('hidden');
  4121. rules.forEach((r, idx) => {
  4122. const tr = document.createElement('tr');
  4123. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4124. let markVal = '<span class="text-slate-500">-</span>';
  4125. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  4126. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  4127. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  4128. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  4129. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  4130. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  4131. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  4132. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  4133. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  4134. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4135. 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>`;
  4136. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4137. tr.innerHTML = `
  4138. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4139. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4140. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  4141. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4142. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4143. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4144. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  4145. <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>
  4146. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4147. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  4148. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4149. </td>
  4150. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4151. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4152. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4153. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4154. <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>
  4155. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4156. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4157. </td>
  4158. `;
  4159. tbody.appendChild(tr);
  4160. });
  4161. }
  4162. // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4163. function switchMangleRuleTab(tab) {
  4164. state.activeMangleRuleTab = tab;
  4165. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4166. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4167. btn.classList.add('text-slate-400', 'border-transparent');
  4168. });
  4169. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4170. if (activeBtn) {
  4171. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4172. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4173. }
  4174. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4175. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4176. if (activePane) activePane.classList.remove('hidden');
  4177. if (tab === 'statistics') {
  4178. startMangleStatPolling();
  4179. } else {
  4180. stopMangleStatPolling();
  4181. }
  4182. }
  4183. function toggleMangleField(fieldKey, expand) {
  4184. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4185. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4186. if (!plusBtn || !fieldBox) return;
  4187. if (expand) {
  4188. plusBtn.classList.add('hidden');
  4189. fieldBox.classList.remove('hidden');
  4190. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4191. if (valInput) valInput.focus();
  4192. } else {
  4193. fieldBox.classList.add('hidden');
  4194. plusBtn.classList.remove('hidden');
  4195. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4196. if (valInput) {
  4197. if (valInput.tagName === 'SELECT') {
  4198. valInput.selectedIndex = 0;
  4199. } else {
  4200. valInput.value = '';
  4201. }
  4202. }
  4203. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4204. if (invInput) invInput.checked = false;
  4205. if (fieldKey === 'cs') {
  4206. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4207. const el = document.getElementById(id);
  4208. if (el) el.checked = false;
  4209. });
  4210. }
  4211. if (fieldKey === 'natstate') {
  4212. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4213. const el = document.getElementById(id);
  4214. if (el) el.checked = false;
  4215. });
  4216. }
  4217. }
  4218. }
  4219. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4220. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4221. toggleMangleField(fieldKey, true);
  4222. let strVal = String(value);
  4223. if (hasInvert) {
  4224. const inv = strVal.startsWith('!');
  4225. if (inv) strVal = strVal.slice(1);
  4226. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4227. if (invEl) invEl.checked = inv;
  4228. }
  4229. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4230. if (valEl) valEl.value = strVal;
  4231. } else {
  4232. toggleMangleField(fieldKey, false);
  4233. }
  4234. }
  4235. function getMangleFieldVal(fieldKey, hasInvert = false) {
  4236. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4237. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4238. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4239. let v = valEl ? valEl.value.trim() : '';
  4240. if (!v) return '';
  4241. if (hasInvert) {
  4242. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4243. if (invEl && invEl.checked) {
  4244. v = '!' + v.replace(/^!/, '');
  4245. }
  4246. }
  4247. return v;
  4248. }
  4249. function toggleMaximizeMangleModal() {
  4250. const win = document.getElementById('mangle-modal-window');
  4251. if (!win) return;
  4252. if (win.classList.contains('max-w-[720px]')) {
  4253. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4254. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4255. } else {
  4256. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4257. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4258. }
  4259. }
  4260. function toggleMangleActionFields() {
  4261. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  4262. // Hide all dynamic rows first
  4263. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  4264. const el = document.getElementById(`mangle-row-${id}`);
  4265. if (el) el.classList.add('hidden');
  4266. });
  4267. const jumpBox = document.getElementById('mangle-action-jump-box');
  4268. const addrBox = document.getElementById('mangle-action-addrlist-box');
  4269. if (jumpBox) jumpBox.classList.add('hidden');
  4270. if (addrBox) addrBox.classList.add('hidden');
  4271. // Activate matching rows
  4272. if (act === 'mark-connection') {
  4273. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  4274. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4275. } else if (act === 'mark-routing') {
  4276. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  4277. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4278. } else if (act === 'mark-packet') {
  4279. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  4280. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4281. } else if (act === 'change-mss') {
  4282. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  4283. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4284. } else if (act === 'change-dscp') {
  4285. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  4286. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4287. } else if (act === 'change-ttl') {
  4288. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  4289. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4290. } else if (act === 'set-priority') {
  4291. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  4292. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4293. } else if (act === 'route') {
  4294. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  4295. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4296. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  4297. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  4298. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4299. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  4300. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4301. } else if (act === 'jump') {
  4302. if (jumpBox) jumpBox.classList.remove('hidden');
  4303. } else if (act.includes('address-list') || act.includes('address list')) {
  4304. if (addrBox) addrBox.classList.remove('hidden');
  4305. }
  4306. if (act === 'log') {
  4307. const logEl = document.getElementById('mangle-modal-log');
  4308. if (logEl) logEl.checked = true;
  4309. toggleMangleField('logprefix', true);
  4310. }
  4311. }
  4312. function toggleMangleLogPrefix() {
  4313. const isLog = document.getElementById('mangle-modal-log')?.checked;
  4314. toggleMangleField('logprefix', !!isLog);
  4315. }
  4316. const allMangleFieldKeys = [
  4317. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4318. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4319. 'routingmark', 'conntype', 'cs', 'natstate',
  4320. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4321. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4322. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4323. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  4324. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  4325. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  4326. ];
  4327. function openAddMangleModal() {
  4328. switchMangleRuleTab('general');
  4329. const badge = document.getElementById('mangle-modal-badge');
  4330. if (badge) badge.innerText = 'New...';
  4331. document.getElementById('mangle-modal-id').value = '';
  4332. document.getElementById('mangle-modal-enabled').checked = true;
  4333. document.getElementById('mangle-modal-comment').value = '';
  4334. document.getElementById('mangle-modal-chain').value = 'prerouting';
  4335. document.getElementById('mangle-modal-action').value = 'mark-connection';
  4336. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  4337. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  4338. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  4339. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  4340. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  4341. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  4342. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  4343. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  4344. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  4345. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  4346. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  4347. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  4348. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  4349. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  4350. populateInterfaceSelect('mangle-val-iniface');
  4351. populateInterfaceSelect('mangle-val-outiface');
  4352. populateAddressListSelect('mangle-val-srclist');
  4353. populateAddressListSelect('mangle-val-dstlist');
  4354. populateGeoIPSelect('mangle-val-srcgeo');
  4355. populateGeoIPSelect('mangle-val-dstgeo');
  4356. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  4357. resetCurrentMangleRuleCounters();
  4358. toggleMangleActionFields();
  4359. document.getElementById('mangle-modal').classList.remove('hidden');
  4360. }
  4361. function openEditMangleModal(id) {
  4362. const r = (state.mangleRules || []).find(rule => rule.id === id);
  4363. if (!r) return;
  4364. switchMangleRuleTab('general');
  4365. const badge = document.getElementById('mangle-modal-badge');
  4366. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4367. document.getElementById('mangle-modal-id').value = r.id;
  4368. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  4369. document.getElementById('mangle-modal-comment').value = r.comment || '';
  4370. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  4371. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  4372. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  4373. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  4374. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  4375. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  4376. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  4377. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  4378. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  4379. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  4380. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  4381. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  4382. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  4383. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  4384. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  4385. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  4386. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4387. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4388. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4389. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4390. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  4391. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  4392. setMangleFieldVal('src', r.src_address, true);
  4393. setMangleFieldVal('dst', r.dst_address, true);
  4394. setMangleFieldVal('srclist', r.src_address_list, true);
  4395. setMangleFieldVal('dstlist', r.dst_address_list, true);
  4396. setMangleFieldVal('srcgeo', r.src_geoip, true);
  4397. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  4398. if (r.protocol && r.protocol !== 'all') {
  4399. setMangleFieldVal('proto', r.protocol, true);
  4400. } else {
  4401. toggleMangleField('proto', false);
  4402. }
  4403. setMangleFieldVal('sport', r.src_port, true);
  4404. setMangleFieldVal('dport', r.dst_port, true);
  4405. setMangleFieldVal('anyport', r.any_port, true);
  4406. setMangleFieldVal('iniface', r.in_interface, true);
  4407. setMangleFieldVal('outiface', r.out_interface, true);
  4408. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  4409. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  4410. setMangleFieldVal('pktmark', r.packet_mark, true);
  4411. setMangleFieldVal('connmark', r.connection_mark, true);
  4412. setMangleFieldVal('routingmark', r.routing_mark, true);
  4413. setMangleFieldVal('conntype', r.connection_type, false);
  4414. // Connection State
  4415. const states = r.connection_state || [];
  4416. if (states.length > 0) {
  4417. toggleMangleField('cs', true);
  4418. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4419. const el = document.getElementById(`mangle-modal-cs-${s}`);
  4420. if (el) el.checked = states.includes(s);
  4421. });
  4422. } else {
  4423. toggleMangleField('cs', false);
  4424. }
  4425. // Connection NAT State
  4426. const natStates = r.connection_nat_state || [];
  4427. if (natStates.length > 0) {
  4428. toggleMangleField('natstate', true);
  4429. ['srcnat', 'dstnat'].forEach(s => {
  4430. const el = document.getElementById(`mangle-modal-nat-${s}`);
  4431. if (el) el.checked = natStates.includes(s);
  4432. });
  4433. } else {
  4434. toggleMangleField('natstate', false);
  4435. }
  4436. // Advanced tab fields
  4437. setMangleFieldVal('layer7', r.layer7_protocol, false);
  4438. setMangleFieldVal('content', r.content, false);
  4439. setMangleFieldVal('connbytes', r.connection_bytes, false);
  4440. setMangleFieldVal('connrate', r.connection_rate, false);
  4441. setMangleFieldVal('pcc', r.pcc, false);
  4442. setMangleFieldVal('srcmac', r.src_mac_address, true);
  4443. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  4444. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  4445. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4446. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4447. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  4448. setMangleFieldVal('tlshost', r.tls_host, false);
  4449. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  4450. setMangleFieldVal('priority', r.priority, false);
  4451. setMangleFieldVal('dscp', r.dscp, false);
  4452. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  4453. if (r.tos) {
  4454. const tosEl = document.getElementById('mangle-val-tos');
  4455. if (tosEl) tosEl.value = r.tos;
  4456. }
  4457. setMangleFieldVal('pktsize', r.packet_size, false);
  4458. setMangleFieldVal('random', r.random, false);
  4459. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  4460. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  4461. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  4462. setMangleFieldVal('ttl', r.ttl, false);
  4463. // Extra tab fields
  4464. setMangleFieldVal('nth', r.nth, false);
  4465. setMangleFieldVal('connlimit', r.connection_limit, false);
  4466. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  4467. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  4468. setMangleFieldVal('hotspot', r.hotspot, false);
  4469. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  4470. setMangleFieldVal('limit', r.limit, false);
  4471. setMangleFieldVal('dstlimit', r.dst_limit, false);
  4472. setMangleFieldVal('time', r.time, false);
  4473. setMangleFieldVal('psd', r.psd, false);
  4474. // Action fields
  4475. if (r.jump_target) {
  4476. const jtEl = document.getElementById('mangle-modal-jumptarget');
  4477. if (jtEl) jtEl.value = r.jump_target;
  4478. }
  4479. if (r.address_list) {
  4480. const alEl = document.getElementById('mangle-modal-action-addrlist');
  4481. if (alEl) alEl.value = r.address_list;
  4482. }
  4483. if (r.address_list_timeout) {
  4484. const toEl = document.getElementById('mangle-modal-action-timeout');
  4485. if (toEl) toEl.value = r.address_list_timeout;
  4486. }
  4487. setMangleFieldVal('logprefix', r.log_prefix, false);
  4488. // Statistics
  4489. const bEl = document.getElementById('mangle-stat-bytes');
  4490. const pEl = document.getElementById('mangle-stat-packets');
  4491. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4492. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4493. state.mangleLastBytes = r.bytes || 0;
  4494. state.mangleLastPackets = r.packets || 0;
  4495. state.mangleLastTimestamp = Date.now();
  4496. state.mangleStatRateHistory = new Array(30).fill(0);
  4497. state.mangleStatPktHistory = new Array(30).fill(0);
  4498. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4499. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4500. toggleMangleActionFields();
  4501. document.getElementById('mangle-modal').classList.remove('hidden');
  4502. }
  4503. function closeMangleModal() {
  4504. stopMangleStatPolling();
  4505. document.getElementById('mangle-modal').classList.add('hidden');
  4506. }
  4507. function copyMangleRule() {
  4508. document.getElementById('mangle-modal-id').value = '';
  4509. const badge = document.getElementById('mangle-modal-badge');
  4510. if (badge) badge.innerText = 'New...';
  4511. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  4512. }
  4513. function resetCurrentMangleRuleCounters() {
  4514. state.mangleStatRateHistory = new Array(30).fill(0);
  4515. state.mangleStatPktHistory = new Array(30).fill(0);
  4516. state.mangleLastBytes = 0;
  4517. state.mangleLastPackets = 0;
  4518. state.mangleLastTimestamp = Date.now();
  4519. const bEl = document.getElementById('mangle-stat-bytes');
  4520. const pEl = document.getElementById('mangle-stat-packets');
  4521. const rEl = document.getElementById('mangle-stat-rate');
  4522. const prEl = document.getElementById('mangle-stat-pktrate');
  4523. if (bEl) bEl.value = '0 B';
  4524. if (pEl) pEl.value = '0';
  4525. if (rEl) rEl.value = '0 bps';
  4526. if (prEl) prEl.value = '0 p/s';
  4527. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4528. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4529. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  4530. }
  4531. async function applyMangleRule(closeAfter = false) {
  4532. const id = document.getElementById('mangle-modal-id').value;
  4533. const chain = document.getElementById('mangle-modal-chain').value;
  4534. const action = document.getElementById('mangle-modal-action').value;
  4535. const comment = document.getElementById('mangle-modal-comment').value.trim();
  4536. const enabled = document.getElementById('mangle-modal-enabled').checked;
  4537. const src = getMangleFieldVal('src', true);
  4538. const dst = getMangleFieldVal('dst', true);
  4539. const srclist = getMangleFieldVal('srclist', true);
  4540. const dstlist = getMangleFieldVal('dstlist', true);
  4541. const srcgeo = getMangleFieldVal('srcgeo', true);
  4542. const dstgeo = getMangleFieldVal('dstgeo', true);
  4543. const proto = getMangleFieldVal('proto', true);
  4544. const sport = getMangleFieldVal('sport', true);
  4545. const dport = getMangleFieldVal('dport', true);
  4546. const anyport = getMangleFieldVal('anyport', true);
  4547. const iniface = getMangleFieldVal('iniface', true);
  4548. const outiface = getMangleFieldVal('outiface', true);
  4549. const inifacelist = getMangleFieldVal('inifacelist', true);
  4550. const outifacelist = getMangleFieldVal('outifacelist', true);
  4551. const pktmark = getMangleFieldVal('pktmark', true);
  4552. const connmark = getMangleFieldVal('connmark', true);
  4553. const routingmark = getMangleFieldVal('routingmark', true);
  4554. const conntype = getMangleFieldVal('conntype', false);
  4555. const states = [];
  4556. const csBox = document.getElementById('mangle-field-cs');
  4557. if (csBox && !csBox.classList.contains('hidden')) {
  4558. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4559. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  4560. });
  4561. }
  4562. const natStates = [];
  4563. const natBox = document.getElementById('mangle-field-natstate');
  4564. if (natBox && !natBox.classList.contains('hidden')) {
  4565. ['srcnat', 'dstnat'].forEach(s => {
  4566. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  4567. });
  4568. }
  4569. const payload = {
  4570. id,
  4571. chain,
  4572. action,
  4573. protocol: proto || 'all',
  4574. src_address: src,
  4575. dst_address: dst,
  4576. src_port: sport,
  4577. dst_port: dport,
  4578. any_port: anyport,
  4579. in_interface: iniface,
  4580. out_interface: outiface,
  4581. in_interface_list: inifacelist,
  4582. out_interface_list: outifacelist,
  4583. packet_mark: pktmark,
  4584. connection_mark: connmark,
  4585. routing_mark: routingmark,
  4586. connection_type: conntype,
  4587. connection_state: states,
  4588. connection_nat_state: natStates,
  4589. src_address_list: srclist,
  4590. dst_address_list: dstlist,
  4591. src_geoip: srcgeo,
  4592. dst_geoip: dstgeo,
  4593. comment,
  4594. disabled: !enabled,
  4595. // Advanced tab
  4596. layer7_protocol: getMangleFieldVal('layer7', false),
  4597. content: getMangleFieldVal('content', false),
  4598. connection_bytes: getMangleFieldVal('connbytes', false),
  4599. connection_rate: getMangleFieldVal('connrate', false),
  4600. pcc: getMangleFieldVal('pcc', false),
  4601. src_mac_address: getMangleFieldVal('srcmac', true),
  4602. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  4603. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  4604. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  4605. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  4606. ipsec_policy: getMangleFieldVal('ipsec', false),
  4607. tls_host: getMangleFieldVal('tlshost', false),
  4608. ingress_priority: getMangleFieldVal('ingresspriority', false),
  4609. priority: getMangleFieldVal('priority', false),
  4610. dscp: getMangleFieldVal('dscp', false),
  4611. tcp_mss: getMangleFieldVal('tcpmss', false),
  4612. tos: document.getElementById('mangle-val-tos')?.value || '',
  4613. packet_size: getMangleFieldVal('pktsize', false),
  4614. random: getMangleFieldVal('random', false),
  4615. tcp_flags: getMangleFieldVal('tcpflags', false),
  4616. icmp_options: getMangleFieldVal('icmpoptions', false),
  4617. ipv4_options: getMangleFieldVal('ipv4options', false),
  4618. ttl: getMangleFieldVal('ttl', false),
  4619. // Extra tab
  4620. nth: getMangleFieldVal('nth', false),
  4621. connection_limit: getMangleFieldVal('connlimit', false),
  4622. src_address_type: getMangleFieldVal('srcaddrtype', false),
  4623. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  4624. hotspot: getMangleFieldVal('hotspot', false),
  4625. ip_fragment: getMangleFieldVal('ipfragment', false),
  4626. limit: getMangleFieldVal('limit', false),
  4627. dst_limit: getMangleFieldVal('dstlimit', false),
  4628. time: getMangleFieldVal('time', false),
  4629. psd: getMangleFieldVal('psd', false),
  4630. // Action tab
  4631. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  4632. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  4633. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  4634. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  4635. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  4636. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  4637. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  4638. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  4639. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  4640. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  4641. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  4642. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  4643. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  4644. log: document.getElementById('mangle-modal-log')?.checked || false,
  4645. log_prefix: getMangleFieldVal('logprefix', false)
  4646. };
  4647. try {
  4648. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  4649. method: 'POST',
  4650. headers: { 'Content-Type': 'application/json' },
  4651. body: JSON.stringify(payload)
  4652. });
  4653. if (res.ok) {
  4654. const data = await res.json();
  4655. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  4656. loadFirewall(false);
  4657. if (closeAfter) {
  4658. closeMangleModal();
  4659. } else {
  4660. if (data.id) {
  4661. document.getElementById('mangle-modal-id').value = data.id;
  4662. const badge = document.getElementById('mangle-modal-badge');
  4663. if (badge) badge.innerText = `#${data.id}`;
  4664. }
  4665. }
  4666. } else {
  4667. const err = await res.json();
  4668. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  4669. }
  4670. } catch (err) {
  4671. showToast('Error', err.message, 'error');
  4672. }
  4673. }
  4674. function submitSaveMangleRule(e) {
  4675. if (e && e.preventDefault) e.preventDefault();
  4676. return applyMangleRule(true);
  4677. }
  4678. function startMangleStatPolling() {
  4679. stopMangleStatPolling();
  4680. pollMangleRuleStats();
  4681. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  4682. }
  4683. function stopMangleStatPolling() {
  4684. if (state.mangleStatInterval) {
  4685. clearInterval(state.mangleStatInterval);
  4686. state.mangleStatInterval = null;
  4687. }
  4688. }
  4689. async function pollMangleRuleStats() {
  4690. const id = document.getElementById('mangle-modal-id')?.value;
  4691. if (!id) {
  4692. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  4693. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  4694. return;
  4695. }
  4696. try {
  4697. const res = await fetch(`${API_BASE}/firewall/mangle`);
  4698. if (!res.ok) return;
  4699. const rules = await res.json();
  4700. const r = rules.find(x => x.id === id);
  4701. if (!r) return;
  4702. const now = Date.now();
  4703. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  4704. state.mangleLastTimestamp = now;
  4705. const curBytes = r.bytes || 0;
  4706. const curPackets = r.packets || 0;
  4707. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  4708. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  4709. state.mangleLastBytes = curBytes;
  4710. state.mangleLastPackets = curPackets;
  4711. const rateBps = Math.round((deltaBytes * 8) / dt);
  4712. const ratePkt = Math.round(deltaPkts / dt);
  4713. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  4714. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  4715. state.mangleStatRateHistory.push(rateBps);
  4716. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  4717. state.mangleStatPktHistory.push(ratePkt);
  4718. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  4719. const bEl = document.getElementById('mangle-stat-bytes');
  4720. const pEl = document.getElementById('mangle-stat-packets');
  4721. const rEl = document.getElementById('mangle-stat-rate');
  4722. const prEl = document.getElementById('mangle-stat-pktrate');
  4723. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4724. if (pEl) pEl.value = curPackets.toLocaleString();
  4725. if (rEl) rEl.value = formatBps(rateBps);
  4726. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4727. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4728. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4729. } catch (e) {
  4730. console.error('Error polling Mangle rule stats', e);
  4731. }
  4732. }
  4733. async function moveMangleRule(id, dir) {
  4734. try {
  4735. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  4736. method: 'POST',
  4737. headers: { 'Content-Type': 'application/json' },
  4738. body: JSON.stringify({ direction: dir })
  4739. });
  4740. if (res.ok) loadFirewall(false);
  4741. } catch (err) {
  4742. showToast('Error', err.message, 'error');
  4743. }
  4744. }
  4745. async function toggleMangleRuleState(id, disabled) {
  4746. try {
  4747. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  4748. method: 'POST',
  4749. headers: { 'Content-Type': 'application/json' },
  4750. body: JSON.stringify({ disabled })
  4751. });
  4752. if (res.ok) loadFirewall(false);
  4753. } catch (err) {
  4754. showToast('Error', err.message, 'error');
  4755. }
  4756. }
  4757. async function deleteMangleRule(id) {
  4758. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  4759. try {
  4760. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4761. if (res.ok) {
  4762. showToast('Deleted', 'Mangle rule removed', 'success');
  4763. loadFirewall(false);
  4764. }
  4765. } catch (err) {
  4766. showToast('Error', err.message, 'error');
  4767. }
  4768. }
  4769. // ----------------- Address Lists -----------------
  4770. function renderAddressLists() {
  4771. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  4772. const tbody = document.getElementById('addrlist-table-body');
  4773. const empty = document.getElementById('addrlist-empty');
  4774. if (!tbody) return;
  4775. tbody.innerHTML = '';
  4776. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  4777. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  4778. // Update filter select
  4779. const sel = document.getElementById('addrlist-filter-name');
  4780. if (sel) {
  4781. const cur = sel.value;
  4782. sel.innerHTML = '<option value="">All Lists</option>';
  4783. const set = new Set((state.addressLists || []).map(a => a.name));
  4784. set.forEach(n => {
  4785. const opt = document.createElement('option');
  4786. opt.value = n;
  4787. opt.innerText = n;
  4788. if (n === cur) opt.selected = true;
  4789. sel.appendChild(opt);
  4790. });
  4791. }
  4792. if (entries.length === 0) {
  4793. empty?.classList.remove('hidden');
  4794. return;
  4795. }
  4796. empty?.classList.add('hidden');
  4797. entries.forEach((e, idx) => {
  4798. const tr = document.createElement('tr');
  4799. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  4800. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  4801. tr.innerHTML = `
  4802. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  4803. <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>
  4804. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  4805. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  4806. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  4807. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4808. <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>
  4809. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  4810. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4811. </td>
  4812. `;
  4813. tbody.appendChild(tr);
  4814. });
  4815. populateCommonAddrListDatalist();
  4816. }
  4817. function openAddAddrListModal() {
  4818. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  4819. document.getElementById('addrlist-modal-id').value = '';
  4820. document.getElementById('addrlist-modal-name').value = '';
  4821. document.getElementById('addrlist-modal-addr').value = '';
  4822. document.getElementById('addrlist-modal-comment').value = '';
  4823. document.getElementById('addrlist-modal-disabled').checked = false;
  4824. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4825. if (submitBtn) submitBtn.innerText = 'Add to List';
  4826. document.getElementById('addrlist-modal').classList.remove('hidden');
  4827. }
  4828. function openEditAddrListModal(id) {
  4829. const e = (state.addressLists || []).find(item => item.id === id);
  4830. if (!e) return;
  4831. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  4832. document.getElementById('addrlist-modal-id').value = e.id;
  4833. document.getElementById('addrlist-modal-name').value = e.name;
  4834. document.getElementById('addrlist-modal-addr').value = e.address;
  4835. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  4836. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  4837. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4838. if (submitBtn) submitBtn.innerText = 'Save Changes';
  4839. document.getElementById('addrlist-modal').classList.remove('hidden');
  4840. }
  4841. function closeAddrListModal() {
  4842. document.getElementById('addrlist-modal').classList.add('hidden');
  4843. }
  4844. async function submitSaveAddrList(e) {
  4845. e.preventDefault();
  4846. const id = document.getElementById('addrlist-modal-id').value;
  4847. const name = document.getElementById('addrlist-modal-name').value.trim();
  4848. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  4849. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  4850. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  4851. try {
  4852. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  4853. method: 'POST',
  4854. headers: { 'Content-Type': 'application/json' },
  4855. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  4856. });
  4857. if (res.ok) {
  4858. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  4859. closeAddrListModal();
  4860. loadFirewall(false);
  4861. } else {
  4862. const err = await res.json();
  4863. showToast('Error', err.message || 'Failed to save address list', 'error');
  4864. }
  4865. } catch (err) {
  4866. showToast('Error', err.message, 'error');
  4867. }
  4868. }
  4869. async function toggleAddrListState(id, disabled) {
  4870. try {
  4871. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  4872. method: 'POST',
  4873. headers: { 'Content-Type': 'application/json' },
  4874. body: JSON.stringify({ disabled })
  4875. });
  4876. if (res.ok) {
  4877. loadFirewall(false);
  4878. }
  4879. } catch (err) {
  4880. showToast('Error', err.message, 'error');
  4881. }
  4882. }
  4883. async function deleteAddrList(id) {
  4884. if (!confirm('Are you sure you want to delete this address list item?')) return;
  4885. try {
  4886. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4887. if (res.ok) {
  4888. showToast('Deleted', 'Address list item removed', 'info');
  4889. loadFirewall(false);
  4890. }
  4891. } catch (err) {
  4892. showToast('Error', err.message, 'error');
  4893. }
  4894. }
  4895. // ----------------- Geo-Location IP Management -----------------
  4896. async function loadGeoIP() {
  4897. try {
  4898. const [statusRes, countriesRes] = await Promise.all([
  4899. fetch(`${API_BASE}/firewall/geoip/status`),
  4900. fetch(`${API_BASE}/firewall/geoip/countries`)
  4901. ]);
  4902. if (statusRes.ok) state.geoStatus = await statusRes.json();
  4903. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  4904. updateGeoHeader();
  4905. renderGeoCountries();
  4906. } catch (err) {
  4907. console.error('Failed to load GeoIP:', err);
  4908. }
  4909. }
  4910. function getGeoUsageMap() {
  4911. const usage = {};
  4912. const checkRule = (r, type) => {
  4913. ['src_geoip', 'dst_geoip'].forEach(field => {
  4914. let val = (r && r[field]) || '';
  4915. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  4916. if (code) {
  4917. if (!usage[code]) usage[code] = [];
  4918. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  4919. if (!usage[code].includes(label)) usage[code].push(label);
  4920. }
  4921. });
  4922. };
  4923. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  4924. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  4925. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  4926. return usage;
  4927. }
  4928. function updateGeoHeader() {
  4929. const s = state.geoStatus || {};
  4930. const statusBadge = document.getElementById('geo-status-badge');
  4931. if (statusBadge) {
  4932. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  4933. statusBadge.className = s.auto_update
  4934. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  4935. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  4936. }
  4937. const intervalLabel = document.getElementById('geo-interval-label');
  4938. if (intervalLabel) {
  4939. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  4940. }
  4941. const usageMap = getGeoUsageMap();
  4942. const inUseCount = Object.keys(usageMap).length;
  4943. const activeCountEl = document.getElementById('geo-stat-active-countries');
  4944. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  4945. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  4946. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  4947. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  4948. if (lastSyncEl) {
  4949. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  4950. const d = new Date(s.last_updated);
  4951. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4952. } else {
  4953. lastSyncEl.innerText = 'Never (Sync Pending)';
  4954. }
  4955. }
  4956. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  4957. if (nextSyncEl) {
  4958. if (s.next_update && !s.next_update.startsWith('0001')) {
  4959. const d = new Date(s.next_update);
  4960. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4961. } else {
  4962. nextSyncEl.innerText = '-';
  4963. }
  4964. }
  4965. const badge = document.getElementById('fw-badge-geo');
  4966. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  4967. }
  4968. function renderGeoCountries() {
  4969. const tbody = document.getElementById('geo-table-body');
  4970. const empty = document.getElementById('geo-empty');
  4971. if (!tbody) return;
  4972. tbody.innerHTML = '';
  4973. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  4974. const continent = document.getElementById('geo-continent-filter')?.value || '';
  4975. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  4976. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  4977. const usageMap = getGeoUsageMap();
  4978. const countries = (state.geoCountries || []).filter(c => {
  4979. const isUsed = !!usageMap[c.code];
  4980. if (inUseOnly && !isUsed) return false;
  4981. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  4982. if (continent && c.continent !== continent) return false;
  4983. if (q) {
  4984. const matchCode = c.code.toLowerCase().includes(q);
  4985. const matchName = c.name.toLowerCase().includes(q);
  4986. if (!matchCode && !matchName) return false;
  4987. }
  4988. return true;
  4989. });
  4990. if (countries.length === 0) {
  4991. empty?.classList.remove('hidden');
  4992. return;
  4993. }
  4994. empty?.classList.add('hidden');
  4995. countries.forEach(c => {
  4996. const tr = document.createElement('tr');
  4997. const isUsed = !!usageMap[c.code];
  4998. const rulesUsing = usageMap[c.code] || [];
  4999. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  5000. let statusHtml = '';
  5001. if (isUsed) {
  5002. 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>`;
  5003. } else if (c.subnet_count > 0) {
  5004. 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>';
  5005. } else {
  5006. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  5007. }
  5008. tr.innerHTML = `
  5009. <td class="py-2.5 px-3 text-center">
  5010. <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'}">
  5011. ${c.code}
  5012. </span>
  5013. </td>
  5014. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  5015. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  5016. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  5017. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  5018. </td>
  5019. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  5020. <td class="py-2.5 px-3">
  5021. ${statusHtml}
  5022. </td>
  5023. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5024. <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>
  5025. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  5026. </td>
  5027. `;
  5028. tbody.appendChild(tr);
  5029. });
  5030. }
  5031. function quickFilterGeo(preset) {
  5032. const searchInput = document.getElementById('geo-search-input');
  5033. const continentSel = document.getElementById('geo-continent-filter');
  5034. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  5035. const cachedCheck = document.getElementById('geo-filter-cached-only');
  5036. if (searchInput) searchInput.value = '';
  5037. if (continentSel) continentSel.value = '';
  5038. if (inUseCheck) inUseCheck.checked = false;
  5039. if (cachedCheck) cachedCheck.checked = false;
  5040. if (preset === 'GR') {
  5041. if (searchInput) searchInput.value = 'Greece';
  5042. } else if (preset === 'Europe') {
  5043. if (continentSel) continentSel.value = 'Europe';
  5044. } else if (preset === 'HIGHRISK') {
  5045. if (searchInput) searchInput.value = 'China';
  5046. }
  5047. renderGeoCountries();
  5048. }
  5049. async function toggleGeoCountry(code, enabled) {
  5050. try {
  5051. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  5052. method: 'POST',
  5053. headers: { 'Content-Type': 'application/json' },
  5054. body: JSON.stringify({ enabled })
  5055. });
  5056. if (res.ok) {
  5057. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  5058. loadGeoIP();
  5059. } else {
  5060. const err = await res.json();
  5061. showToast('Error', err.message || 'Failed to toggle country', 'error');
  5062. }
  5063. } catch (err) {
  5064. showToast('Error', err.message, 'error');
  5065. }
  5066. }
  5067. async function updateGeoCountry(code) {
  5068. try {
  5069. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  5070. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  5071. if (res.ok) {
  5072. const data = await res.json();
  5073. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  5074. loadGeoIP();
  5075. } else {
  5076. const err = await res.json();
  5077. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  5078. }
  5079. } catch (err) {
  5080. showToast('Error', err.message, 'error');
  5081. }
  5082. }
  5083. async function triggerGeoUpdateNow() {
  5084. const spinner = document.getElementById('geo-update-spinner');
  5085. if (spinner) spinner.classList.remove('hidden');
  5086. try {
  5087. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  5088. if (res.ok) {
  5089. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  5090. setTimeout(() => {
  5091. loadGeoIP();
  5092. if (spinner) spinner.classList.add('hidden');
  5093. }, 2500);
  5094. } else {
  5095. const err = await res.json();
  5096. showToast('Notice', err.message || 'Update in progress', 'info');
  5097. if (spinner) spinner.classList.add('hidden');
  5098. }
  5099. } catch (err) {
  5100. showToast('Error', err.message, 'error');
  5101. if (spinner) spinner.classList.add('hidden');
  5102. }
  5103. }
  5104. async function applyGeoPreset(preset) {
  5105. try {
  5106. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  5107. method: 'POST',
  5108. headers: { 'Content-Type': 'application/json' },
  5109. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  5110. });
  5111. if (res.ok) {
  5112. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  5113. loadGeoIP();
  5114. }
  5115. } catch (err) {
  5116. showToast('Error', err.message, 'error');
  5117. }
  5118. }
  5119. function openGeoIntervalModal() {
  5120. const s = state.geoStatus || {};
  5121. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  5122. const sel = document.getElementById('geo-cfg-interval');
  5123. const customBox = document.getElementById('geo-cfg-custom-box');
  5124. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  5125. const curHours = s.interval_hours || 24;
  5126. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  5127. if (matchOption) {
  5128. sel.value = String(curHours);
  5129. customBox.classList.add('hidden');
  5130. } else {
  5131. sel.value = 'custom';
  5132. customHoursInput.value = curHours;
  5133. customBox.classList.remove('hidden');
  5134. }
  5135. document.getElementById('geo-interval-modal').classList.remove('hidden');
  5136. }
  5137. function closeGeoIntervalModal() {
  5138. document.getElementById('geo-interval-modal').classList.add('hidden');
  5139. }
  5140. function toggleCustomGeoInterval() {
  5141. const val = document.getElementById('geo-cfg-interval').value;
  5142. const customBox = document.getElementById('geo-cfg-custom-box');
  5143. if (val === 'custom') {
  5144. customBox.classList.remove('hidden');
  5145. } else {
  5146. customBox.classList.add('hidden');
  5147. }
  5148. }
  5149. async function submitGeoIntervalSettings(e) {
  5150. e.preventDefault();
  5151. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5152. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5153. let hours = 24;
  5154. if (intervalVal === 'custom') {
  5155. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5156. } else {
  5157. hours = parseInt(intervalVal, 10) || 24;
  5158. }
  5159. try {
  5160. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5161. method: 'POST',
  5162. headers: { 'Content-Type': 'application/json' },
  5163. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5164. });
  5165. if (res.ok) {
  5166. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5167. closeGeoIntervalModal();
  5168. loadGeoIP();
  5169. } else {
  5170. const err = await res.json();
  5171. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5172. }
  5173. } catch (err) {
  5174. showToast('Error', err.message, 'error');
  5175. }
  5176. }
  5177. async function viewGeoSubnets(code, name) {
  5178. if (!name) {
  5179. const found = (state.geoCountries || []).find(x => x.code === code);
  5180. name = found ? found.name : code;
  5181. }
  5182. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5183. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5184. const listEl = document.getElementById('geo-subnets-list');
  5185. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5186. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5187. try {
  5188. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5189. if (res.ok) {
  5190. const data = await res.json();
  5191. const subnets = data.subnets || [];
  5192. if (subnets.length === 0) {
  5193. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5194. } else {
  5195. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5196. }
  5197. } else {
  5198. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5199. }
  5200. } catch (err) {
  5201. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5202. }
  5203. }
  5204. function closeGeoSubnetsModal() {
  5205. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5206. }
  5207. // ----------------- Active Connections Tracking -----------------
  5208. async function loadConnections() {
  5209. try {
  5210. const res = await fetch(`${API_BASE}/firewall/connections`);
  5211. const data = await res.json();
  5212. state.connections = Array.isArray(data) ? data : [];
  5213. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5214. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5215. renderConnections();
  5216. } catch (err) {
  5217. console.error('Failed to load connections:', err);
  5218. }
  5219. }
  5220. function renderConnections() {
  5221. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  5222. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  5223. const tbody = document.getElementById('conns-table-body');
  5224. const empty = document.getElementById('conns-empty');
  5225. if (!tbody) return;
  5226. tbody.innerHTML = '';
  5227. const conns = (state.connections || []).filter(c => {
  5228. if (protoFilter && c.protocol !== protoFilter) return false;
  5229. if (search) {
  5230. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  5231. if (!line.includes(search)) return false;
  5232. }
  5233. return true;
  5234. });
  5235. if (conns.length === 0) {
  5236. empty?.classList.remove('hidden');
  5237. return;
  5238. }
  5239. empty?.classList.add('hidden');
  5240. conns.slice(0, 150).forEach(c => {
  5241. const tr = document.createElement('tr');
  5242. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5243. let stateColor = 'text-slate-400';
  5244. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  5245. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  5246. tr.innerHTML = `
  5247. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  5248. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  5249. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  5250. <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>
  5251. <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>
  5252. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  5253. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  5254. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  5255. <td class="py-2.5 px-3 text-right font-sans">
  5256. <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>
  5257. </td>
  5258. `;
  5259. tbody.appendChild(tr);
  5260. });
  5261. }
  5262. async function killConnection(protocol, src, sport, dst, dport) {
  5263. try {
  5264. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  5265. method: 'POST',
  5266. headers: { 'Content-Type': 'application/json' },
  5267. body: JSON.stringify({ protocol, src, sport, dst, dport })
  5268. });
  5269. if (res.ok) {
  5270. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  5271. loadConnections();
  5272. }
  5273. } catch (err) {
  5274. showToast('Error', err.message, 'error');
  5275. }
  5276. }
  5277. async function resetFirewallCounters() {
  5278. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  5279. try {
  5280. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  5281. if (res.ok) {
  5282. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  5283. loadFirewall(false);
  5284. }
  5285. } catch (err) {
  5286. showToast('Error', err.message, 'error');
  5287. }
  5288. }
  5289. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  5290. function switchRoutesSubTab(tab) {
  5291. state.routesSubTab = tab;
  5292. const tabs = ['routes', 'rules', 'tables'];
  5293. tabs.forEach(t => {
  5294. const panel = document.getElementById(`routes-subtab-${t}`);
  5295. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  5296. if (panel) {
  5297. if (t === tab) panel.classList.remove('hidden');
  5298. else panel.classList.add('hidden');
  5299. }
  5300. if (btn) {
  5301. if (t === tab) {
  5302. 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';
  5303. } else {
  5304. 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';
  5305. }
  5306. }
  5307. });
  5308. setTimeout(initTableSorting, 50);
  5309. }
  5310. async function loadRoutes() {
  5311. try {
  5312. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  5313. fetch(`${API_BASE}/routes`),
  5314. fetch(`${API_BASE}/routing/rules`),
  5315. fetch(`${API_BASE}/routing/tables`)
  5316. ]);
  5317. if (routesRes.ok) state.routes = await routesRes.json();
  5318. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  5319. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  5320. const bRoutes = document.getElementById('routes-badge-routes');
  5321. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  5322. const showSystem = document.getElementById('prule-show-system')?.checked;
  5323. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5324. const bRules = document.getElementById('routes-badge-rules');
  5325. if (bRules) bRules.innerText = userRules.length;
  5326. const bTables = document.getElementById('routes-badge-tables');
  5327. if (bTables) bTables.innerText = (state.routingTables || []).length;
  5328. const bRoutesCount = document.getElementById('badge-routes-count');
  5329. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  5330. renderRoutesList();
  5331. renderPolicyRules();
  5332. renderRoutingTables();
  5333. } catch (err) {
  5334. console.error('Failed to load routing:', err);
  5335. }
  5336. }
  5337. function renderRoutesList() {
  5338. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  5339. const tbody = document.getElementById('routes-table-body');
  5340. const empty = document.getElementById('routes-empty');
  5341. if (!tbody) return;
  5342. tbody.innerHTML = '';
  5343. // Update table filter select
  5344. const sel = document.getElementById('routes-filter-table');
  5345. if (sel) {
  5346. const cur = sel.value;
  5347. sel.innerHTML = '<option value="">All Tables</option>';
  5348. (state.routingTables || []).forEach(t => {
  5349. const opt = document.createElement('option');
  5350. opt.value = t.name;
  5351. opt.innerText = t.name;
  5352. if (t.name === cur) opt.selected = true;
  5353. sel.appendChild(opt);
  5354. });
  5355. }
  5356. const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
  5357. document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
  5358. if (routes.length === 0) {
  5359. empty?.classList.remove('hidden');
  5360. return;
  5361. }
  5362. empty?.classList.add('hidden');
  5363. routes.forEach(r => {
  5364. const tr = document.createElement('tr');
  5365. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  5366. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  5367. // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
  5368. let flags = '';
  5369. if (r.dynamic) flags += 'D';
  5370. if (r.active) flags += 'A';
  5371. if (r.connect) flags += 'C';
  5372. if (r.static) flags += 'S';
  5373. if (r.disabled) flags += 'X';
  5374. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  5375. tr.innerHTML = `
  5376. <td class="py-2.5 px-3 text-center">
  5377. <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'}">
  5378. ${flags || '-'}
  5379. </span>
  5380. </td>
  5381. <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
  5382. <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>
  5383. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  5384. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  5385. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  5386. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  5387. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5388. ${r.static ? `
  5389. <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>
  5390. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  5391. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5392. ` : `
  5393. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  5394. `}
  5395. </td>
  5396. `;
  5397. tbody.appendChild(tr);
  5398. });
  5399. }
  5400. function openAddRouteModal() {
  5401. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  5402. document.getElementById('route-modal-id').value = '';
  5403. document.getElementById('route-modal-old-dst').value = '';
  5404. document.getElementById('route-modal-old-gw').value = '';
  5405. document.getElementById('route-modal-old-distance').value = '';
  5406. document.getElementById('route-modal-old-table').value = '';
  5407. document.getElementById('route-modal-old-iface').value = '';
  5408. const dstInput = document.getElementById('route-modal-dst');
  5409. const gwInput = document.getElementById('route-modal-gw');
  5410. const distInput = document.getElementById('route-modal-distance');
  5411. const ifaceSelect = document.getElementById('route-modal-iface');
  5412. const tableSelect = document.getElementById('route-modal-table');
  5413. const commentInput = document.getElementById('route-modal-comment');
  5414. const disCheck = document.getElementById('route-modal-disabled');
  5415. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5416. dstInput.disabled = false;
  5417. dstInput.value = '0.0.0.0/0';
  5418. gwInput.disabled = false;
  5419. gwInput.value = '';
  5420. distInput.disabled = false;
  5421. distInput.value = '1';
  5422. ifaceSelect.disabled = false;
  5423. tableSelect.disabled = false;
  5424. commentInput.disabled = false;
  5425. commentInput.value = '';
  5426. disCheck.disabled = false;
  5427. disCheck.checked = false;
  5428. if (saveBtn) saveBtn.classList.remove('hidden');
  5429. populateInterfaceSelect('route-modal-iface');
  5430. // Populate tables
  5431. tableSelect.innerHTML = '';
  5432. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5433. const opt = document.createElement('option');
  5434. opt.value = t.name;
  5435. opt.innerText = t.name;
  5436. if (t.name === 'main') opt.selected = true;
  5437. tableSelect.appendChild(opt);
  5438. });
  5439. document.getElementById('route-modal').classList.remove('hidden');
  5440. }
  5441. function openEditRouteModal(id) {
  5442. const r = (state.routes || []).find(route => route.id === id);
  5443. if (!r) return;
  5444. const isStatic = !!r.static;
  5445. document.getElementById('route-modal-title').innerText = isStatic
  5446. ? `Edit Route: ${r.dst_address}`
  5447. : `Route Properties (Read Only): ${r.dst_address}`;
  5448. document.getElementById('route-modal-id').value = r.id;
  5449. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  5450. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  5451. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  5452. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  5453. document.getElementById('route-modal-old-iface').value = r.interface || '';
  5454. const dstInput = document.getElementById('route-modal-dst');
  5455. const gwInput = document.getElementById('route-modal-gw');
  5456. const distInput = document.getElementById('route-modal-distance');
  5457. const ifaceSelect = document.getElementById('route-modal-iface');
  5458. const tableSelect = document.getElementById('route-modal-table');
  5459. const commentInput = document.getElementById('route-modal-comment');
  5460. const disCheck = document.getElementById('route-modal-disabled');
  5461. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5462. dstInput.value = r.dst_address;
  5463. gwInput.value = r.gateway || '';
  5464. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  5465. commentInput.value = r.comment || '';
  5466. disCheck.checked = !!r.disabled;
  5467. dstInput.disabled = !isStatic;
  5468. gwInput.disabled = !isStatic;
  5469. distInput.disabled = !isStatic;
  5470. ifaceSelect.disabled = !isStatic;
  5471. tableSelect.disabled = !isStatic;
  5472. commentInput.disabled = !isStatic;
  5473. disCheck.disabled = !isStatic;
  5474. if (saveBtn) {
  5475. if (isStatic) {
  5476. saveBtn.classList.remove('hidden');
  5477. } else {
  5478. saveBtn.classList.add('hidden');
  5479. }
  5480. }
  5481. populateInterfaceSelect('route-modal-iface', r.interface);
  5482. tableSelect.innerHTML = '';
  5483. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5484. const opt = document.createElement('option');
  5485. opt.value = t.name;
  5486. opt.innerText = t.name;
  5487. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  5488. tableSelect.appendChild(opt);
  5489. });
  5490. document.getElementById('route-modal').classList.remove('hidden');
  5491. }
  5492. function closeRouteModal() {
  5493. document.getElementById('route-modal').classList.add('hidden');
  5494. }
  5495. async function submitSaveRoute(e) {
  5496. e.preventDefault();
  5497. const id = document.getElementById('route-modal-id').value;
  5498. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  5499. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  5500. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  5501. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  5502. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  5503. const dst = document.getElementById('route-modal-dst').value.trim();
  5504. const gw = document.getElementById('route-modal-gw').value.trim();
  5505. const table = document.getElementById('route-modal-table').value;
  5506. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  5507. const iface = document.getElementById('route-modal-iface').value;
  5508. const comment = document.getElementById('route-modal-comment').value.trim();
  5509. const disabled = document.getElementById('route-modal-disabled').checked;
  5510. if (!dst) {
  5511. showToast('Error', 'Destination address is required', 'error');
  5512. return;
  5513. }
  5514. if (!gw && !iface) {
  5515. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  5516. return;
  5517. }
  5518. const payload = {
  5519. id,
  5520. old_dst_address: oldDst,
  5521. old_gateway: oldGw,
  5522. old_routing_table: oldTable,
  5523. old_interface: oldIface,
  5524. dst_address: dst,
  5525. gateway: gw || iface,
  5526. routing_table: table,
  5527. distance,
  5528. interface: iface,
  5529. comment,
  5530. disabled
  5531. };
  5532. if (oldDistStr !== undefined && oldDistStr !== '') {
  5533. payload.old_distance = parseInt(oldDistStr, 10);
  5534. }
  5535. try {
  5536. const res = await fetch(`${API_BASE}/routes`, {
  5537. method: 'POST',
  5538. headers: { 'Content-Type': 'application/json' },
  5539. body: JSON.stringify(payload)
  5540. });
  5541. if (res.ok) {
  5542. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  5543. closeRouteModal();
  5544. loadRoutes();
  5545. } else {
  5546. const err = await res.json();
  5547. showToast('Error', err.message || 'Failed to save route', 'error');
  5548. }
  5549. } catch (err) {
  5550. showToast('Error', err.message, 'error');
  5551. }
  5552. }
  5553. async function toggleRouteState(id, disabled) {
  5554. try {
  5555. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  5556. method: 'POST',
  5557. headers: { 'Content-Type': 'application/json' },
  5558. body: JSON.stringify({ disabled })
  5559. });
  5560. if (res.ok) loadRoutes();
  5561. } catch (err) {
  5562. showToast('Error', err.message, 'error');
  5563. }
  5564. }
  5565. async function deleteRoute(id) {
  5566. if (!confirm('Are you sure you want to delete this route?')) return;
  5567. try {
  5568. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5569. if (res.ok) {
  5570. showToast('Deleted', 'Route removed', 'success');
  5571. loadRoutes();
  5572. }
  5573. } catch (err) {
  5574. showToast('Error', err.message, 'error');
  5575. }
  5576. }
  5577. // ----------------- Policy Rules (/ip route rule) -----------------
  5578. function renderPolicyRules() {
  5579. const tbody = document.getElementById('rules-table-body');
  5580. const empty = document.getElementById('rules-empty');
  5581. if (!tbody) return;
  5582. tbody.innerHTML = '';
  5583. const showSystem = document.getElementById('prule-show-system')?.checked;
  5584. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5585. const countBadge = document.getElementById('rules-count-badge');
  5586. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  5587. const bRules = document.getElementById('routes-badge-rules');
  5588. if (bRules) bRules.innerText = filtered.length;
  5589. if (filtered.length === 0) {
  5590. empty?.classList.remove('hidden');
  5591. return;
  5592. }
  5593. empty?.classList.add('hidden');
  5594. filtered.forEach(pr => {
  5595. const isSys = pr.is_default || pr.is_system;
  5596. const tr = document.createElement('tr');
  5597. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  5598. tr.innerHTML = `
  5599. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  5600. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  5601. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  5602. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  5603. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  5604. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  5605. <td class="py-2.5 px-3 text-right font-sans">
  5606. ${!pr.is_default ? `
  5607. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5608. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  5609. </td>
  5610. `;
  5611. tbody.appendChild(tr);
  5612. });
  5613. }
  5614. function openAddPolicyRuleModal() {
  5615. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  5616. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  5617. document.getElementById('prule-modal-mark').value = '';
  5618. document.getElementById('prule-modal-src').value = '';
  5619. document.getElementById('prule-modal-dst').value = '';
  5620. const sel = document.getElementById('prule-modal-table');
  5621. sel.innerHTML = '';
  5622. (state.routingTables || []).forEach(t => {
  5623. const opt = document.createElement('option');
  5624. opt.value = t.name;
  5625. opt.innerText = t.name;
  5626. sel.appendChild(opt);
  5627. });
  5628. document.getElementById('prule-modal').classList.remove('hidden');
  5629. }
  5630. function closePolicyRuleModal() {
  5631. document.getElementById('prule-modal').classList.add('hidden');
  5632. }
  5633. async function submitSavePolicyRule(e) {
  5634. e.preventDefault();
  5635. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  5636. const mark = document.getElementById('prule-modal-mark').value.trim();
  5637. const src = document.getElementById('prule-modal-src').value.trim();
  5638. const dst = document.getElementById('prule-modal-dst').value.trim();
  5639. const table = document.getElementById('prule-modal-table').value;
  5640. const action = document.getElementById('prule-modal-action').value;
  5641. try {
  5642. const res = await fetch(`${API_BASE}/routing/rules`, {
  5643. method: 'POST',
  5644. headers: { 'Content-Type': 'application/json' },
  5645. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  5646. });
  5647. if (res.ok) {
  5648. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  5649. closePolicyRuleModal();
  5650. loadRoutes();
  5651. } else {
  5652. const err = await res.json();
  5653. showToast('Error', err.message, 'error');
  5654. }
  5655. } catch (err) {
  5656. showToast('Error', err.message, 'error');
  5657. }
  5658. }
  5659. async function deletePolicyRule(id) {
  5660. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  5661. try {
  5662. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5663. if (res.ok) {
  5664. showToast('Rule Removed', 'Policy rule deleted', 'success');
  5665. loadRoutes();
  5666. }
  5667. } catch (err) {
  5668. showToast('Error', err.message, 'error');
  5669. }
  5670. }
  5671. // ----------------- Routing Tables -----------------
  5672. function renderRoutingTables() {
  5673. const tbody = document.getElementById('tables-table-body');
  5674. if (!tbody) return;
  5675. tbody.innerHTML = '';
  5676. (state.routingTables || []).forEach(t => {
  5677. const tr = document.createElement('tr');
  5678. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5679. tr.innerHTML = `
  5680. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  5681. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  5682. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  5683. `;
  5684. tbody.appendChild(tr);
  5685. });
  5686. }
  5687. function openAddTableModal() {
  5688. document.getElementById('table-modal-name').value = '';
  5689. document.getElementById('table-modal-id').value = '';
  5690. document.getElementById('table-modal-comment').value = '';
  5691. document.getElementById('table-modal').classList.remove('hidden');
  5692. }
  5693. function closeTableModal() {
  5694. document.getElementById('table-modal').classList.add('hidden');
  5695. }
  5696. async function submitSaveTable(e) {
  5697. e.preventDefault();
  5698. const name = document.getElementById('table-modal-name').value.trim();
  5699. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  5700. const comment = document.getElementById('table-modal-comment').value.trim();
  5701. try {
  5702. const res = await fetch(`${API_BASE}/routing/tables`, {
  5703. method: 'POST',
  5704. headers: { 'Content-Type': 'application/json' },
  5705. body: JSON.stringify({ name, table_id: id, comment })
  5706. });
  5707. if (res.ok) {
  5708. showToast('Table Created', `Routing table ${name} registered`, 'success');
  5709. closeTableModal();
  5710. loadRoutes();
  5711. } else {
  5712. const err = await res.json();
  5713. showToast('Error', err.message, 'error');
  5714. }
  5715. } catch (err) {
  5716. showToast('Error', err.message, 'error');
  5717. }
  5718. }
  5719. async function loadDebianConfig() {
  5720. const view = document.getElementById('debian-config-view');
  5721. view.innerText = 'Generating live configuration...';
  5722. try {
  5723. const res = await fetch(`${API_BASE}/debian/config`);
  5724. const data = await res.json();
  5725. view.innerText = data.content || '# Empty config';
  5726. } catch (err) {
  5727. view.innerText = 'Failed to generate Debian network config.';
  5728. }
  5729. }
  5730. async function saveDebianConfig() {
  5731. try {
  5732. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  5733. const data = await res.json();
  5734. if (res.ok) {
  5735. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  5736. loadDebianConfig();
  5737. }
  5738. } catch (err) {
  5739. showToast('Error', err.message, 'error');
  5740. }
  5741. }
  5742. function showToast(title, message, type = 'info') {
  5743. const container = document.getElementById('toast-container');
  5744. const toast = document.createElement('div');
  5745. const borderColors = {
  5746. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  5747. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  5748. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  5749. };
  5750. 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}`;
  5751. toast.innerHTML = `
  5752. <div class="flex-1">
  5753. <div class="font-bold text-xs text-white">${title}</div>
  5754. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  5755. </div>
  5756. `;
  5757. container.appendChild(toast);
  5758. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  5759. setTimeout(() => {
  5760. toast.classList.add('opacity-0', 'translate-y-2');
  5761. setTimeout(() => toast.remove(), 300);
  5762. }, 4000);
  5763. }
  5764. function formatTraffic(bytesPerSec) {
  5765. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  5766. const kb = bytesPerSec / 1024;
  5767. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  5768. const mb = kb / 1024;
  5769. return `${mb.toFixed(2)} MB/s`;
  5770. }
  5771. function toggleSidebar() {
  5772. const sb = document.getElementById('sidebar');
  5773. sb.classList.toggle('-translate-x-full');
  5774. }
  5775. // ======================== EoIP (Ethernet over IP) ========================
  5776. async function loadEoIP(populate = true) {
  5777. try {
  5778. const res = await fetch(`${API_BASE}/vpn/eoip`);
  5779. const data = await res.json();
  5780. state.eoipTunnels = Array.isArray(data) ? data : [];
  5781. const badge = document.getElementById('eoip-count-badge');
  5782. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  5783. const sideBadge = document.getElementById('badge-eoip-count');
  5784. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  5785. renderEoIPTunnels();
  5786. } catch (err) {
  5787. console.error('Failed to load EoIP:', err);
  5788. }
  5789. }
  5790. function renderEoIPTunnels() {
  5791. const tbody = document.getElementById('eoip-table-body');
  5792. const empty = document.getElementById('eoip-empty');
  5793. if (!tbody) return;
  5794. tbody.innerHTML = '';
  5795. const tunnels = state.eoipTunnels || [];
  5796. if (tunnels.length === 0) {
  5797. empty?.classList.remove('hidden');
  5798. return;
  5799. }
  5800. empty?.classList.add('hidden');
  5801. tunnels.forEach(t => {
  5802. const tr = document.createElement('tr');
  5803. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  5804. tr.innerHTML = `
  5805. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  5806. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  5807. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  5808. <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>
  5809. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  5810. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  5811. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  5812. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  5813. <td class="py-2.5 px-3 font-mono text-[11px]">
  5814. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  5815. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  5816. </td>
  5817. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  5818. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5819. <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>
  5820. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5821. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  5822. </td>
  5823. `;
  5824. tbody.appendChild(tr);
  5825. });
  5826. }
  5827. function openAddEoIPModal() {
  5828. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  5829. document.getElementById('eoip-modal-id').value = '';
  5830. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  5831. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  5832. document.getElementById('eoip-modal-remote').value = '';
  5833. document.getElementById('eoip-modal-ip').value = '';
  5834. document.getElementById('eoip-modal-local').value = '';
  5835. document.getElementById('eoip-modal-mac').value = '';
  5836. document.getElementById('eoip-modal-mtu').value = '1500';
  5837. document.getElementById('eoip-modal-comment').value = '';
  5838. document.getElementById('eoip-modal-clampmss').checked = true;
  5839. document.getElementById('eoip-modal-disabled').checked = false;
  5840. document.getElementById('eoip-modal').classList.remove('hidden');
  5841. }
  5842. function openEditEoIPModal(id) {
  5843. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  5844. if (!t) return;
  5845. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  5846. document.getElementById('eoip-modal-id').value = t.id;
  5847. document.getElementById('eoip-modal-name').value = t.name;
  5848. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  5849. document.getElementById('eoip-modal-remote').value = t.remote_address;
  5850. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  5851. document.getElementById('eoip-modal-local').value = t.local_address || '';
  5852. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  5853. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  5854. document.getElementById('eoip-modal-comment').value = t.comment || '';
  5855. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  5856. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  5857. document.getElementById('eoip-modal').classList.remove('hidden');
  5858. }
  5859. function closeEoIPModal() {
  5860. document.getElementById('eoip-modal').classList.add('hidden');
  5861. }
  5862. async function submitSaveEoIP(e) {
  5863. e.preventDefault();
  5864. const id = document.getElementById('eoip-modal-id').value;
  5865. const name = document.getElementById('eoip-modal-name').value.trim();
  5866. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  5867. const remote = document.getElementById('eoip-modal-remote').value.trim();
  5868. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  5869. const local = document.getElementById('eoip-modal-local').value.trim();
  5870. const mac = document.getElementById('eoip-modal-mac').value.trim();
  5871. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  5872. const comment = document.getElementById('eoip-modal-comment').value.trim();
  5873. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  5874. const disabled = document.getElementById('eoip-modal-disabled').checked;
  5875. try {
  5876. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  5877. method: 'POST',
  5878. headers: { 'Content-Type': 'application/json' },
  5879. body: JSON.stringify({
  5880. id,
  5881. name,
  5882. tunnel_id: tunnelId,
  5883. remote_address: remote,
  5884. ip_address: ipAddress,
  5885. local_address: local,
  5886. mac_address: mac,
  5887. mtu,
  5888. clamp_mss: clampMss,
  5889. comment,
  5890. disabled
  5891. })
  5892. });
  5893. if (res.ok) {
  5894. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  5895. closeEoIPModal();
  5896. loadEoIP(false);
  5897. fetchData(false);
  5898. } else {
  5899. const err = await res.json();
  5900. showToast('Error', err.message, 'error');
  5901. }
  5902. } catch (err) {
  5903. showToast('Error', err.message, 'error');
  5904. }
  5905. }
  5906. async function toggleEoIPState(id, disabled) {
  5907. try {
  5908. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  5909. method: 'POST',
  5910. headers: { 'Content-Type': 'application/json' },
  5911. body: JSON.stringify({ disabled })
  5912. });
  5913. if (res.ok) {
  5914. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  5915. loadEoIP(false);
  5916. fetchData(false);
  5917. }
  5918. } catch (err) {
  5919. showToast('Error', err.message, 'error');
  5920. }
  5921. }
  5922. async function deleteEoIP(id) {
  5923. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  5924. try {
  5925. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5926. if (res.ok) {
  5927. showToast('Deleted', 'EoIP tunnel removed', 'success');
  5928. loadEoIP(false);
  5929. fetchData(false);
  5930. }
  5931. } catch (err) {
  5932. showToast('Error', err.message, 'error');
  5933. }
  5934. }
  5935. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  5936. async function loadAeroTUN(populate = true) {
  5937. try {
  5938. const [tunnelsRes, statsRes] = await Promise.all([
  5939. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  5940. fetch(`${API_BASE}/vpn/aerotun/stats`)
  5941. ]);
  5942. if (tunnelsRes.ok) {
  5943. const data = await tunnelsRes.json();
  5944. state.aerotunTunnels = Array.isArray(data) ? data : [];
  5945. }
  5946. if (statsRes.ok) {
  5947. state.aerotunStats = await statsRes.json();
  5948. }
  5949. const countBadge = document.getElementById('aerotun-count-badge');
  5950. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  5951. const sideBadge = document.getElementById('badge-aerotun-count');
  5952. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  5953. renderAeroTUN();
  5954. } catch (err) {
  5955. console.error('Failed to load AeroTUN:', err);
  5956. }
  5957. }
  5958. function renderAeroTUN() {
  5959. const tbody = document.getElementById('aerotun-table-body');
  5960. const empty = document.getElementById('aerotun-empty');
  5961. // Update summary cards
  5962. const stats = state.aerotunStats || {};
  5963. const tunnels = state.aerotunTunnels || [];
  5964. const statActive = document.getElementById('aerotun-stat-active');
  5965. if (statActive) {
  5966. const activeCount = tunnels.filter(t => t.running).length;
  5967. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  5968. }
  5969. const statSaved = document.getElementById('aerotun-stat-saved');
  5970. if (statSaved) {
  5971. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  5972. }
  5973. const statRatio = document.getElementById('aerotun-stat-ratio');
  5974. if (statRatio) {
  5975. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  5976. }
  5977. const statTraffic = document.getElementById('aerotun-stat-traffic');
  5978. if (statTraffic) {
  5979. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  5980. }
  5981. if (!tbody) return;
  5982. tbody.innerHTML = '';
  5983. if (tunnels.length === 0) {
  5984. empty?.classList.remove('hidden');
  5985. return;
  5986. }
  5987. empty?.classList.add('hidden');
  5988. tunnels.forEach(t => {
  5989. const tr = document.createElement('tr');
  5990. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  5991. const modeBadge = t.mode === 'server'
  5992. ? `<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>`
  5993. : `<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>`;
  5994. const endpointInfo = t.mode === 'server'
  5995. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  5996. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  5997. const compBadge = t.compression
  5998. ? `<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>`
  5999. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  6000. const activePeer = t.active_peer_endpoint
  6001. ? `<span class="text-emerald-400 font-mono text-[11px]" title="Last seen: ${t.last_handshake || 'just now'}">● ${escapeHtml(t.active_peer_endpoint)}</span>`
  6002. : `<span class="text-slate-500 text-[11px]">${t.mode === 'server' ? 'Waiting for peer...' : 'Connecting...'}</span>`;
  6003. const rawRx = formatBytes(t.rx_bytes || 0);
  6004. const rawTx = formatBytes(t.tx_bytes || 0);
  6005. const wireRx = formatBytes(t.wire_bytes_in || 0);
  6006. const wireTx = formatBytes(t.wire_bytes_out || 0);
  6007. tr.innerHTML = `
  6008. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6009. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  6010. <span>${escapeHtml(t.name)}</span>
  6011. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  6012. </td>
  6013. <td class="py-2.5 px-3">${modeBadge}</td>
  6014. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  6015. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  6016. <td class="py-2.5 px-3">${compBadge}</td>
  6017. <td class="py-2.5 px-3">${activePeer}</td>
  6018. <td class="py-2.5 px-3 font-mono text-[11px]">
  6019. <span class="text-emerald-400">↓ ${rawRx}</span>
  6020. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  6021. </td>
  6022. <td class="py-2.5 px-3 font-mono text-[11px]">
  6023. <span class="text-slate-400">↓ ${wireRx}</span>
  6024. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  6025. </td>
  6026. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  6027. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6028. ${t.running
  6029. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  6030. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  6031. }
  6032. <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>
  6033. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6034. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6035. </td>
  6036. `;
  6037. tbody.appendChild(tr);
  6038. });
  6039. }
  6040. function onAeroTUNModeChange() {
  6041. const mode = document.getElementById('aerotun-modal-mode').value;
  6042. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  6043. const portInput = document.getElementById('aerotun-modal-port');
  6044. if (mode === 'server') {
  6045. if (!portInput.value) portInput.value = '51830';
  6046. endpointInput.placeholder = 'Optional / learned roaming peer';
  6047. } else {
  6048. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  6049. if (!portInput.value) portInput.value = '';
  6050. }
  6051. }
  6052. async function generateAeroTUNKey() {
  6053. try {
  6054. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  6055. if (res.ok) {
  6056. const data = await res.json();
  6057. document.getElementById('aerotun-modal-psk').value = data.key;
  6058. showToast('Key Generated', 'Cryptographic 256-bit PSK generated', 'success');
  6059. }
  6060. } catch (err) {
  6061. const arr = new Uint8Array(32);
  6062. crypto.getRandomValues(arr);
  6063. const hex = Array.from(arr).map(b => b.toString(16).padStart(2, '0')).join('');
  6064. document.getElementById('aerotun-modal-psk').value = hex;
  6065. }
  6066. }
  6067. function openAddAeroTUNModal() {
  6068. const tunnels = state.aerotunTunnels || [];
  6069. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  6070. document.getElementById('aerotun-modal-id').value = '';
  6071. document.getElementById('aerotun-modal-name').value = `aerotun${tunnels.length}`;
  6072. document.getElementById('aerotun-modal-mode').value = 'server';
  6073. document.getElementById('aerotun-modal-port').value = 51830 + tunnels.length;
  6074. document.getElementById('aerotun-modal-endpoint').value = '';
  6075. document.getElementById('aerotun-modal-local').value = `10.99.${tunnels.length}.1/24`;
  6076. document.getElementById('aerotun-modal-peer').value = `10.99.${tunnels.length}.2/24`;
  6077. document.getElementById('aerotun-modal-psk').value = '';
  6078. document.getElementById('aerotun-modal-mtu').value = '1420';
  6079. document.getElementById('aerotun-modal-comment').value = '';
  6080. document.getElementById('aerotun-modal-compression').checked = true;
  6081. document.getElementById('aerotun-modal-defroute').checked = false;
  6082. document.getElementById('aerotun-modal-disabled').checked = false;
  6083. generateAeroTUNKey();
  6084. onAeroTUNModeChange();
  6085. document.getElementById('aerotun-modal').classList.remove('hidden');
  6086. }
  6087. function openEditAeroTUNModal(id) {
  6088. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  6089. if (!t) return;
  6090. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  6091. document.getElementById('aerotun-modal-id').value = t.id;
  6092. document.getElementById('aerotun-modal-name').value = t.name;
  6093. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  6094. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  6095. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  6096. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  6097. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  6098. document.getElementById('aerotun-modal-psk').value = t.psk || '';
  6099. document.getElementById('aerotun-modal-mtu').value = t.mtu || 1420;
  6100. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  6101. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  6102. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  6103. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  6104. onAeroTUNModeChange();
  6105. document.getElementById('aerotun-modal').classList.remove('hidden');
  6106. }
  6107. function closeAeroTUNModal() {
  6108. document.getElementById('aerotun-modal').classList.add('hidden');
  6109. }
  6110. async function submitSaveAeroTUN(e) {
  6111. e.preventDefault();
  6112. const id = document.getElementById('aerotun-modal-id').value;
  6113. const name = document.getElementById('aerotun-modal-name').value.trim();
  6114. const mode = document.getElementById('aerotun-modal-mode').value;
  6115. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  6116. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  6117. const local = document.getElementById('aerotun-modal-local').value.trim();
  6118. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  6119. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  6120. const mtu = parseInt(document.getElementById('aerotun-modal-mtu').value) || 1420;
  6121. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  6122. const compression = document.getElementById('aerotun-modal-compression').checked;
  6123. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  6124. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  6125. if (mode === 'client' && !endpoint) {
  6126. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  6127. return;
  6128. }
  6129. if (!psk) {
  6130. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  6131. return;
  6132. }
  6133. try {
  6134. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  6135. method: 'POST',
  6136. headers: { 'Content-Type': 'application/json' },
  6137. body: JSON.stringify({
  6138. id,
  6139. name,
  6140. mode,
  6141. listen_port: port,
  6142. remote_endpoint: endpoint,
  6143. local_address: local,
  6144. peer_address: peer,
  6145. psk,
  6146. mtu,
  6147. compression,
  6148. default_route: defaultRoute,
  6149. comment,
  6150. disabled
  6151. })
  6152. });
  6153. if (res.ok) {
  6154. showToast('AeroTUN Saved', `Tunnel ${name} configured successfully`, 'success');
  6155. closeAeroTUNModal();
  6156. loadAeroTUN(false);
  6157. fetchData(false);
  6158. } else {
  6159. const err = await res.text();
  6160. showToast('Error Saving Tunnel', err, 'error');
  6161. }
  6162. } catch (err) {
  6163. showToast('Network Error', err.message, 'error');
  6164. }
  6165. }
  6166. async function startAeroTUNTunnel(id) {
  6167. try {
  6168. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  6169. if (res.ok) {
  6170. showToast('AeroTUN Started', 'Tunnel interface is active', 'success');
  6171. loadAeroTUN(false);
  6172. fetchData(false);
  6173. } else {
  6174. const err = await res.text();
  6175. showToast('Failed to Start', err, 'error');
  6176. }
  6177. } catch (err) {
  6178. showToast('Error', err.message, 'error');
  6179. }
  6180. }
  6181. async function stopAeroTUNTunnel(id) {
  6182. try {
  6183. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  6184. if (res.ok) {
  6185. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  6186. loadAeroTUN(false);
  6187. fetchData(false);
  6188. } else {
  6189. const err = await res.text();
  6190. showToast('Failed to Stop', err, 'error');
  6191. }
  6192. } catch (err) {
  6193. showToast('Error', err.message, 'error');
  6194. }
  6195. }
  6196. async function toggleAeroTUNState(id, disabled) {
  6197. try {
  6198. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  6199. method: 'POST',
  6200. headers: { 'Content-Type': 'application/json' },
  6201. body: JSON.stringify({ disabled })
  6202. });
  6203. if (res.ok) {
  6204. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  6205. loadAeroTUN(false);
  6206. fetchData(false);
  6207. }
  6208. } catch (err) {
  6209. showToast('Error', err.message, 'error');
  6210. }
  6211. }
  6212. async function deleteAeroTUN(id) {
  6213. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  6214. try {
  6215. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6216. if (res.ok) {
  6217. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  6218. loadAeroTUN(false);
  6219. fetchData(false);
  6220. }
  6221. } catch (err) {
  6222. showToast('Error', err.message, 'error');
  6223. }
  6224. }
  6225. // ======================== PPP Central Hub & Servers ========================
  6226. function switchPPPSubTab(tab) {
  6227. state.pppSubTab = tab;
  6228. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  6229. tabs.forEach(t => {
  6230. const panel = document.getElementById(`ppp-subtab-${t}`);
  6231. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  6232. if (panel) {
  6233. if (t === tab) panel.classList.remove('hidden');
  6234. else panel.classList.add('hidden');
  6235. }
  6236. if (btn) {
  6237. if (t === tab) {
  6238. 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';
  6239. } else {
  6240. 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';
  6241. }
  6242. }
  6243. });
  6244. const addBtn = document.getElementById('ppp-primary-add-btn');
  6245. if (addBtn) {
  6246. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  6247. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  6248. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  6249. else addBtn.innerHTML = '<span>Save Config</span>';
  6250. }
  6251. if (tab === 'active') loadPPPSessions();
  6252. }
  6253. function openCurrentPPPModal() {
  6254. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  6255. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  6256. else if (state.pppSubTab === 'active') loadPPPSessions();
  6257. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  6258. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  6259. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  6260. }
  6261. async function loadPPP(populateDropdowns = true) {
  6262. await Promise.all([
  6263. loadPPPSecrets(),
  6264. loadPPPProfiles(),
  6265. loadPPPServers(),
  6266. loadPPPSessions()
  6267. ]);
  6268. }
  6269. async function loadPPPSecrets() {
  6270. try {
  6271. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  6272. const data = await res.json();
  6273. state.pppSecrets = Array.isArray(data) ? data : [];
  6274. const b = document.getElementById('ppp-badge-secrets');
  6275. if (b) b.innerText = state.pppSecrets.length;
  6276. const b2 = document.getElementById('secrets-count-badge');
  6277. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  6278. renderPPPSecrets();
  6279. } catch (err) {
  6280. console.error('Failed to load PPP secrets:', err);
  6281. }
  6282. }
  6283. function renderPPPSecrets() {
  6284. const tbody = document.getElementById('secrets-table-body');
  6285. const empty = document.getElementById('secrets-empty');
  6286. if (!tbody) return;
  6287. tbody.innerHTML = '';
  6288. const secrets = state.pppSecrets || [];
  6289. if (secrets.length === 0) {
  6290. empty?.classList.remove('hidden');
  6291. return;
  6292. }
  6293. empty?.classList.add('hidden');
  6294. secrets.forEach(s => {
  6295. const tr = document.createElement('tr');
  6296. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  6297. tr.innerHTML = `
  6298. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  6299. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  6300. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  6301. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  6302. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  6303. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  6304. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  6305. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6306. <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>
  6307. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6308. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6309. </td>
  6310. `;
  6311. tbody.appendChild(tr);
  6312. });
  6313. }
  6314. async function loadPPPProfiles() {
  6315. try {
  6316. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  6317. const data = await res.json();
  6318. state.pppProfiles = Array.isArray(data) ? data : [];
  6319. const b = document.getElementById('ppp-badge-profiles');
  6320. if (b) b.innerText = state.pppProfiles.length;
  6321. const b2 = document.getElementById('profiles-count-badge');
  6322. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  6323. // Populate profile selects across modals
  6324. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  6325. selects.forEach(sid => {
  6326. const el = document.getElementById(sid);
  6327. if (!el) return;
  6328. const cur = el.value;
  6329. el.innerHTML = '';
  6330. state.pppProfiles.forEach(p => {
  6331. const opt = document.createElement('option');
  6332. opt.value = p.name;
  6333. opt.innerText = `${p.name} (${p.remote_address})`;
  6334. if (p.name === cur) opt.selected = true;
  6335. el.appendChild(opt);
  6336. });
  6337. });
  6338. renderPPPProfiles();
  6339. } catch (err) {
  6340. console.error('Failed to load PPP profiles:', err);
  6341. }
  6342. }
  6343. function renderPPPProfiles() {
  6344. const tbody = document.getElementById('profiles-table-body');
  6345. if (!tbody) return;
  6346. tbody.innerHTML = '';
  6347. (state.pppProfiles || []).forEach(p => {
  6348. const isDefault = p.name.startsWith('default');
  6349. const tr = document.createElement('tr');
  6350. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6351. tr.innerHTML = `
  6352. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  6353. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  6354. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  6355. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  6356. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  6357. <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>
  6358. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  6359. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  6360. ${!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>`}
  6361. </td>
  6362. `;
  6363. tbody.appendChild(tr);
  6364. });
  6365. }
  6366. async function loadPPPServers() {
  6367. try {
  6368. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  6369. fetch(`${API_BASE}/vpn/servers/pppoe`),
  6370. fetch(`${API_BASE}/vpn/servers/pptp`),
  6371. fetch(`${API_BASE}/vpn/servers/l2tp`),
  6372. fetch(`${API_BASE}/vpn/servers/ipsec`)
  6373. ]);
  6374. if (pppoeRes.ok) {
  6375. state.pppoeServer = await pppoeRes.json();
  6376. const s = state.pppoeServer;
  6377. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  6378. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  6379. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  6380. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  6381. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  6382. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  6383. const pill = document.getElementById('pppoe-server-status-pill');
  6384. if (pill) {
  6385. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6386. 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';
  6387. }
  6388. setDotBadge('ppp-badge-pppoe-state', s.running);
  6389. }
  6390. if (pptpRes.ok) {
  6391. state.pptpServer = await pptpRes.json();
  6392. const s = state.pptpServer;
  6393. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  6394. document.getElementById('pptp-server-port').value = s.port || 1723;
  6395. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  6396. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  6397. const pill = document.getElementById('pptp-server-status-pill');
  6398. if (pill) {
  6399. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6400. 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';
  6401. }
  6402. setDotBadge('ppp-badge-pptp-state', s.running);
  6403. }
  6404. if (l2tpRes.ok) {
  6405. state.l2tpServer = await l2tpRes.json();
  6406. const s = state.l2tpServer;
  6407. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  6408. document.getElementById('l2tp-server-port').value = s.port || 1701;
  6409. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  6410. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  6411. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  6412. const pill = document.getElementById('l2tp-server-status-pill');
  6413. if (pill) {
  6414. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6415. 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';
  6416. }
  6417. setDotBadge('ppp-badge-l2tp-state', s.running);
  6418. }
  6419. if (ipsecRes.ok) {
  6420. state.ipsecServer = await ipsecRes.json();
  6421. const s = state.ipsecServer;
  6422. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  6423. if (modalEn) modalEn.checked = !!s.enabled;
  6424. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  6425. if (modalPsk) modalPsk.value = s.preshared_key || '';
  6426. const modalPool = document.getElementById('modal-ipsec-server-pool');
  6427. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  6428. const modalDns = document.getElementById('modal-ipsec-server-dns');
  6429. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  6430. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  6431. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  6432. const pill = document.getElementById('modal-ipsec-server-status');
  6433. if (pill) {
  6434. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  6435. 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';
  6436. }
  6437. }
  6438. } catch (err) {
  6439. console.error('Failed to load VPN servers:', err);
  6440. }
  6441. }
  6442. async function loadPPPSessions() {
  6443. try {
  6444. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  6445. const data = await res.json();
  6446. state.pppActiveSessions = Array.isArray(data) ? data : [];
  6447. const b = document.getElementById('ppp-badge-active');
  6448. if (b) b.innerText = state.pppActiveSessions.length;
  6449. const sideB = document.getElementById('badge-ppp-sessions');
  6450. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  6451. renderPPPSessions();
  6452. } catch (err) {
  6453. console.error('Failed to load active PPP sessions:', err);
  6454. }
  6455. }
  6456. function renderPPPSessions() {
  6457. const tbody = document.getElementById('active-ppp-table-body');
  6458. const empty = document.getElementById('active-ppp-empty');
  6459. if (!tbody) return;
  6460. tbody.innerHTML = '';
  6461. const list = state.pppActiveSessions || [];
  6462. if (list.length === 0) {
  6463. empty?.classList.remove('hidden');
  6464. return;
  6465. }
  6466. empty?.classList.add('hidden');
  6467. list.forEach(s => {
  6468. const tr = document.createElement('tr');
  6469. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6470. tr.innerHTML = `
  6471. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  6472. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  6473. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  6474. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  6475. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  6476. <td class="py-2.5 px-3 text-[11px]">
  6477. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  6478. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  6479. </td>
  6480. <td class="py-2.5 px-3 text-right font-sans">
  6481. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  6482. </td>
  6483. `;
  6484. tbody.appendChild(tr);
  6485. });
  6486. }
  6487. async function disconnectPPPSession(iface) {
  6488. if (!confirm(`Disconnect session ${iface}?`)) return;
  6489. try {
  6490. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  6491. if (res.ok) {
  6492. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  6493. loadPPPSessions();
  6494. }
  6495. } catch (err) {
  6496. showToast('Error', err.message, 'error');
  6497. }
  6498. }
  6499. // PPP Secret Modal handlers
  6500. function openAddPPPSecretModal() {
  6501. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  6502. document.getElementById('secret-modal-id').value = '';
  6503. document.getElementById('secret-modal-name').value = '';
  6504. document.getElementById('secret-modal-password').value = '';
  6505. document.getElementById('secret-modal-service').value = 'any';
  6506. document.getElementById('secret-modal-profile').value = 'default';
  6507. document.getElementById('secret-modal-local').value = '';
  6508. document.getElementById('secret-modal-remote').value = '';
  6509. document.getElementById('secret-modal-comment').value = '';
  6510. document.getElementById('secret-modal-disabled').checked = false;
  6511. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  6512. }
  6513. function openEditPPPSecretModal(id) {
  6514. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  6515. if (!s) return;
  6516. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  6517. document.getElementById('secret-modal-id').value = s.id;
  6518. document.getElementById('secret-modal-name').value = s.name;
  6519. document.getElementById('secret-modal-password').value = s.password;
  6520. document.getElementById('secret-modal-service').value = s.service || 'any';
  6521. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  6522. document.getElementById('secret-modal-local').value = s.local_address || '';
  6523. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  6524. document.getElementById('secret-modal-comment').value = s.comment || '';
  6525. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  6526. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  6527. }
  6528. function closePPPSecretModal() {
  6529. document.getElementById('ppp-secret-modal').classList.add('hidden');
  6530. }
  6531. async function submitSavePPPSecret(e) {
  6532. e.preventDefault();
  6533. const id = document.getElementById('secret-modal-id').value;
  6534. const name = document.getElementById('secret-modal-name').value.trim();
  6535. const password = document.getElementById('secret-modal-password').value.trim();
  6536. const service = document.getElementById('secret-modal-service').value;
  6537. const profile = document.getElementById('secret-modal-profile').value;
  6538. const local = document.getElementById('secret-modal-local').value.trim();
  6539. const remote = document.getElementById('secret-modal-remote').value.trim();
  6540. const comment = document.getElementById('secret-modal-comment').value.trim();
  6541. const disabled = document.getElementById('secret-modal-disabled').checked;
  6542. try {
  6543. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  6544. method: 'POST',
  6545. headers: { 'Content-Type': 'application/json' },
  6546. body: JSON.stringify({
  6547. id,
  6548. name,
  6549. password,
  6550. service,
  6551. profile,
  6552. local_address: local,
  6553. remote_address: remote,
  6554. comment,
  6555. disabled
  6556. })
  6557. });
  6558. if (res.ok) {
  6559. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  6560. closePPPSecretModal();
  6561. loadPPPSecrets();
  6562. } else {
  6563. const err = await res.json();
  6564. showToast('Error', err.message, 'error');
  6565. }
  6566. } catch (err) {
  6567. showToast('Error', err.message, 'error');
  6568. }
  6569. }
  6570. async function togglePPPSecretState(id, disabled) {
  6571. try {
  6572. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  6573. method: 'POST',
  6574. headers: { 'Content-Type': 'application/json' },
  6575. body: JSON.stringify({ disabled })
  6576. });
  6577. if (res.ok) {
  6578. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  6579. loadPPPSecrets();
  6580. }
  6581. } catch (err) {
  6582. showToast('Error', err.message, 'error');
  6583. }
  6584. }
  6585. async function deletePPPSecret(id) {
  6586. if (!confirm('Are you sure you want to delete this secret account?')) return;
  6587. try {
  6588. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6589. if (res.ok) {
  6590. showToast('Deleted', 'Secret account removed', 'success');
  6591. loadPPPSecrets();
  6592. }
  6593. } catch (err) {
  6594. showToast('Error', err.message, 'error');
  6595. }
  6596. }
  6597. // PPP Profile Modal handlers
  6598. function openAddPPPProfileModal() {
  6599. document.getElementById('profile-modal-name').value = '';
  6600. document.getElementById('profile-modal-local').value = '10.10.10.1';
  6601. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  6602. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  6603. document.getElementById('profile-modal-encryption').value = 'required';
  6604. document.getElementById('profile-modal-onlyone').checked = true;
  6605. document.getElementById('profile-modal-comment').value = '';
  6606. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  6607. }
  6608. function closePPPProfileModal() {
  6609. document.getElementById('ppp-profile-modal').classList.add('hidden');
  6610. }
  6611. async function submitSavePPPProfile(e) {
  6612. e.preventDefault();
  6613. const name = document.getElementById('profile-modal-name').value.trim();
  6614. const local = document.getElementById('profile-modal-local').value.trim();
  6615. const remote = document.getElementById('profile-modal-remote').value.trim();
  6616. const dns = document.getElementById('profile-modal-dns').value.trim();
  6617. const enc = document.getElementById('profile-modal-encryption').value;
  6618. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  6619. const comment = document.getElementById('profile-modal-comment').value.trim();
  6620. try {
  6621. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  6622. method: 'POST',
  6623. headers: { 'Content-Type': 'application/json' },
  6624. body: JSON.stringify({
  6625. id: name,
  6626. name,
  6627. local_address: local,
  6628. remote_address: remote,
  6629. dns_servers: dns,
  6630. use_encryption: enc,
  6631. only_one: onlyone,
  6632. comment
  6633. })
  6634. });
  6635. if (res.ok) {
  6636. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  6637. closePPPProfileModal();
  6638. loadPPPProfiles();
  6639. } else {
  6640. const err = await res.json();
  6641. showToast('Error', err.message, 'error');
  6642. }
  6643. } catch (err) {
  6644. showToast('Error', err.message, 'error');
  6645. }
  6646. }
  6647. async function deletePPPProfile(name) {
  6648. if (!confirm(`Delete PPP profile ${name}?`)) return;
  6649. try {
  6650. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  6651. if (res.ok) {
  6652. showToast('Deleted', 'Profile removed', 'success');
  6653. loadPPPProfiles();
  6654. } else {
  6655. const err = await res.json();
  6656. showToast('Error', err.message, 'error');
  6657. }
  6658. } catch (err) {
  6659. showToast('Error', err.message, 'error');
  6660. }
  6661. }
  6662. // Server Config submissions
  6663. async function savePPPoEServerConfig(e) {
  6664. e.preventDefault();
  6665. const enabled = document.getElementById('pppoe-server-enabled').checked;
  6666. const name = document.getElementById('pppoe-server-name').value.trim();
  6667. const iface = document.getElementById('pppoe-server-iface').value;
  6668. const profile = document.getElementById('pppoe-server-profile').value;
  6669. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  6670. const onesession = document.getElementById('pppoe-server-onesession').checked;
  6671. try {
  6672. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  6673. method: 'POST',
  6674. headers: { 'Content-Type': 'application/json' },
  6675. body: JSON.stringify({
  6676. enabled,
  6677. service_name: name,
  6678. interface: iface,
  6679. default_profile: profile,
  6680. max_mtu: mtu,
  6681. max_mru: mtu,
  6682. one_session_per_host: onesession
  6683. })
  6684. });
  6685. if (res.ok) {
  6686. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  6687. loadPPPServers();
  6688. fetchData(false);
  6689. } else {
  6690. const err = await res.json();
  6691. showToast('Error', err.message, 'error');
  6692. }
  6693. } catch (err) {
  6694. showToast('Error', err.message, 'error');
  6695. }
  6696. }
  6697. async function savePPTPServerConfig(e) {
  6698. e.preventDefault();
  6699. const enabled = document.getElementById('pptp-server-enabled').checked;
  6700. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  6701. const profile = document.getElementById('pptp-server-profile').value;
  6702. const mppe = document.getElementById('pptp-server-mppe').checked;
  6703. try {
  6704. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  6705. method: 'POST',
  6706. headers: { 'Content-Type': 'application/json' },
  6707. body: JSON.stringify({
  6708. enabled,
  6709. port,
  6710. default_profile: profile,
  6711. require_mppe: mppe
  6712. })
  6713. });
  6714. if (res.ok) {
  6715. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  6716. loadPPPServers();
  6717. fetchData(false);
  6718. } else {
  6719. const err = await res.json();
  6720. showToast('Error', err.message, 'error');
  6721. }
  6722. } catch (err) {
  6723. showToast('Error', err.message, 'error');
  6724. }
  6725. }
  6726. async function saveL2TPServerConfig(e) {
  6727. e.preventDefault();
  6728. const enabled = document.getElementById('l2tp-server-enabled').checked;
  6729. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  6730. const profile = document.getElementById('l2tp-server-profile').value;
  6731. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  6732. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  6733. try {
  6734. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  6735. method: 'POST',
  6736. headers: { 'Content-Type': 'application/json' },
  6737. body: JSON.stringify({
  6738. enabled,
  6739. port,
  6740. default_profile: profile,
  6741. use_ipsec: useipsec,
  6742. ipsec_secret: psk
  6743. })
  6744. });
  6745. if (res.ok) {
  6746. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  6747. loadPPPServers();
  6748. fetchData(false);
  6749. } else {
  6750. const err = await res.json();
  6751. showToast('Error', err.message, 'error');
  6752. }
  6753. } catch (err) {
  6754. showToast('Error', err.message, 'error');
  6755. }
  6756. }
  6757. // IPSec Server Modal
  6758. function openIPSecServerModal() {
  6759. loadPPPServers();
  6760. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  6761. }
  6762. function closeIPSecServerModal() {
  6763. document.getElementById('ipsec-server-modal').classList.add('hidden');
  6764. }
  6765. async function submitSaveIPSecServer(e) {
  6766. e.preventDefault();
  6767. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  6768. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  6769. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  6770. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  6771. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  6772. try {
  6773. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  6774. method: 'POST',
  6775. headers: { 'Content-Type': 'application/json' },
  6776. body: JSON.stringify({
  6777. enabled,
  6778. preshared_key: psk,
  6779. pool_address: pool,
  6780. dns_servers: dns,
  6781. local_subnet: subnet
  6782. })
  6783. });
  6784. if (res.ok) {
  6785. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  6786. closeIPSecServerModal();
  6787. loadPPPServers();
  6788. fetchData(false);
  6789. } else {
  6790. const err = await res.json();
  6791. showToast('Error', err.message, 'error');
  6792. }
  6793. } catch (err) {
  6794. showToast('Error', err.message, 'error');
  6795. }
  6796. }
  6797. // WireGuard Client Config Viewer
  6798. let currentWGClientConf = '';
  6799. async function openWGClientConfModal(iface, clientIP) {
  6800. try {
  6801. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  6802. method: 'POST',
  6803. headers: { 'Content-Type': 'application/json' },
  6804. body: JSON.stringify({
  6805. interface: iface,
  6806. address: clientIP || '10.10.0.2/32',
  6807. dns: '1.1.1.1, 8.8.8.8'
  6808. })
  6809. });
  6810. if (res.ok) {
  6811. const data = await res.json();
  6812. currentWGClientConf = data.config;
  6813. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  6814. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  6815. } else {
  6816. const err = await res.json();
  6817. showToast('Error', err.message, 'error');
  6818. }
  6819. } catch (err) {
  6820. showToast('Error', err.message, 'error');
  6821. }
  6822. }
  6823. function closeWGClientConfModal() {
  6824. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  6825. }
  6826. function copyWGClientConf() {
  6827. if (!currentWGClientConf) return;
  6828. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  6829. }
  6830. function downloadWGClientConf() {
  6831. if (!currentWGClientConf) return;
  6832. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  6833. const a = document.createElement('a');
  6834. a.href = URL.createObjectURL(blob);
  6835. a.download = 'wireguard-client.conf';
  6836. document.body.appendChild(a);
  6837. a.click();
  6838. document.body.removeChild(a);
  6839. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  6840. }
  6841. // =========================================================================
  6842. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  6843. // =========================================================================
  6844. state.activeDynSubTab = 'bgp-peers';
  6845. state.activeBgpSubTab = 'bgp-peers';
  6846. state.activeOspfTab = 'instances';
  6847. state.bgpInstance = null;
  6848. state.bgpPeers = [];
  6849. state.bgpNets = [];
  6850. state.bgpRoutes = [];
  6851. state.ospfInstance = null;
  6852. state.ospfInstances = [];
  6853. state.ospfAreas = [];
  6854. state.ospfAreaRanges = [];
  6855. state.ospfTemplates = [];
  6856. state.ospfLiveInterfaces = [];
  6857. state.ospfStaticNbrs = [];
  6858. state.ospfNeighbors = [];
  6859. state.ospfLSA = [];
  6860. state.ospfRoutes = [];
  6861. state.selectedOspfRow = {
  6862. instances: null,
  6863. areas: null,
  6864. 'area-ranges': null,
  6865. templates: null,
  6866. interfaces: null,
  6867. 'static-nbrs': null,
  6868. neighbors: null,
  6869. lsa: null,
  6870. };
  6871. state.ospfSort = {
  6872. instances: { col: 'name', asc: true },
  6873. areas: { col: 'name', asc: true },
  6874. ranges: { col: 'area', asc: true },
  6875. templates: { col: 'interfaces', asc: true },
  6876. live_ifaces: { col: 'interface', asc: true },
  6877. snbrs: { col: 'address', asc: true },
  6878. neighbors: { col: 'address', asc: true },
  6879. lsa: { col: 'instance', asc: true },
  6880. };
  6881. function switchBgpSubTab(subTab) {
  6882. state.activeBgpSubTab = subTab;
  6883. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  6884. tabs.forEach(t => {
  6885. const el = document.getElementById(`dyn-subtab-${t}`);
  6886. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  6887. if (el) el.classList.toggle('hidden', t !== subTab);
  6888. if (btn) {
  6889. if (t === subTab) {
  6890. 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';
  6891. } else {
  6892. 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';
  6893. }
  6894. }
  6895. });
  6896. }
  6897. function switchOspfTab(tabName) {
  6898. state.activeOspfTab = tabName;
  6899. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  6900. tabs.forEach(t => {
  6901. const pane = document.getElementById(`ospf-pane-${t}`);
  6902. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  6903. if (pane) pane.classList.toggle('hidden', t !== tabName);
  6904. if (btn) {
  6905. if (t === tabName) {
  6906. 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';
  6907. } else {
  6908. 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';
  6909. }
  6910. }
  6911. });
  6912. }
  6913. function switchOspfSubTab(tab) {
  6914. // Legacy alias
  6915. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  6916. else if (tab === 'ospf-areas') switchOspfTab('areas');
  6917. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  6918. else switchOspfTab('instances');
  6919. }
  6920. function switchDynSubTab(subTab) {
  6921. if (subTab.startsWith('bgp')) {
  6922. if (state.activeTab !== 'bgp') navigate('bgp');
  6923. switchBgpSubTab(subTab);
  6924. } else if (subTab.startsWith('ospf')) {
  6925. if (state.activeTab !== 'ospf') navigate('ospf');
  6926. switchOspfTab('instances');
  6927. }
  6928. }
  6929. async function loadDynamicRouting(showToastMsg = false) {
  6930. try {
  6931. const fetchSafeJson = async (url) => {
  6932. try {
  6933. const r = await fetch(url);
  6934. return r.ok ? await r.json() : null;
  6935. } catch (e) {
  6936. return null;
  6937. }
  6938. };
  6939. const [
  6940. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  6941. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  6942. selectRules, commLists, asLists
  6943. ] = await Promise.all([
  6944. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  6945. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  6946. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  6947. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  6948. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  6949. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  6950. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  6951. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  6952. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  6953. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  6954. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  6955. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  6956. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  6957. fetchSafeJson(`${API_BASE}/routing/filters`),
  6958. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  6959. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  6960. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  6961. ]);
  6962. if (sum) state.dynSummary = sum;
  6963. if (bgpInst) state.bgpInstance = bgpInst;
  6964. if (bgpPeers) state.bgpPeers = bgpPeers;
  6965. if (bgpNets) state.bgpNets = bgpNets;
  6966. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  6967. if (ospfInsts) state.ospfInstances = ospfInsts;
  6968. if (ospfAreas) state.ospfAreas = ospfAreas;
  6969. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  6970. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  6971. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  6972. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  6973. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  6974. if (ospfLsa) state.ospfLSA = ospfLsa;
  6975. if (filters) state.routingFilters = filters;
  6976. if (selectRules) state.routingSelectRules = selectRules;
  6977. if (commLists) state.routingCommunityLists = commLists;
  6978. if (asLists) state.routingASLists = asLists;
  6979. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  6980. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  6981. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  6982. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  6983. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  6984. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  6985. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  6986. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  6987. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  6988. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  6989. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  6990. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  6991. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  6992. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  6993. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  6994. } catch (err) {
  6995. console.error('Failed to load dynamic routing:', err);
  6996. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  6997. }
  6998. }
  6999. async function loadOspfAll() {
  7000. await loadDynamicRouting(true);
  7001. }
  7002. function renderBgpStatusPill() {
  7003. const pill = document.getElementById('bgp-live-status-pill');
  7004. if (!pill) return;
  7005. const inst = state.bgpInstance;
  7006. if (!inst || !inst.enabled) {
  7007. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  7008. pill.innerText = 'BGP DISABLED';
  7009. } else if (inst.running) {
  7010. 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';
  7011. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  7012. } else {
  7013. 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';
  7014. pill.innerText = 'BGP STARTING...';
  7015. }
  7016. }
  7017. function renderBgpPeers() {
  7018. const tbody = document.getElementById('bgp-peers-table-body');
  7019. if (!tbody) return;
  7020. const empty = document.getElementById('bgp-peers-empty');
  7021. const countBadge = document.getElementById('bgp-peers-count-badge');
  7022. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  7023. const peers = state.bgpPeers || [];
  7024. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  7025. if (navBadge) navBadge.innerText = peers.length;
  7026. if (peers.length === 0) {
  7027. tbody.innerHTML = '';
  7028. if (empty) empty.classList.remove('hidden');
  7029. return;
  7030. }
  7031. if (empty) empty.classList.add('hidden');
  7032. tbody.innerHTML = peers.map(p => {
  7033. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  7034. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  7035. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  7036. let stateBadge = '';
  7037. if (p.disabled) {
  7038. 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>';
  7039. } else if (p.state === 'Established') {
  7040. 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>';
  7041. } else if (p.state === 'Connect' || p.state === 'Active') {
  7042. 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>`;
  7043. } else {
  7044. 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>`;
  7045. }
  7046. return `
  7047. <tr class="hover:bg-slate-800/40 transition">
  7048. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  7049. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  7050. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  7051. <td class="py-2.5 px-3">
  7052. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  7053. ${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>`}
  7054. </td>
  7055. <td class="py-2.5 px-3">${stateBadge}</td>
  7056. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  7057. <td class="py-2.5 px-3 text-slate-300">
  7058. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  7059. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  7060. </td>
  7061. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  7062. ${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> ` : ''}
  7063. ${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>` : ''}
  7064. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  7065. </td>
  7066. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  7067. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  7068. <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'}">
  7069. ${p.disabled ? 'Enable' : 'Disable'}
  7070. </button>
  7071. <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">
  7072. Edit
  7073. </button>
  7074. <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">
  7075. Delete
  7076. </button>
  7077. </td>
  7078. </tr>
  7079. `;
  7080. }).join('');
  7081. }
  7082. function renderBgpNetworks() {
  7083. const tbody = document.getElementById('bgp-nets-table-body');
  7084. if (!tbody) return;
  7085. const empty = document.getElementById('bgp-nets-empty');
  7086. const countBadge = document.getElementById('bgp-nets-count-badge');
  7087. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  7088. const nets = state.bgpNets || [];
  7089. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  7090. if (navBadge) navBadge.innerText = nets.length;
  7091. if (nets.length === 0) {
  7092. tbody.innerHTML = '';
  7093. if (empty) empty.classList.remove('hidden');
  7094. return;
  7095. }
  7096. if (empty) empty.classList.add('hidden');
  7097. tbody.innerHTML = nets.map(n => `
  7098. <tr class="hover:bg-slate-800/40 transition">
  7099. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  7100. <td class="py-2.5 px-3">
  7101. ${n.disabled
  7102. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  7103. : '<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>'}
  7104. </td>
  7105. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  7106. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  7107. <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">
  7108. Delete
  7109. </button>
  7110. </td>
  7111. </tr>
  7112. `).join('');
  7113. }
  7114. function renderBgpRoutes() {
  7115. const tbody = document.getElementById('bgp-routes-table-body');
  7116. if (!tbody) return;
  7117. const empty = document.getElementById('bgp-routes-empty');
  7118. const countBadge = document.getElementById('bgp-routes-count-badge');
  7119. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  7120. const routes = state.bgpRoutes || [];
  7121. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  7122. if (navBadge) navBadge.innerText = routes.length;
  7123. if (routes.length === 0) {
  7124. tbody.innerHTML = '';
  7125. if (empty) empty.classList.remove('hidden');
  7126. return;
  7127. }
  7128. if (empty) empty.classList.add('hidden');
  7129. tbody.innerHTML = routes.map(r => `
  7130. <tr class="hover:bg-slate-800/40 transition">
  7131. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  7132. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  7133. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  7134. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  7135. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  7136. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  7137. </tr>
  7138. `).join('');
  7139. }
  7140. // =========================================================================
  7141. // ROUTEROS v7 OSPF TABLE RENDERING & SORTING
  7142. // =========================================================================
  7143. function sortOspfTable(tab, col) {
  7144. if (!state.ospfSort) state.ospfSort = {};
  7145. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  7146. if (state.ospfSort[tab].col === col) {
  7147. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  7148. } else {
  7149. state.ospfSort[tab].col = col;
  7150. state.ospfSort[tab].asc = true;
  7151. }
  7152. const asc = state.ospfSort[tab].asc;
  7153. let list = [];
  7154. if (tab === 'instances') list = state.ospfInstances || [];
  7155. else if (tab === 'areas') list = state.ospfAreas || [];
  7156. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  7157. else if (tab === 'templates') list = state.ospfTemplates || [];
  7158. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  7159. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  7160. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  7161. else if (tab === 'lsa') list = state.ospfLSA || [];
  7162. list.sort((a, b) => {
  7163. let valA = a[col] ?? '';
  7164. let valB = b[col] ?? '';
  7165. if (typeof valA === 'number' && typeof valB === 'number') {
  7166. return asc ? valA - valB : valB - valA;
  7167. }
  7168. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  7169. });
  7170. if (tab === 'instances') renderOspfInstances();
  7171. else if (tab === 'areas') renderOspfAreas();
  7172. else if (tab === 'ranges') renderOspfAreaRanges();
  7173. else if (tab === 'templates') renderOspfTemplates();
  7174. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  7175. else if (tab === 'snbrs') renderOspfStaticNbrs();
  7176. else if (tab === 'neighbors') renderOspfNeighbors();
  7177. else if (tab === 'lsa') renderOspfLSA();
  7178. }
  7179. function selectOspfRow(tab, id) {
  7180. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  7181. state.selectedOspfRow[tab] = id;
  7182. if (tab === 'instances') {
  7183. renderOspfInstances();
  7184. const btnEn = document.getElementById('btn-ospf-inst-enable');
  7185. const btnDis = document.getElementById('btn-ospf-inst-disable');
  7186. const btnRem = document.getElementById('btn-ospf-inst-remove');
  7187. const btnCom = document.getElementById('btn-ospf-inst-comment');
  7188. if (btnEn) btnEn.disabled = false;
  7189. if (btnDis) btnDis.disabled = false;
  7190. if (btnRem) btnRem.disabled = false;
  7191. if (btnCom) btnCom.disabled = false;
  7192. } else if (tab === 'areas') {
  7193. renderOspfAreas();
  7194. const btnEn = document.getElementById('btn-ospf-area-enable');
  7195. const btnDis = document.getElementById('btn-ospf-area-disable');
  7196. const btnRem = document.getElementById('btn-ospf-area-remove');
  7197. const btnCom = document.getElementById('btn-ospf-area-comment');
  7198. if (btnEn) btnEn.disabled = false;
  7199. if (btnDis) btnDis.disabled = false;
  7200. if (btnRem) btnRem.disabled = false;
  7201. if (btnCom) btnCom.disabled = false;
  7202. } else if (tab === 'ranges') {
  7203. renderOspfAreaRanges();
  7204. const btnEn = document.getElementById('btn-ospf-range-enable');
  7205. const btnDis = document.getElementById('btn-ospf-range-disable');
  7206. const btnRem = document.getElementById('btn-ospf-range-remove');
  7207. const btnCom = document.getElementById('btn-ospf-range-comment');
  7208. if (btnEn) btnEn.disabled = false;
  7209. if (btnDis) btnDis.disabled = false;
  7210. if (btnRem) btnRem.disabled = false;
  7211. if (btnCom) btnCom.disabled = false;
  7212. } else if (tab === 'templates') {
  7213. renderOspfTemplates();
  7214. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  7215. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  7216. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  7217. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  7218. if (btnEn) btnEn.disabled = false;
  7219. if (btnDis) btnDis.disabled = false;
  7220. if (btnRem) btnRem.disabled = false;
  7221. if (btnCom) btnCom.disabled = false;
  7222. } else if (tab === 'snbrs') {
  7223. renderOspfStaticNbrs();
  7224. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  7225. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  7226. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  7227. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  7228. if (btnEn) btnEn.disabled = false;
  7229. if (btnDis) btnDis.disabled = false;
  7230. if (btnRem) btnRem.disabled = false;
  7231. if (btnCom) btnCom.disabled = false;
  7232. }
  7233. }
  7234. // TAB 1: INSTANCES
  7235. function renderOspfInstances() {
  7236. const tbody = document.getElementById('ospf-instances-table-body');
  7237. if (!tbody) return;
  7238. const countEl = document.getElementById('ospf-instances-footer-count');
  7239. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  7240. let list = state.ospfInstances || [];
  7241. if (filter) {
  7242. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  7243. }
  7244. if (countEl) countEl.innerText = list.length;
  7245. const selId = state.selectedOspfRow?.instances;
  7246. tbody.innerHTML = list.map((inst, idx) => {
  7247. const isSel = inst.id === selId;
  7248. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7249. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7250. return `
  7251. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  7252. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7253. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  7254. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  7255. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7256. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  7257. </td>
  7258. <td class="py-1.5 px-3">${inst.version || 2}</td>
  7259. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  7260. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  7261. </tr>
  7262. `;
  7263. }).join('');
  7264. }
  7265. // TAB 2: AREAS
  7266. function renderOspfAreas() {
  7267. const tbody = document.getElementById('ospf-areas-table-body');
  7268. if (!tbody) return;
  7269. const countEl = document.getElementById('ospf-areas-footer-count');
  7270. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  7271. let list = state.ospfAreas || [];
  7272. if (filter) {
  7273. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  7274. }
  7275. if (countEl) countEl.innerText = list.length;
  7276. const selId = state.selectedOspfRow?.areas;
  7277. tbody.innerHTML = list.map((a, idx) => {
  7278. const isSel = a.id === selId;
  7279. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7280. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7281. return `
  7282. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  7283. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7284. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  7285. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  7286. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7287. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  7288. </td>
  7289. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  7290. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  7291. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  7292. </tr>
  7293. `;
  7294. }).join('');
  7295. }
  7296. // TAB 3: AREA RANGES
  7297. function renderOspfAreaRanges() {
  7298. const tbody = document.getElementById('ospf-ranges-table-body');
  7299. if (!tbody) return;
  7300. const countEl = document.getElementById('ospf-ranges-footer-count');
  7301. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  7302. let list = state.ospfAreaRanges || [];
  7303. if (filter) {
  7304. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  7305. }
  7306. if (countEl) countEl.innerText = list.length;
  7307. const selId = state.selectedOspfRow?.['area-ranges'];
  7308. tbody.innerHTML = list.map((r, idx) => {
  7309. const isSel = r.id === selId;
  7310. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7311. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7312. return `
  7313. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  7314. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7315. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  7316. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  7317. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  7318. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  7319. <td class="py-1.5 px-3">${r.cost || 1}</td>
  7320. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  7321. </tr>
  7322. `;
  7323. }).join('');
  7324. }
  7325. // TAB 4: INTERFACE TEMPLATES
  7326. function renderOspfTemplates() {
  7327. const tbody = document.getElementById('ospf-templates-table-body');
  7328. if (!tbody) return;
  7329. const countEl = document.getElementById('ospf-templates-footer-count');
  7330. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  7331. let list = state.ospfTemplates || [];
  7332. if (filter) {
  7333. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  7334. }
  7335. if (countEl) countEl.innerText = list.length;
  7336. const selId = state.selectedOspfRow?.templates;
  7337. tbody.innerHTML = list.map((t, idx) => {
  7338. const isSel = t.id === selId;
  7339. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7340. const ifaces = t.interfaces || t.interface || 'all';
  7341. const nets = t.networks || t.network || '';
  7342. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7343. return `
  7344. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  7345. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  7346. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  7347. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  7348. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7349. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  7350. </td>
  7351. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  7352. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  7353. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  7354. <td class="py-1.5 px-3">${t.cost || 1}</td>
  7355. <td class="py-1.5 px-3">${t.priority || 128}</td>
  7356. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  7357. </tr>
  7358. `;
  7359. }).join('');
  7360. }
  7361. // TAB 5: LIVE INTERFACES
  7362. function renderOspfLiveInterfaces() {
  7363. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  7364. if (!tbody) return;
  7365. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  7366. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  7367. let list = state.ospfLiveInterfaces || [];
  7368. if (filter) {
  7369. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  7370. }
  7371. if (countEl) countEl.innerText = list.length;
  7372. tbody.innerHTML = list.map(i => `
  7373. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7374. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  7375. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  7376. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  7377. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  7378. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  7379. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  7380. <td class="py-1.5 px-3">${i.cost || 1}</td>
  7381. <td class="py-1.5 px-3">${i.priority || 128}</td>
  7382. </tr>
  7383. `).join('');
  7384. }
  7385. // TAB 6: STATIC NEIGHBORS
  7386. function renderOspfStaticNbrs() {
  7387. const tbody = document.getElementById('ospf-snbrs-table-body');
  7388. if (!tbody) return;
  7389. const countEl = document.getElementById('ospf-snbrs-footer-count');
  7390. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  7391. let list = state.ospfStaticNbrs || [];
  7392. if (filter) {
  7393. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  7394. }
  7395. if (countEl) countEl.innerText = list.length;
  7396. const selId = state.selectedOspfRow?.['static-nbrs'];
  7397. tbody.innerHTML = list.map((n, idx) => {
  7398. const isSel = n.id === selId;
  7399. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7400. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7401. return `
  7402. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  7403. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7404. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  7405. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  7406. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  7407. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  7408. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  7409. <td class="py-1.5 px-3">${n.cost || 1}</td>
  7410. </tr>
  7411. `;
  7412. }).join('');
  7413. }
  7414. // TAB 7: LIVE NEIGHBORS
  7415. function renderOspfNeighbors() {
  7416. const tbody = document.getElementById('ospf-neighbors-table-body');
  7417. if (!tbody) return;
  7418. const countEl = document.getElementById('ospf-neighbors-footer-count');
  7419. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  7420. let list = state.ospfNeighbors || [];
  7421. if (filter) {
  7422. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  7423. }
  7424. if (countEl) countEl.innerText = list.length;
  7425. tbody.innerHTML = list.map(n => `
  7426. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7427. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  7428. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  7429. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7430. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  7431. </td>
  7432. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  7433. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  7434. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  7435. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  7436. </tr>
  7437. `).join('');
  7438. }
  7439. // TAB 8: LINK-STATE DATABASE (LSA)
  7440. function renderOspfLSA() {
  7441. const tbody = document.getElementById('ospf-lsa-table-body');
  7442. if (!tbody) return;
  7443. const countEl = document.getElementById('ospf-lsa-footer-count');
  7444. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  7445. let list = state.ospfLSA || [];
  7446. if (filter) {
  7447. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  7448. }
  7449. if (countEl) countEl.innerText = list.length;
  7450. tbody.innerHTML = list.map(l => `
  7451. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7452. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  7453. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7454. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  7455. </td>
  7456. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  7457. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  7458. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  7459. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  7460. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  7461. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  7462. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  7463. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  7464. </tr>
  7465. `).join('');
  7466. }
  7467. function renderOspfStatusPill() {
  7468. // Maintained for backward compatibility
  7469. const pill = document.getElementById('ospf-live-status-pill');
  7470. if (!pill) return;
  7471. 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';
  7472. pill.innerText = 'OSPF ACTIVE';
  7473. }
  7474. function renderOspfInterfaces() {
  7475. renderOspfTemplates();
  7476. }
  7477. function renderOspfRoutes() {
  7478. // Routes retained in background
  7479. }
  7480. // BGP Modals & Actions
  7481. function openBgpInstanceModal() {
  7482. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  7483. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  7484. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  7485. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  7486. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  7487. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  7488. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  7489. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  7490. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  7491. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  7492. }
  7493. function closeBgpInstanceModal() {
  7494. document.getElementById('bgp-instance-modal').classList.add('hidden');
  7495. }
  7496. async function submitBgpInstance(e) {
  7497. e.preventDefault();
  7498. const payload = {
  7499. enabled: document.getElementById('modal-bgp-enabled').checked,
  7500. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  7501. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  7502. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  7503. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  7504. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  7505. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  7506. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  7507. };
  7508. try {
  7509. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  7510. method: 'POST',
  7511. headers: { 'Content-Type': 'application/json' },
  7512. body: JSON.stringify(payload)
  7513. });
  7514. if (res.ok) {
  7515. closeBgpInstanceModal();
  7516. showToast('Success', 'BGP instance configuration updated', 'success');
  7517. loadDynamicRouting();
  7518. } else {
  7519. const err = await res.json();
  7520. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  7521. }
  7522. } catch (err) {
  7523. showToast('Error', err.message, 'error');
  7524. }
  7525. }
  7526. // ----------------- BGP Peer Connection Modal (RouterOS v7) -----------------
  7527. function switchBgpPeerModalTab(tab) {
  7528. const tabs = ['general', 'extra', 'attributes', 'filter'];
  7529. tabs.forEach(t => {
  7530. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  7531. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  7532. if (t === tab) {
  7533. if (pane) pane.classList.remove('hidden');
  7534. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  7535. } else {
  7536. if (pane) pane.classList.add('hidden');
  7537. 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';
  7538. }
  7539. });
  7540. }
  7541. function addOutputNetworkRow(val = '') {
  7542. const container = document.getElementById('modal-bgp-output-networks-container');
  7543. if (!container) return;
  7544. const row = document.createElement('div');
  7545. row.className = 'flex items-center gap-2 output-net-row';
  7546. row.innerHTML = `
  7547. <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">
  7548. <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>
  7549. `;
  7550. container.appendChild(row);
  7551. }
  7552. function parseBgpTime(val) {
  7553. if (!val) return 0;
  7554. val = String(val).trim();
  7555. if (val.includes(':')) {
  7556. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  7557. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  7558. if (parts.length === 2) return parts[0] * 60 + parts[1];
  7559. }
  7560. return parseInt(val, 10) || 0;
  7561. }
  7562. function formatBgpTime(secs) {
  7563. if (!secs || secs <= 0) return '00:00:00';
  7564. const h = Math.floor(secs / 3600);
  7565. const m = Math.floor((secs % 3600) / 60);
  7566. const s = secs % 60;
  7567. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  7568. }
  7569. function populateBgpRoutingTables() {
  7570. const sel = document.getElementById('modal-bgp-peer-routing-table');
  7571. if (!sel) return;
  7572. const cur = sel.value || 'main';
  7573. sel.innerHTML = '<option value="main">main</option>';
  7574. (state.routingTables || []).forEach(t => {
  7575. if (t.name !== 'main') {
  7576. const opt = document.createElement('option');
  7577. opt.value = t.name;
  7578. opt.innerText = t.name;
  7579. sel.appendChild(opt);
  7580. }
  7581. });
  7582. sel.value = cur;
  7583. }
  7584. function openAddBgpPeerModal() {
  7585. document.getElementById('bgp-peer-form').reset();
  7586. document.getElementById('modal-bgp-peer-id').value = '';
  7587. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  7588. // General Tab
  7589. document.getElementById('modal-bgp-peer-enabled').checked = true;
  7590. document.getElementById('modal-bgp-peer-comment').value = '';
  7591. document.getElementById('modal-bgp-peer-name').value = '';
  7592. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  7593. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  7594. document.getElementById('modal-bgp-peer-local-as').value = '';
  7595. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  7596. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  7597. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  7598. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  7599. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  7600. document.getElementById('modal-bgp-peer-router-id').value = '';
  7601. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  7602. document.getElementById('modal-bgp-peer-remote-port').value = '';
  7603. document.getElementById('modal-bgp-peer-remote-as').value = '';
  7604. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  7605. document.getElementById('modal-bgp-peer-local-addr').value = '';
  7606. document.getElementById('modal-bgp-peer-local-port').value = '';
  7607. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  7608. document.getElementById('modal-bgp-peer-password').value = '';
  7609. document.getElementById('modal-bgp-peer-multihop').checked = false;
  7610. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  7611. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  7612. document.getElementById('modal-bgp-peer-connect').checked = true;
  7613. document.getElementById('modal-bgp-peer-listen').checked = true;
  7614. // Extra Tab
  7615. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  7616. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  7617. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  7618. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  7619. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  7620. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  7621. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  7622. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  7623. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  7624. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  7625. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  7626. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  7627. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = false;
  7628. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = false;
  7629. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  7630. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = false;
  7631. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = false;
  7632. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = false;
  7633. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = '';
  7634. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = '';
  7635. // Attributes Tab
  7636. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  7637. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  7638. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  7639. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  7640. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  7641. document.getElementById('modal-bgp-peer-as-override').checked = false;
  7642. // Filter Tab
  7643. populateFilterChainsDatalist();
  7644. document.getElementById('modal-bgp-peer-in-filter').value = '';
  7645. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = '';
  7646. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = '';
  7647. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = '';
  7648. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = '';
  7649. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = '';
  7650. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = '';
  7651. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = '';
  7652. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = false;
  7653. document.getElementById('modal-bgp-peer-out-filter').value = '';
  7654. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = 'disabled';
  7655. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  7656. populateBgpRoutingTables();
  7657. const container = document.getElementById('modal-bgp-output-networks-container');
  7658. if (container) {
  7659. container.innerHTML = '';
  7660. addOutputNetworkRow('');
  7661. }
  7662. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7663. if (removeBtn) removeBtn.classList.add('hidden');
  7664. switchBgpPeerModalTab('general');
  7665. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  7666. }
  7667. function populateFilterChainsDatalist() {
  7668. const dl = document.getElementById('filter-chains-list');
  7669. if (!dl) return;
  7670. const chains = new Set();
  7671. (state.routingFilters || []).forEach(f => {
  7672. if (f.chain) chains.add(f.chain);
  7673. });
  7674. if (chains.size === 0) {
  7675. chains.add('awmn');
  7676. chains.add('bgp-in');
  7677. chains.add('bgp-out');
  7678. }
  7679. dl.innerHTML = '';
  7680. chains.forEach(c => {
  7681. const opt = document.createElement('option');
  7682. opt.value = c;
  7683. dl.appendChild(opt);
  7684. });
  7685. }
  7686. function openEditBgpPeerModal(id) {
  7687. const p = (state.bgpPeers || []).find(item => item.id === id);
  7688. if (!p) return;
  7689. populateBgpRoutingTables();
  7690. populateFilterChainsDatalist();
  7691. document.getElementById('modal-bgp-peer-id').value = p.id;
  7692. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  7693. // General Tab
  7694. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  7695. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  7696. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  7697. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  7698. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  7699. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  7700. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  7701. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  7702. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  7703. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  7704. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  7705. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  7706. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  7707. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  7708. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  7709. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  7710. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  7711. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  7712. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  7713. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  7714. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  7715. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  7716. // Extra Tab
  7717. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  7718. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  7719. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  7720. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  7721. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  7722. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  7723. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  7724. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  7725. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  7726. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  7727. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  7728. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  7729. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  7730. 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;
  7731. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = !!p.redist_slaac;
  7732. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  7733. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = !!p.network_blackhole;
  7734. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = !!p.no_early_cut;
  7735. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = !!p.keep_sent_attrs;
  7736. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = p.input_affinity || '';
  7737. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = p.output_affinity || '';
  7738. // Attributes Tab
  7739. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  7740. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  7741. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  7742. 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;
  7743. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  7744. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  7745. // Filter Tab
  7746. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  7747. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = p.in_accept_nlri || '';
  7748. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = p.in_accept_communities || '';
  7749. 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 || '';
  7750. 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 || '';
  7751. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = p.in_filter_communities || '';
  7752. 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 || '';
  7753. 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 || '';
  7754. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = !!p.in_filter_unknown;
  7755. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  7756. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = p.out_selection_policy || 'disabled';
  7757. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  7758. // Output Networks
  7759. const container = document.getElementById('modal-bgp-output-networks-container');
  7760. if (container) {
  7761. container.innerHTML = '';
  7762. if (p.output_networks && p.output_networks.length > 0) {
  7763. p.output_networks.forEach(net => addOutputNetworkRow(net));
  7764. } else {
  7765. addOutputNetworkRow('');
  7766. }
  7767. }
  7768. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7769. if (removeBtn) removeBtn.classList.remove('hidden');
  7770. switchBgpPeerModalTab('general');
  7771. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  7772. }
  7773. function copyCurrentBgpPeer() {
  7774. document.getElementById('modal-bgp-peer-id').value = '';
  7775. const nameEl = document.getElementById('modal-bgp-peer-name');
  7776. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  7777. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  7778. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7779. if (removeBtn) removeBtn.classList.add('hidden');
  7780. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  7781. }
  7782. function removeCurrentBgpPeer() {
  7783. const id = document.getElementById('modal-bgp-peer-id')?.value;
  7784. if (!id) return;
  7785. deleteBgpPeer(id);
  7786. closeBgpPeerModal();
  7787. }
  7788. function closeBgpPeerModal() {
  7789. document.getElementById('bgp-peer-modal').classList.add('hidden');
  7790. }
  7791. function getBgpPeerFormData() {
  7792. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  7793. const outputNetworks = [];
  7794. netInputs.forEach(inp => {
  7795. const v = inp.value.trim();
  7796. if (v) outputNetworks.push(v);
  7797. });
  7798. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  7799. return {
  7800. id: document.getElementById('modal-bgp-peer-id').value,
  7801. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  7802. enabled: enabled,
  7803. disabled: !enabled,
  7804. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  7805. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  7806. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  7807. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  7808. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  7809. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  7810. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  7811. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  7812. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  7813. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  7814. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  7815. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  7816. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  7817. password: document.getElementById('modal-bgp-peer-password').value,
  7818. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  7819. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  7820. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  7821. connect: document.getElementById('modal-bgp-peer-connect').checked,
  7822. listen: document.getElementById('modal-bgp-peer-listen').checked,
  7823. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  7824. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  7825. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  7826. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  7827. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  7828. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  7829. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  7830. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  7831. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  7832. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  7833. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  7834. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  7835. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  7836. redist_bgp_mpls_vpn: document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')?.checked || false,
  7837. redist_slaac: document.getElementById('modal-bgp-peer-redist-slaac')?.checked || false,
  7838. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  7839. network_blackhole: document.getElementById('modal-bgp-peer-network-blackhole')?.checked || false,
  7840. no_early_cut: document.getElementById('modal-bgp-peer-no-early-cut')?.checked || false,
  7841. keep_sent_attrs: document.getElementById('modal-bgp-peer-keep-sent-attrs')?.checked || false,
  7842. input_affinity: (document.getElementById('modal-bgp-peer-input-affinity')?.value || '').trim(),
  7843. output_affinity: (document.getElementById('modal-bgp-peer-output-affinity')?.value || '').trim(),
  7844. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  7845. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  7846. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  7847. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  7848. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  7849. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  7850. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  7851. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  7852. in_accept_nlri: (document.getElementById('modal-bgp-peer-in-accept-nlri')?.value || '').trim(),
  7853. in_accept_communities: (document.getElementById('modal-bgp-peer-in-accept-comm')?.value || '').trim(),
  7854. in_accept_ext_communities: (document.getElementById('modal-bgp-peer-in-accept-ext-comm')?.value || '').trim(),
  7855. in_accept_large_communities: (document.getElementById('modal-bgp-peer-in-accept-large-comm')?.value || '').trim(),
  7856. in_filter_communities: (document.getElementById('modal-bgp-peer-in-filter-comm')?.value || '').trim(),
  7857. in_filter_ext_communities: (document.getElementById('modal-bgp-peer-in-filter-ext-comm')?.value || '').trim(),
  7858. in_filter_large_communities: (document.getElementById('modal-bgp-peer-in-filter-large-comm')?.value || '').trim(),
  7859. in_filter_unknown: document.getElementById('modal-bgp-peer-in-filter-unknown')?.checked || false,
  7860. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  7861. out_selection_policy: document.getElementById('modal-bgp-peer-out-selection-policy')?.value || 'disabled',
  7862. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  7863. output_networks: outputNetworks
  7864. };
  7865. }
  7866. async function submitBgpPeer(e) {
  7867. if (e) e.preventDefault();
  7868. const payload = getBgpPeerFormData();
  7869. try {
  7870. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  7871. method: 'POST',
  7872. headers: { 'Content-Type': 'application/json' },
  7873. body: JSON.stringify(payload)
  7874. });
  7875. if (res.ok) {
  7876. closeBgpPeerModal();
  7877. showToast('Success', 'BGP Connection saved', 'success');
  7878. loadDynamicRouting();
  7879. } else {
  7880. const err = await res.json();
  7881. showToast('Error', err.error || 'Failed to save peer', 'error');
  7882. }
  7883. } catch (err) {
  7884. showToast('Error', err.message, 'error');
  7885. }
  7886. }
  7887. async function applyBgpPeerModal(e) {
  7888. if (e) e.preventDefault();
  7889. const payload = getBgpPeerFormData();
  7890. try {
  7891. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  7892. method: 'POST',
  7893. headers: { 'Content-Type': 'application/json' },
  7894. body: JSON.stringify(payload)
  7895. });
  7896. if (res.ok) {
  7897. const data = await res.json();
  7898. if (data.peer && data.peer.id) {
  7899. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  7900. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  7901. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  7902. }
  7903. showToast('Applied', 'BGP Connection applied', 'success');
  7904. loadDynamicRouting();
  7905. } else {
  7906. const err = await res.json();
  7907. showToast('Error', err.error || 'Failed to apply peer', 'error');
  7908. }
  7909. } catch (err) {
  7910. showToast('Error', err.message, 'error');
  7911. }
  7912. }
  7913. async function deleteBgpPeer(id) {
  7914. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  7915. try {
  7916. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7917. if (res.ok) {
  7918. showToast('Deleted', 'BGP peer removed', 'success');
  7919. loadDynamicRouting();
  7920. }
  7921. } catch (err) {
  7922. showToast('Error', err.message, 'error');
  7923. }
  7924. }
  7925. async function toggleBgpPeerState(id, disabled) {
  7926. try {
  7927. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  7928. method: 'POST',
  7929. headers: { 'Content-Type': 'application/json' },
  7930. body: JSON.stringify({ disabled })
  7931. });
  7932. if (res.ok) {
  7933. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  7934. loadDynamicRouting();
  7935. }
  7936. } catch (err) {
  7937. showToast('Error', err.message, 'error');
  7938. }
  7939. }
  7940. function openAddBgpNetworkModal() {
  7941. document.getElementById('bgp-network-form').reset();
  7942. document.getElementById('modal-bgp-net-id').value = '';
  7943. document.getElementById('bgp-network-modal').classList.remove('hidden');
  7944. }
  7945. function closeBgpNetworkModal() {
  7946. document.getElementById('bgp-network-modal').classList.add('hidden');
  7947. }
  7948. async function submitBgpNetwork(e) {
  7949. e.preventDefault();
  7950. const payload = {
  7951. id: document.getElementById('modal-bgp-net-id').value,
  7952. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  7953. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  7954. disabled: document.getElementById('modal-bgp-net-disabled').checked
  7955. };
  7956. try {
  7957. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  7958. method: 'POST',
  7959. headers: { 'Content-Type': 'application/json' },
  7960. body: JSON.stringify(payload)
  7961. });
  7962. if (res.ok) {
  7963. closeBgpNetworkModal();
  7964. showToast('Success', 'BGP network advertisement saved', 'success');
  7965. loadDynamicRouting();
  7966. } else {
  7967. const err = await res.json();
  7968. showToast('Error', err.error || 'Failed to save network', 'error');
  7969. }
  7970. } catch (err) {
  7971. showToast('Error', err.message, 'error');
  7972. }
  7973. }
  7974. async function deleteBgpNetwork(id) {
  7975. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  7976. try {
  7977. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7978. if (res.ok) {
  7979. showToast('Deleted', 'Network advertisement removed', 'success');
  7980. loadDynamicRouting();
  7981. }
  7982. } catch (err) {
  7983. showToast('Error', err.message, 'error');
  7984. }
  7985. }
  7986. // =========================================================================
  7987. // ROUTEROS v7 OSPF MODALS & ACTIONS
  7988. // =========================================================================
  7989. // --- 1. OSPF INSTANCE ---
  7990. function openOspfInstanceModal(id = null) {
  7991. const isEdit = !!id;
  7992. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  7993. id: '',
  7994. name: 'Default',
  7995. version: 2,
  7996. vrf: 'main',
  7997. router_id: '192.168.131.56',
  7998. routing_table: 'main',
  7999. enabled: true,
  8000. redistribute_connected: false,
  8001. redistribute_static: true,
  8002. redistribute_bgp: false,
  8003. comment: ''
  8004. };
  8005. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  8006. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  8007. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  8008. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  8009. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  8010. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  8011. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  8012. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  8013. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  8014. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  8015. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  8016. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  8017. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  8018. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8019. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  8020. }
  8021. function openEditOspfInstanceModal(id) {
  8022. openOspfInstanceModal(id);
  8023. }
  8024. function closeOspfInstanceModal() {
  8025. document.getElementById('ospf-instance-modal').classList.add('hidden');
  8026. }
  8027. async function submitOspfInstance(e) {
  8028. if (e) e.preventDefault();
  8029. const payload = {
  8030. id: document.getElementById('modal-ospf-inst-id').value,
  8031. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  8032. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  8033. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  8034. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  8035. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  8036. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  8037. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  8038. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  8039. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  8040. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  8041. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  8042. };
  8043. try {
  8044. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  8045. method: 'POST',
  8046. headers: { 'Content-Type': 'application/json' },
  8047. body: JSON.stringify(payload)
  8048. });
  8049. if (res.ok) {
  8050. closeOspfInstanceModal();
  8051. showToast('Saved', 'OSPF instance updated', 'success');
  8052. loadDynamicRouting();
  8053. } else {
  8054. const err = await res.json();
  8055. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  8056. }
  8057. } catch (err) {
  8058. showToast('Error', err.message, 'error');
  8059. }
  8060. }
  8061. function applyOspfInstanceForm() {
  8062. submitOspfInstance(null);
  8063. }
  8064. function copyOspfInstance() {
  8065. document.getElementById('modal-ospf-inst-id').value = '';
  8066. document.getElementById('modal-ospf-inst-name').value += '-copy';
  8067. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  8068. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  8069. }
  8070. async function deleteCurrentOspfInstance() {
  8071. const id = document.getElementById('modal-ospf-inst-id').value;
  8072. if (!id) return;
  8073. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  8074. try {
  8075. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8076. if (res.ok) {
  8077. closeOspfInstanceModal();
  8078. showToast('Removed', 'OSPF instance deleted', 'success');
  8079. loadDynamicRouting();
  8080. }
  8081. } catch (err) {
  8082. showToast('Error', err.message, 'error');
  8083. }
  8084. }
  8085. async function enableSelectedOspfInstance() {
  8086. const id = state.selectedOspfRow?.instances;
  8087. if (!id) return;
  8088. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8089. method: 'POST',
  8090. headers: { 'Content-Type': 'application/json' },
  8091. body: JSON.stringify({ disabled: false })
  8092. });
  8093. loadDynamicRouting();
  8094. }
  8095. async function disableSelectedOspfInstance() {
  8096. const id = state.selectedOspfRow?.instances;
  8097. if (!id) return;
  8098. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8099. method: 'POST',
  8100. headers: { 'Content-Type': 'application/json' },
  8101. body: JSON.stringify({ disabled: true })
  8102. });
  8103. loadDynamicRouting();
  8104. }
  8105. async function removeSelectedOspfInstance() {
  8106. const id = state.selectedOspfRow?.instances;
  8107. if (!id) return;
  8108. if (!confirm('Delete selected OSPF instance?')) return;
  8109. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8110. loadDynamicRouting();
  8111. }
  8112. async function promptCommentOspfInstance() {
  8113. const id = state.selectedOspfRow?.instances;
  8114. if (!id) return;
  8115. const inst = (state.ospfInstances || []).find(i => i.id === id);
  8116. if (!inst) return;
  8117. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  8118. if (comment === null) return;
  8119. inst.comment = comment;
  8120. await fetch(`${API_BASE}/routing/ospf/instances`, {
  8121. method: 'POST',
  8122. headers: { 'Content-Type': 'application/json' },
  8123. body: JSON.stringify(inst)
  8124. });
  8125. loadDynamicRouting();
  8126. }
  8127. // --- 2. OSPF AREA ---
  8128. function populateOspfAreaDropdowns() {
  8129. const instSelect = document.getElementById('modal-ospf-area-instance');
  8130. if (instSelect) {
  8131. const cur = instSelect.value;
  8132. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  8133. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  8134. if (cur) instSelect.value = cur;
  8135. }
  8136. }
  8137. function openOspfAreaModal(id = null) {
  8138. const isEdit = !!id;
  8139. populateOspfAreaDropdowns();
  8140. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  8141. id: '',
  8142. name: 'Default',
  8143. instance: 'Default',
  8144. area_id: '0.0.0.0',
  8145. area_type: 'default',
  8146. default_cost: 1,
  8147. no_summaries: false,
  8148. disabled: false,
  8149. comment: ''
  8150. };
  8151. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  8152. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  8153. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  8154. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  8155. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  8156. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  8157. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  8158. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  8159. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  8160. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  8161. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  8162. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8163. document.getElementById('ospf-area-modal').classList.remove('hidden');
  8164. }
  8165. function openEditOspfAreaModal(id) {
  8166. openOspfAreaModal(id);
  8167. }
  8168. function closeOspfAreaModal() {
  8169. document.getElementById('ospf-area-modal').classList.add('hidden');
  8170. }
  8171. async function submitOspfArea(e) {
  8172. if (e) e.preventDefault();
  8173. const payload = {
  8174. id: document.getElementById('modal-ospf-area-id').value,
  8175. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  8176. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  8177. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  8178. area_type: document.getElementById('modal-ospf-area-type').value,
  8179. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  8180. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  8181. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  8182. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  8183. };
  8184. try {
  8185. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  8186. method: 'POST',
  8187. headers: { 'Content-Type': 'application/json' },
  8188. body: JSON.stringify(payload)
  8189. });
  8190. if (res.ok) {
  8191. closeOspfAreaModal();
  8192. showToast('Saved', 'OSPF area saved', 'success');
  8193. loadDynamicRouting();
  8194. } else {
  8195. const err = await res.json();
  8196. showToast('Error', err.error || 'Failed to save area', 'error');
  8197. }
  8198. } catch (err) {
  8199. showToast('Error', err.message, 'error');
  8200. }
  8201. }
  8202. function applyOspfAreaForm() {
  8203. submitOspfArea(null);
  8204. }
  8205. function copyOspfArea() {
  8206. document.getElementById('modal-ospf-area-id').value = '';
  8207. document.getElementById('modal-ospf-area-name').value += '-copy';
  8208. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  8209. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  8210. }
  8211. async function deleteCurrentOspfArea() {
  8212. const id = document.getElementById('modal-ospf-area-id').value;
  8213. if (!id) return;
  8214. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  8215. try {
  8216. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8217. if (res.ok) {
  8218. closeOspfAreaModal();
  8219. showToast('Removed', 'OSPF area deleted', 'success');
  8220. loadDynamicRouting();
  8221. }
  8222. } catch (err) {
  8223. showToast('Error', err.message, 'error');
  8224. }
  8225. }
  8226. async function enableSelectedOspfArea() {
  8227. const id = state.selectedOspfRow?.areas;
  8228. if (!id) return;
  8229. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  8230. method: 'POST',
  8231. headers: { 'Content-Type': 'application/json' },
  8232. body: JSON.stringify({ disabled: false })
  8233. });
  8234. loadDynamicRouting();
  8235. }
  8236. async function disableSelectedOspfArea() {
  8237. const id = state.selectedOspfRow?.areas;
  8238. if (!id) return;
  8239. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  8240. method: 'POST',
  8241. headers: { 'Content-Type': 'application/json' },
  8242. body: JSON.stringify({ disabled: true })
  8243. });
  8244. loadDynamicRouting();
  8245. }
  8246. async function removeSelectedOspfArea() {
  8247. const id = state.selectedOspfRow?.areas;
  8248. if (!id) return;
  8249. if (!confirm('Delete selected OSPF area?')) return;
  8250. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8251. loadDynamicRouting();
  8252. }
  8253. async function promptCommentOspfArea() {
  8254. const id = state.selectedOspfRow?.areas;
  8255. if (!id) return;
  8256. const area = (state.ospfAreas || []).find(a => a.id === id);
  8257. if (!area) return;
  8258. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  8259. if (comment === null) return;
  8260. area.comment = comment;
  8261. await fetch(`${API_BASE}/routing/ospf/areas`, {
  8262. method: 'POST',
  8263. headers: { 'Content-Type': 'application/json' },
  8264. body: JSON.stringify(area)
  8265. });
  8266. loadDynamicRouting();
  8267. }
  8268. // --- 3. OSPF AREA RANGE ---
  8269. function populateAreaRangeDropdowns() {
  8270. const select = document.getElementById('modal-ospf-range-area');
  8271. if (select) {
  8272. const cur = select.value;
  8273. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8274. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8275. if (cur) select.value = cur;
  8276. }
  8277. }
  8278. function openOspfAreaRangeModal(id = null) {
  8279. const isEdit = !!id;
  8280. populateAreaRangeDropdowns();
  8281. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  8282. id: '',
  8283. area: 'Default',
  8284. prefix: '',
  8285. cost: 1,
  8286. advertise: true,
  8287. disabled: false,
  8288. comment: ''
  8289. };
  8290. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  8291. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  8292. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  8293. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  8294. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  8295. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  8296. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  8297. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  8298. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  8299. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8300. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  8301. }
  8302. function openEditOspfAreaRangeModal(id) {
  8303. openOspfAreaRangeModal(id);
  8304. }
  8305. function closeOspfAreaRangeModal() {
  8306. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  8307. }
  8308. async function submitOspfAreaRange(e) {
  8309. if (e) e.preventDefault();
  8310. const payload = {
  8311. id: document.getElementById('modal-ospf-range-id').value,
  8312. area: document.getElementById('modal-ospf-range-area').value,
  8313. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  8314. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  8315. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  8316. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  8317. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  8318. };
  8319. try {
  8320. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  8321. method: 'POST',
  8322. headers: { 'Content-Type': 'application/json' },
  8323. body: JSON.stringify(payload)
  8324. });
  8325. if (res.ok) {
  8326. closeOspfAreaRangeModal();
  8327. showToast('Saved', 'Area range saved', 'success');
  8328. loadDynamicRouting();
  8329. } else {
  8330. const err = await res.json();
  8331. showToast('Error', err.error || 'Failed to save area range', 'error');
  8332. }
  8333. } catch (err) {
  8334. showToast('Error', err.message, 'error');
  8335. }
  8336. }
  8337. function applyOspfAreaRangeForm() {
  8338. submitOspfAreaRange(null);
  8339. }
  8340. async function deleteCurrentOspfAreaRange() {
  8341. const id = document.getElementById('modal-ospf-range-id').value;
  8342. if (!id) return;
  8343. if (!confirm('Delete this area range?')) return;
  8344. try {
  8345. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8346. closeOspfAreaRangeModal();
  8347. showToast('Removed', 'Area range removed', 'success');
  8348. loadDynamicRouting();
  8349. } catch (err) {
  8350. showToast('Error', err.message, 'error');
  8351. }
  8352. }
  8353. async function enableSelectedOspfAreaRange() {
  8354. const id = state.selectedOspfRow?.['area-ranges'];
  8355. if (!id) return;
  8356. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8357. if (!r) return;
  8358. r.disabled = false;
  8359. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8360. loadDynamicRouting();
  8361. }
  8362. async function disableSelectedOspfAreaRange() {
  8363. const id = state.selectedOspfRow?.['area-ranges'];
  8364. if (!id) return;
  8365. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8366. if (!r) return;
  8367. r.disabled = true;
  8368. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8369. loadDynamicRouting();
  8370. }
  8371. async function removeSelectedOspfAreaRange() {
  8372. const id = state.selectedOspfRow?.['area-ranges'];
  8373. if (!id) return;
  8374. if (!confirm('Delete selected area range?')) return;
  8375. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8376. loadDynamicRouting();
  8377. }
  8378. async function promptCommentOspfAreaRange() {
  8379. const id = state.selectedOspfRow?.['area-ranges'];
  8380. if (!id) return;
  8381. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8382. if (!r) return;
  8383. const comment = prompt('Enter comment for area range:', r.comment || '');
  8384. if (comment === null) return;
  8385. r.comment = comment;
  8386. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8387. loadDynamicRouting();
  8388. }
  8389. // --- 4. OSPF INTERFACE TEMPLATE ---
  8390. function switchOspfTemplateTab(tab) {
  8391. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  8392. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  8393. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  8394. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  8395. if (tab === 'general') {
  8396. if (tabGen) tabGen.classList.remove('hidden');
  8397. if (tabAuth) tabAuth.classList.add('hidden');
  8398. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  8399. 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';
  8400. } else {
  8401. if (tabGen) tabGen.classList.add('hidden');
  8402. if (tabAuth) tabAuth.classList.remove('hidden');
  8403. 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';
  8404. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  8405. }
  8406. }
  8407. function populateTemplateAreaDropdowns() {
  8408. const select = document.getElementById('modal-ospf-tmpl-area');
  8409. if (select) {
  8410. const cur = select.value;
  8411. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8412. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8413. if (cur) select.value = cur;
  8414. }
  8415. }
  8416. function openOspfTemplateModal(id = null) {
  8417. const isEdit = !!id;
  8418. populateTemplateAreaDropdowns();
  8419. switchOspfTemplateTab('general');
  8420. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  8421. id: '',
  8422. interfaces: '',
  8423. area: 'Default',
  8424. networks: '',
  8425. network_type: 'broadcast',
  8426. cost: 1,
  8427. priority: 128,
  8428. passive: false,
  8429. hello_interval: 10,
  8430. dead_interval: 40,
  8431. auth: 'none',
  8432. auth_key: '',
  8433. disabled: false,
  8434. comment: ''
  8435. };
  8436. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  8437. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  8438. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  8439. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  8440. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  8441. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  8442. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  8443. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  8444. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  8445. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  8446. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  8447. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  8448. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  8449. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  8450. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  8451. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  8452. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8453. document.getElementById('ospf-template-modal').classList.remove('hidden');
  8454. }
  8455. function openEditOspfTemplateModal(id) {
  8456. openOspfTemplateModal(id);
  8457. }
  8458. function closeOspfTemplateModal() {
  8459. document.getElementById('ospf-template-modal').classList.add('hidden');
  8460. }
  8461. async function submitOspfTemplate(e) {
  8462. if (e) e.preventDefault();
  8463. const payload = {
  8464. id: document.getElementById('modal-ospf-tmpl-id').value,
  8465. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  8466. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  8467. area: document.getElementById('modal-ospf-tmpl-area').value,
  8468. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  8469. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  8470. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  8471. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  8472. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  8473. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  8474. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  8475. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  8476. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  8477. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  8478. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  8479. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  8480. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  8481. };
  8482. try {
  8483. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  8484. method: 'POST',
  8485. headers: { 'Content-Type': 'application/json' },
  8486. body: JSON.stringify(payload)
  8487. });
  8488. if (res.ok) {
  8489. closeOspfTemplateModal();
  8490. showToast('Saved', 'Interface template saved', 'success');
  8491. loadDynamicRouting();
  8492. } else {
  8493. const err = await res.json();
  8494. showToast('Error', err.error || 'Failed to save interface template', 'error');
  8495. }
  8496. } catch (err) {
  8497. showToast('Error', err.message, 'error');
  8498. }
  8499. }
  8500. function applyOspfTemplateForm() {
  8501. submitOspfTemplate(null);
  8502. }
  8503. function copyOspfTemplate() {
  8504. document.getElementById('modal-ospf-tmpl-id').value = '';
  8505. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  8506. showToast('Copied', 'Duplicated as new template', 'info');
  8507. }
  8508. async function deleteCurrentOspfTemplate() {
  8509. const id = document.getElementById('modal-ospf-tmpl-id').value;
  8510. if (!id) return;
  8511. if (!confirm('Delete this interface template?')) return;
  8512. try {
  8513. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8514. closeOspfTemplateModal();
  8515. showToast('Removed', 'Interface template deleted', 'success');
  8516. loadDynamicRouting();
  8517. } catch (err) {
  8518. showToast('Error', err.message, 'error');
  8519. }
  8520. }
  8521. async function enableSelectedOspfTemplate() {
  8522. const id = state.selectedOspfRow?.templates;
  8523. if (!id) return;
  8524. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8525. method: 'POST',
  8526. headers: { 'Content-Type': 'application/json' },
  8527. body: JSON.stringify({ disabled: false })
  8528. });
  8529. loadDynamicRouting();
  8530. }
  8531. async function disableSelectedOspfTemplate() {
  8532. const id = state.selectedOspfRow?.templates;
  8533. if (!id) return;
  8534. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8535. method: 'POST',
  8536. headers: { 'Content-Type': 'application/json' },
  8537. body: JSON.stringify({ disabled: true })
  8538. });
  8539. loadDynamicRouting();
  8540. }
  8541. async function removeSelectedOspfTemplate() {
  8542. const id = state.selectedOspfRow?.templates;
  8543. if (!id) return;
  8544. if (!confirm('Delete selected interface template?')) return;
  8545. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8546. loadDynamicRouting();
  8547. }
  8548. async function promptCommentOspfTemplate() {
  8549. const id = state.selectedOspfRow?.templates;
  8550. if (!id) return;
  8551. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  8552. if (!tmpl) return;
  8553. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  8554. if (comment === null) return;
  8555. tmpl.comment = comment;
  8556. await fetch(`${API_BASE}/routing/ospf/templates`, {
  8557. method: 'POST',
  8558. headers: { 'Content-Type': 'application/json' },
  8559. body: JSON.stringify(tmpl)
  8560. });
  8561. loadDynamicRouting();
  8562. }
  8563. // --- 5. OSPF STATIC NEIGHBOR ---
  8564. function populateStaticNbrAreaDropdowns() {
  8565. const select = document.getElementById('modal-ospf-snbr-area');
  8566. if (select) {
  8567. const cur = select.value;
  8568. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8569. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8570. if (cur) select.value = cur;
  8571. }
  8572. }
  8573. function openOspfStaticNbrModal(id = null) {
  8574. const isEdit = !!id;
  8575. populateStaticNbrAreaDropdowns();
  8576. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  8577. id: '',
  8578. address: '',
  8579. area: 'Default',
  8580. poll_interval: 120,
  8581. cost: 1,
  8582. disabled: false,
  8583. comment: ''
  8584. };
  8585. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  8586. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  8587. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  8588. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  8589. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  8590. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  8591. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  8592. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  8593. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  8594. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8595. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  8596. }
  8597. function openEditOspfStaticNbrModal(id) {
  8598. openOspfStaticNbrModal(id);
  8599. }
  8600. function closeOspfStaticNbrModal() {
  8601. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  8602. }
  8603. async function submitOspfStaticNbr(e) {
  8604. if (e) e.preventDefault();
  8605. const payload = {
  8606. id: document.getElementById('modal-ospf-snbr-id').value,
  8607. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  8608. area: document.getElementById('modal-ospf-snbr-area').value,
  8609. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  8610. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  8611. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  8612. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  8613. };
  8614. try {
  8615. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  8616. method: 'POST',
  8617. headers: { 'Content-Type': 'application/json' },
  8618. body: JSON.stringify(payload)
  8619. });
  8620. if (res.ok) {
  8621. closeOspfStaticNbrModal();
  8622. showToast('Saved', 'Static neighbor saved', 'success');
  8623. loadDynamicRouting();
  8624. } else {
  8625. const err = await res.json();
  8626. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  8627. }
  8628. } catch (err) {
  8629. showToast('Error', err.message, 'error');
  8630. }
  8631. }
  8632. function applyOspfStaticNbrForm() {
  8633. submitOspfStaticNbr(null);
  8634. }
  8635. async function deleteCurrentOspfStaticNbr() {
  8636. const id = document.getElementById('modal-ospf-snbr-id').value;
  8637. if (!id) return;
  8638. if (!confirm('Delete this static neighbor?')) return;
  8639. try {
  8640. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8641. closeOspfStaticNbrModal();
  8642. showToast('Removed', 'Static neighbor removed', 'success');
  8643. loadDynamicRouting();
  8644. } catch (err) {
  8645. showToast('Error', err.message, 'error');
  8646. }
  8647. }
  8648. async function enableSelectedOspfStaticNbr() {
  8649. const id = state.selectedOspfRow?.['static-nbrs'];
  8650. if (!id) return;
  8651. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8652. if (!n) return;
  8653. n.disabled = false;
  8654. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8655. loadDynamicRouting();
  8656. }
  8657. async function disableSelectedOspfStaticNbr() {
  8658. const id = state.selectedOspfRow?.['static-nbrs'];
  8659. if (!id) return;
  8660. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8661. if (!n) return;
  8662. n.disabled = true;
  8663. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8664. loadDynamicRouting();
  8665. }
  8666. async function removeSelectedOspfStaticNbr() {
  8667. const id = state.selectedOspfRow?.['static-nbrs'];
  8668. if (!id) return;
  8669. if (!confirm('Delete selected static neighbor?')) return;
  8670. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8671. loadDynamicRouting();
  8672. }
  8673. async function promptCommentOspfStaticNbr() {
  8674. const id = state.selectedOspfRow?.['static-nbrs'];
  8675. if (!id) return;
  8676. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8677. if (!n) return;
  8678. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  8679. if (comment === null) return;
  8680. n.comment = comment;
  8681. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8682. loadDynamicRouting();
  8683. }
  8684. // Backward-compat aliases
  8685. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  8686. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  8687. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  8688. function submitOspfInterface(e) { submitOspfTemplate(e); }
  8689. function deleteOspfInterface(id) {
  8690. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  8691. }
  8692. function toggleOspfInterfaceState(id, disabled) {
  8693. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8694. method: 'POST',
  8695. headers: { 'Content-Type': 'application/json' },
  8696. body: JSON.stringify({ disabled })
  8697. }).then(() => loadDynamicRouting());
  8698. }
  8699. function openAddOspfAreaModal() { openOspfAreaModal(); }
  8700. function deleteOspfArea(id) {
  8701. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  8702. }
  8703. // ============================================================================
  8704. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  8705. // ============================================================================
  8706. function switchBridgeSubTab(tab) {
  8707. state.bridgeSubTab = tab;
  8708. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  8709. tabs.forEach(t => {
  8710. const panel = document.getElementById(`bridge-subtab-${t}`);
  8711. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  8712. if (panel) {
  8713. if (t === tab) panel.classList.remove('hidden');
  8714. else panel.classList.add('hidden');
  8715. }
  8716. if (btn) {
  8717. if (t === tab) {
  8718. 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';
  8719. } else {
  8720. 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';
  8721. }
  8722. }
  8723. });
  8724. const addBtn = document.getElementById('bridge-top-action-btn');
  8725. if (addBtn) {
  8726. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  8727. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  8728. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  8729. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  8730. }
  8731. if (tab === 'hosts') loadBridgeHosts();
  8732. setTimeout(initTableSorting, 50);
  8733. }
  8734. function openCurrentBridgeModal() {
  8735. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  8736. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  8737. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  8738. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  8739. }
  8740. async function loadBridge() {
  8741. try {
  8742. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  8743. fetch(`${API_BASE}/bridge/bridges`),
  8744. fetch(`${API_BASE}/bridge/ports`),
  8745. fetch(`${API_BASE}/bridge/vlans`),
  8746. fetch(`${API_BASE}/bridge/summary`),
  8747. fetch(`${API_BASE}/vpn/eoip`),
  8748. fetch(`${API_BASE}/vlans`)
  8749. ]);
  8750. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  8751. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  8752. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  8753. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  8754. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  8755. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  8756. // Badges & Stats
  8757. const bBridges = document.getElementById('bridge-badge-bridges');
  8758. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  8759. const bPorts = document.getElementById('bridge-badge-ports');
  8760. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  8761. const bVlans = document.getElementById('bridge-badge-vlans');
  8762. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  8763. const bHosts = document.getElementById('bridge-badge-hosts');
  8764. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  8765. const sBr = document.getElementById('bridge-stat-bridges');
  8766. if (sBr) sBr.innerText = (state.bridges || []).length;
  8767. const sPorts = document.getElementById('bridge-stat-ports');
  8768. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  8769. const sHosts = document.getElementById('bridge-stat-hosts');
  8770. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  8771. renderBridges();
  8772. renderBridgePorts();
  8773. renderBridgeVLANs();
  8774. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  8775. } catch (err) {
  8776. console.error('Failed to load bridge subsystem:', err);
  8777. }
  8778. }
  8779. // ----------------- Bridges -----------------
  8780. function renderBridges() {
  8781. const tbody = document.getElementById('bridge-table-body');
  8782. const empty = document.getElementById('bridge-empty-bridges');
  8783. const countBadge = document.getElementById('bridge-count-badge');
  8784. if (!tbody) return;
  8785. tbody.innerHTML = '';
  8786. const bridges = state.bridges || [];
  8787. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  8788. if (bridges.length === 0) {
  8789. empty?.classList.remove('hidden');
  8790. return;
  8791. }
  8792. empty?.classList.add('hidden');
  8793. bridges.forEach((b, idx) => {
  8794. const tr = document.createElement('tr');
  8795. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  8796. // Format IP addresses pill list
  8797. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  8798. if (b.ip_addresses && b.ip_addresses.length > 0) {
  8799. ipsHtml = b.ip_addresses.map(ip => `
  8800. <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">
  8801. <span>${ip}</span>
  8802. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  8803. </span>
  8804. `).join(' ');
  8805. }
  8806. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  8807. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  8808. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  8809. tr.innerHTML = `
  8810. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  8811. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  8812. <td class="py-2.5 px-3 font-bold text-white text-sm">
  8813. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  8814. </td>
  8815. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  8816. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  8817. <td class="py-2.5 px-3">
  8818. <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>
  8819. </td>
  8820. <td class="py-2.5 px-3 text-center">
  8821. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  8822. </td>
  8823. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  8824. <td class="py-2.5 px-3">
  8825. <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>
  8826. </td>
  8827. <td class="py-2.5 px-3">
  8828. <div class="flex items-center gap-1.5 flex-wrap">
  8829. ${ipsHtml}
  8830. <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>
  8831. </div>
  8832. </td>
  8833. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  8834. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  8835. </td>
  8836. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  8837. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8838. <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>
  8839. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8840. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  8841. </td>
  8842. `;
  8843. tbody.appendChild(tr);
  8844. });
  8845. }
  8846. function openAddBridgeModal() {
  8847. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  8848. document.getElementById('bridge-modal-id').value = '';
  8849. document.getElementById('bridge-modal-name').value = 'bridge1';
  8850. document.getElementById('bridge-modal-name').disabled = false;
  8851. document.getElementById('bridge-modal-mtu').value = '1500';
  8852. document.getElementById('bridge-modal-mac').value = '';
  8853. document.getElementById('bridge-modal-stp').value = 'rstp';
  8854. document.getElementById('bridge-modal-priority').value = '32768';
  8855. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  8856. document.getElementById('bridge-modal-pvid').value = '1';
  8857. document.getElementById('bridge-modal-fastforward').checked = true;
  8858. document.getElementById('bridge-modal-comment').value = '';
  8859. document.getElementById('bridge-modal-disabled').checked = false;
  8860. toggleBridgeModalVlanFiltering();
  8861. document.getElementById('bridge-modal').classList.remove('hidden');
  8862. }
  8863. function openEditBridgeModal(id) {
  8864. const b = (state.bridges || []).find(x => x.id === id);
  8865. if (!b) return;
  8866. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  8867. document.getElementById('bridge-modal-id').value = b.id;
  8868. document.getElementById('bridge-modal-name').value = b.name;
  8869. document.getElementById('bridge-modal-name').disabled = true;
  8870. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  8871. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  8872. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  8873. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  8874. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  8875. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  8876. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  8877. document.getElementById('bridge-modal-comment').value = b.comment || '';
  8878. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  8879. toggleBridgeModalVlanFiltering();
  8880. document.getElementById('bridge-modal').classList.remove('hidden');
  8881. }
  8882. function closeBridgeModal() {
  8883. document.getElementById('bridge-modal').classList.add('hidden');
  8884. }
  8885. function toggleBridgeModalVlanFiltering() {
  8886. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  8887. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  8888. if (pvidBox) {
  8889. if (chk) pvidBox.classList.remove('opacity-40');
  8890. else pvidBox.classList.add('opacity-40');
  8891. }
  8892. }
  8893. async function submitSaveBridge(e) {
  8894. e.preventDefault();
  8895. const id = document.getElementById('bridge-modal-id').value;
  8896. const name = document.getElementById('bridge-modal-name').value.trim();
  8897. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  8898. const mac = document.getElementById('bridge-modal-mac').value.trim();
  8899. const stp = document.getElementById('bridge-modal-stp').value;
  8900. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  8901. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  8902. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  8903. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  8904. const comment = document.getElementById('bridge-modal-comment').value.trim();
  8905. const disabled = document.getElementById('bridge-modal-disabled').checked;
  8906. try {
  8907. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  8908. method: 'POST',
  8909. headers: { 'Content-Type': 'application/json' },
  8910. body: JSON.stringify({
  8911. id,
  8912. name,
  8913. mtu,
  8914. mac_address: mac,
  8915. stp,
  8916. priority,
  8917. vlan_filtering: vlanFiltering,
  8918. pvid,
  8919. fast_forward: fastForward,
  8920. comment,
  8921. disabled
  8922. })
  8923. });
  8924. if (res.ok) {
  8925. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  8926. closeBridgeModal();
  8927. loadBridge();
  8928. fetchData(false);
  8929. } else {
  8930. const err = await res.json();
  8931. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  8932. }
  8933. } catch (err) {
  8934. showToast('Error', err.message, 'error');
  8935. }
  8936. }
  8937. async function toggleBridgeState(id, disabled) {
  8938. try {
  8939. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  8940. method: 'POST',
  8941. headers: { 'Content-Type': 'application/json' },
  8942. body: JSON.stringify({ disabled })
  8943. });
  8944. if (res.ok) {
  8945. loadBridge();
  8946. fetchData(false);
  8947. }
  8948. } catch (err) {
  8949. showToast('Error', err.message, 'error');
  8950. }
  8951. }
  8952. async function deleteBridge(id) {
  8953. const b = (state.bridges || []).find(x => x.id === id);
  8954. const name = b ? b.name : id;
  8955. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  8956. try {
  8957. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8958. if (res.ok) {
  8959. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  8960. loadBridge();
  8961. fetchData(false);
  8962. } else {
  8963. const err = await res.json();
  8964. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  8965. }
  8966. } catch (err) {
  8967. showToast('Error', err.message, 'error');
  8968. }
  8969. }
  8970. // ----------------- Bridge IP Assignments -----------------
  8971. function openAddBridgeIPModal(id, name) {
  8972. document.getElementById('bridge-ip-modal-id').value = id;
  8973. document.getElementById('bridge-ip-modal-sub').innerText = name;
  8974. document.getElementById('bridge-ip-modal-cidr').value = '';
  8975. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  8976. }
  8977. function closeBridgeIPModal() {
  8978. document.getElementById('bridge-ip-modal').classList.add('hidden');
  8979. }
  8980. async function submitAddBridgeIP(e) {
  8981. e.preventDefault();
  8982. const id = document.getElementById('bridge-ip-modal-id').value;
  8983. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  8984. try {
  8985. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  8986. method: 'POST',
  8987. headers: { 'Content-Type': 'application/json' },
  8988. body: JSON.stringify({ ip })
  8989. });
  8990. if (res.ok) {
  8991. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  8992. closeBridgeIPModal();
  8993. loadBridge();
  8994. fetchData(false);
  8995. } else {
  8996. const err = await res.json();
  8997. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  8998. }
  8999. } catch (err) {
  9000. showToast('Error', err.message, 'error');
  9001. }
  9002. }
  9003. async function deleteBridgeIP(id, ip) {
  9004. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  9005. try {
  9006. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9007. method: 'DELETE',
  9008. headers: { 'Content-Type': 'application/json' },
  9009. body: JSON.stringify({ ip })
  9010. });
  9011. if (res.ok) {
  9012. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  9013. loadBridge();
  9014. fetchData(false);
  9015. }
  9016. } catch (err) {
  9017. showToast('Error', err.message, 'error');
  9018. }
  9019. }
  9020. // ----------------- Bridge Ports -----------------
  9021. function renderBridgePorts() {
  9022. const tbody = document.getElementById('bridge-ports-table-body');
  9023. const empty = document.getElementById('bridge-empty-ports');
  9024. const countBadge = document.getElementById('bridge-ports-count-badge');
  9025. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  9026. if (!tbody) return;
  9027. tbody.innerHTML = '';
  9028. // Update filter select
  9029. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  9030. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  9031. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  9032. if (ports.length === 0) {
  9033. empty?.classList.remove('hidden');
  9034. return;
  9035. }
  9036. empty?.classList.add('hidden');
  9037. ports.forEach((p, idx) => {
  9038. const tr = document.createElement('tr');
  9039. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  9040. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9041. tr.innerHTML = `
  9042. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9043. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9044. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9045. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  9046. </td>
  9047. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  9048. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  9049. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  9050. <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>
  9051. <td class="py-2.5 px-3">
  9052. ${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>'}
  9053. </td>
  9054. <td class="py-2.5 px-3">
  9055. <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>
  9056. </td>
  9057. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  9058. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9059. <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>
  9060. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9061. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9062. </td>
  9063. `;
  9064. tbody.appendChild(tr);
  9065. });
  9066. }
  9067. function openAddBridgePortModal() {
  9068. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  9069. document.getElementById('bridge-port-modal-id').value = '';
  9070. populateBridgeSelect('bridge-port-modal-bridge');
  9071. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  9072. document.getElementById('bridge-port-modal-pvid').value = '1';
  9073. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  9074. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  9075. document.getElementById('bridge-port-modal-horizon').value = '0';
  9076. document.getElementById('bridge-port-modal-pathcost').value = '10';
  9077. document.getElementById('bridge-port-modal-priority').value = '128';
  9078. document.getElementById('bridge-port-modal-learn').checked = true;
  9079. document.getElementById('bridge-port-modal-comment').value = '';
  9080. document.getElementById('bridge-port-modal-disabled').checked = false;
  9081. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9082. }
  9083. function openEditBridgePortModal(id) {
  9084. const p = (state.bridgePorts || []).find(x => x.id === id);
  9085. if (!p) return;
  9086. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  9087. document.getElementById('bridge-port-modal-id').value = p.id;
  9088. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  9089. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  9090. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  9091. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  9092. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  9093. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  9094. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  9095. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  9096. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  9097. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  9098. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  9099. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9100. }
  9101. function closeBridgePortModal() {
  9102. document.getElementById('bridge-port-modal').classList.add('hidden');
  9103. }
  9104. async function submitSaveBridgePort(e) {
  9105. e.preventDefault();
  9106. const id = document.getElementById('bridge-port-modal-id').value;
  9107. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  9108. const iface = document.getElementById('bridge-port-modal-interface').value;
  9109. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  9110. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  9111. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  9112. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  9113. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  9114. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  9115. const learn = document.getElementById('bridge-port-modal-learn').checked;
  9116. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  9117. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  9118. try {
  9119. const res = await fetch(`${API_BASE}/bridge/ports`, {
  9120. method: 'POST',
  9121. headers: { 'Content-Type': 'application/json' },
  9122. body: JSON.stringify({
  9123. id,
  9124. bridge,
  9125. interface: iface,
  9126. pvid,
  9127. frame_types: frameTypes,
  9128. ingress_filtering: ingressFiltering,
  9129. horizon,
  9130. path_cost: pathCost,
  9131. priority,
  9132. learn,
  9133. comment,
  9134. disabled
  9135. })
  9136. });
  9137. if (res.ok) {
  9138. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  9139. closeBridgePortModal();
  9140. loadBridge();
  9141. fetchData(false);
  9142. } else {
  9143. const err = await res.json();
  9144. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  9145. }
  9146. } catch (err) {
  9147. showToast('Error', err.message, 'error');
  9148. }
  9149. }
  9150. async function toggleBridgePortState(id, disabled) {
  9151. try {
  9152. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  9153. method: 'POST',
  9154. headers: { 'Content-Type': 'application/json' },
  9155. body: JSON.stringify({ disabled })
  9156. });
  9157. if (res.ok) {
  9158. loadBridge();
  9159. fetchData(false);
  9160. }
  9161. } catch (err) {
  9162. showToast('Error', err.message, 'error');
  9163. }
  9164. }
  9165. async function deleteBridgePort(id) {
  9166. const p = (state.bridgePorts || []).find(x => x.id === id);
  9167. const iface = p ? p.interface : id;
  9168. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  9169. try {
  9170. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9171. if (res.ok) {
  9172. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  9173. loadBridge();
  9174. fetchData(false);
  9175. }
  9176. } catch (err) {
  9177. showToast('Error', err.message, 'error');
  9178. }
  9179. }
  9180. // ----------------- Bridge VLANs -----------------
  9181. function renderBridgeVLANs() {
  9182. const tbody = document.getElementById('bridge-vlans-table-body');
  9183. const empty = document.getElementById('bridge-empty-vlans');
  9184. const countBadge = document.getElementById('bridge-vlans-count-badge');
  9185. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  9186. if (!tbody) return;
  9187. tbody.innerHTML = '';
  9188. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  9189. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  9190. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  9191. if (vlans.length === 0) {
  9192. empty?.classList.remove('hidden');
  9193. return;
  9194. }
  9195. empty?.classList.add('hidden');
  9196. vlans.forEach((v, idx) => {
  9197. const tr = document.createElement('tr');
  9198. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  9199. const taggedHtml = (v.tagged && v.tagged.length > 0)
  9200. ? 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(' ')
  9201. : '<span class="text-slate-600">none</span>';
  9202. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  9203. ? 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(' ')
  9204. : '<span class="text-slate-600">none</span>';
  9205. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9206. tr.innerHTML = `
  9207. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9208. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9209. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  9210. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  9211. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  9212. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  9213. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  9214. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9215. <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>
  9216. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9217. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9218. </td>
  9219. `;
  9220. tbody.appendChild(tr);
  9221. });
  9222. }
  9223. function openAddBridgeVLANModal() {
  9224. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  9225. document.getElementById('bridge-vlan-modal-id').value = '';
  9226. populateBridgeSelect('bridge-vlan-modal-bridge');
  9227. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  9228. document.getElementById('bridge-vlan-modal-comment').value = '';
  9229. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  9230. updateBridgeVlanPortCheckboxes();
  9231. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  9232. }
  9233. function openEditBridgeVLANModal(id) {
  9234. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  9235. if (!v) return;
  9236. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  9237. document.getElementById('bridge-vlan-modal-id').value = v.id;
  9238. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  9239. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  9240. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  9241. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  9242. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  9243. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  9244. }
  9245. function closeBridgeVlanModal() {
  9246. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  9247. }
  9248. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  9249. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  9250. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  9251. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  9252. if (!taggedBox || !untaggedBox) return;
  9253. // Ports belonging to the selected bridge
  9254. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  9255. if (memberPorts.length === 0) {
  9256. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  9257. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  9258. return;
  9259. }
  9260. taggedBox.innerHTML = memberPorts.map(p => `
  9261. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  9262. <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">
  9263. <span>${p.interface}</span>
  9264. </label>
  9265. `).join('');
  9266. untaggedBox.innerHTML = memberPorts.map(p => `
  9267. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  9268. <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">
  9269. <span>${p.interface}</span>
  9270. </label>
  9271. `).join('');
  9272. }
  9273. async function submitSaveBridgeVLAN(e) {
  9274. e.preventDefault();
  9275. const id = document.getElementById('bridge-vlan-modal-id').value;
  9276. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  9277. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  9278. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  9279. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  9280. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  9281. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  9282. try {
  9283. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  9284. method: 'POST',
  9285. headers: { 'Content-Type': 'application/json' },
  9286. body: JSON.stringify({
  9287. id,
  9288. bridge,
  9289. vlan_ids: vlanIDs,
  9290. tagged,
  9291. untagged,
  9292. comment,
  9293. disabled
  9294. })
  9295. });
  9296. if (res.ok) {
  9297. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  9298. closeBridgeVlanModal();
  9299. loadBridge();
  9300. } else {
  9301. const err = await res.json();
  9302. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  9303. }
  9304. } catch (err) {
  9305. showToast('Error', err.message, 'error');
  9306. }
  9307. }
  9308. async function toggleBridgeVLANState(id, disabled) {
  9309. try {
  9310. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  9311. method: 'POST',
  9312. headers: { 'Content-Type': 'application/json' },
  9313. body: JSON.stringify({ disabled })
  9314. });
  9315. if (res.ok) loadBridge();
  9316. } catch (err) {
  9317. showToast('Error', err.message, 'error');
  9318. }
  9319. }
  9320. async function deleteBridgeVLAN(id) {
  9321. if (!confirm('Delete this bridge VLAN entry?')) return;
  9322. try {
  9323. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9324. if (res.ok) {
  9325. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  9326. loadBridge();
  9327. }
  9328. } catch (err) {
  9329. showToast('Error', err.message, 'error');
  9330. }
  9331. }
  9332. // ----------------- Hosts / MAC Table -----------------
  9333. async function loadBridgeHosts() {
  9334. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  9335. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  9336. try {
  9337. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  9338. const res = await fetch(url);
  9339. if (res.ok) {
  9340. state.bridgeHosts = await res.json();
  9341. renderBridgeHosts();
  9342. }
  9343. } catch (err) {
  9344. console.error('Failed to load bridge hosts:', err);
  9345. }
  9346. }
  9347. function renderBridgeHosts() {
  9348. const tbody = document.getElementById('bridge-hosts-table-body');
  9349. const empty = document.getElementById('bridge-empty-hosts');
  9350. const countBadge = document.getElementById('bridge-hosts-count-badge');
  9351. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  9352. if (!tbody) return;
  9353. tbody.innerHTML = '';
  9354. const hosts = (state.bridgeHosts || []).filter(h => {
  9355. if (!search) return true;
  9356. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  9357. });
  9358. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  9359. if (hosts.length === 0) {
  9360. empty?.classList.remove('hidden');
  9361. return;
  9362. }
  9363. empty?.classList.add('hidden');
  9364. hosts.forEach(h => {
  9365. const tr = document.createElement('tr');
  9366. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  9367. let flagBadges = '';
  9368. 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>';
  9369. 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>';
  9370. 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>';
  9371. tr.innerHTML = `
  9372. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  9373. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  9374. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  9375. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  9376. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  9377. <td class="py-2.5 px-3">${flagBadges}</td>
  9378. `;
  9379. tbody.appendChild(tr);
  9380. });
  9381. }
  9382. async function flushBridgeHosts() {
  9383. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  9384. if (!selBridge) {
  9385. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  9386. return;
  9387. }
  9388. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  9389. try {
  9390. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  9391. method: 'POST',
  9392. headers: { 'Content-Type': 'application/json' },
  9393. body: JSON.stringify({ bridge: selBridge })
  9394. });
  9395. if (res.ok) {
  9396. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  9397. loadBridgeHosts();
  9398. }
  9399. } catch (err) {
  9400. showToast('Error', err.message, 'error');
  9401. }
  9402. }
  9403. // ----------------- Helpers -----------------
  9404. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  9405. const sel = document.getElementById(selectId);
  9406. if (!sel) return;
  9407. const prevVal = currentVal || sel.value;
  9408. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  9409. (state.bridges || []).forEach(b => {
  9410. const opt = document.createElement('option');
  9411. opt.value = b.name;
  9412. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  9413. if (b.name === prevVal) opt.selected = true;
  9414. sel.appendChild(opt);
  9415. });
  9416. }
  9417. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  9418. const sel = document.getElementById(selectId);
  9419. if (!sel) return;
  9420. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  9421. // 1. Physical Interfaces
  9422. const grpPhys = document.createElement('optgroup');
  9423. grpPhys.label = 'Physical Interfaces';
  9424. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  9425. const opt = document.createElement('option');
  9426. opt.value = i.name;
  9427. opt.innerText = `${i.name} (${i.role || i.type})`;
  9428. if (i.name === currentVal) opt.selected = true;
  9429. grpPhys.appendChild(opt);
  9430. });
  9431. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  9432. // 2. VLAN Sub-interfaces
  9433. const grpVlans = document.createElement('optgroup');
  9434. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  9435. (state.vlans || []).forEach(v => {
  9436. const opt = document.createElement('option');
  9437. opt.value = v.name;
  9438. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  9439. if (v.name === currentVal) opt.selected = true;
  9440. grpVlans.appendChild(opt);
  9441. });
  9442. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  9443. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  9444. const grpEoip = document.createElement('optgroup');
  9445. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  9446. (state.eoipTunnels || []).forEach(t => {
  9447. const opt = document.createElement('option');
  9448. opt.value = t.name;
  9449. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  9450. if (t.name === currentVal) opt.selected = true;
  9451. grpEoip.appendChild(opt);
  9452. });
  9453. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  9454. }
  9455. // -------------------------------------------------------------
  9456. // RouterOS v7 Routing Filters Management (/routing filter)
  9457. // -------------------------------------------------------------
  9458. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  9459. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  9460. if (!state.rfSort) state.rfSort = {};
  9461. function switchRoutingFilterTab(tab) {
  9462. state.activeRoutingFilterTab = tab;
  9463. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  9464. tabs.forEach(t => {
  9465. const btn = document.getElementById(`tab-rf-${t}`);
  9466. const content = document.getElementById(`tab-content-rf-${t}`);
  9467. if (btn) {
  9468. if (t === tab) {
  9469. 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';
  9470. } else {
  9471. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  9472. }
  9473. }
  9474. if (content) {
  9475. if (t === tab) content.classList.remove('hidden');
  9476. else content.classList.add('hidden');
  9477. }
  9478. });
  9479. const chainContainer = document.getElementById('rf-chain-filter-container');
  9480. if (chainContainer) {
  9481. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  9482. else chainContainer.classList.add('hidden');
  9483. }
  9484. renderRoutingFilters();
  9485. }
  9486. function selectFilterRow(tab, id) {
  9487. if (state.selectedFilterRow[tab] === id) {
  9488. delete state.selectedFilterRow[tab];
  9489. } else {
  9490. state.selectedFilterRow[tab] = id;
  9491. }
  9492. if (tab === 'rules') renderRoutingFilterRules();
  9493. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  9494. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  9495. else if (tab === 'as-lists') renderRoutingFilterASLists();
  9496. }
  9497. function openRoutingFilterNewModal() {
  9498. const tab = state.activeRoutingFilterTab || 'rules';
  9499. if (tab === 'rules') openAddRoutingFilterModal();
  9500. else if (tab === 'select-rules') openAddSelectRuleModal();
  9501. else if (tab === 'community-lists') openAddCommunityListModal();
  9502. else if (tab === 'as-lists') openAddASListModal();
  9503. }
  9504. function toggleSelectedRoutingFilter(disabled) {
  9505. const tab = state.activeRoutingFilterTab || 'rules';
  9506. const id = state.selectedFilterRow[tab];
  9507. if (!id) {
  9508. showToast('Select Row', 'Please click on a row to select it first', 'info');
  9509. return;
  9510. }
  9511. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  9512. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  9513. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  9514. else if (tab === 'as-lists') toggleASListState(id, disabled);
  9515. }
  9516. function removeSelectedRoutingFilter() {
  9517. const tab = state.activeRoutingFilterTab || 'rules';
  9518. const id = state.selectedFilterRow[tab];
  9519. if (!id) {
  9520. showToast('Select Row', 'Please click on a row to select it first', 'info');
  9521. return;
  9522. }
  9523. if (tab === 'rules') deleteRoutingFilter(id);
  9524. else if (tab === 'select-rules') deleteSelectRule(id);
  9525. else if (tab === 'community-lists') deleteCommunityList(id);
  9526. else if (tab === 'as-lists') deleteASList(id);
  9527. }
  9528. function searchRoutingFilters(q) {
  9529. state.rfSearchQuery = (q || '').trim().toLowerCase();
  9530. renderRoutingFilters();
  9531. }
  9532. function sortFilterTable(tab, col) {
  9533. if (!state.rfSort) state.rfSort = {};
  9534. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  9535. if (state.rfSort[tab].col === col) {
  9536. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  9537. } else {
  9538. state.rfSort[tab].col = col;
  9539. state.rfSort[tab].asc = true;
  9540. }
  9541. const asc = state.rfSort[tab].asc;
  9542. let list = [];
  9543. if (tab === 'rules') list = state.routingFilters || [];
  9544. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  9545. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  9546. else if (tab === 'as-lists') list = state.routingASLists || [];
  9547. list.sort((a, b) => {
  9548. let valA = a[col] ?? '';
  9549. let valB = b[col] ?? '';
  9550. if (col === 'flags') {
  9551. valA = a.disabled ? 'X' : 'A';
  9552. valB = b.disabled ? 'X' : 'A';
  9553. }
  9554. if (typeof valA === 'number' && typeof valB === 'number') {
  9555. return asc ? valA - valB : valB - valA;
  9556. }
  9557. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  9558. });
  9559. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  9560. allCols.forEach(c => {
  9561. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  9562. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  9563. });
  9564. if (tab === 'rules') renderRoutingFilterRules();
  9565. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  9566. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  9567. else if (tab === 'as-lists') renderRoutingFilterASLists();
  9568. }
  9569. function renderRoutingFilters() {
  9570. const navBadge = document.getElementById('badge-filters-count');
  9571. const allRules = state.routingFilters || [];
  9572. if (navBadge) navBadge.innerText = allRules.length;
  9573. // Populate chain filter select options and datalist
  9574. const chainSelect = document.getElementById('routing-filter-chain-select');
  9575. const chainDatalist = document.getElementById('dl-routing-chains');
  9576. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  9577. if (chainSelect) {
  9578. const currentVal = state.filterChainSelected || 'all';
  9579. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  9580. uniqueChains.map(ch => {
  9581. const count = allRules.filter(r => r.chain === ch).length;
  9582. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  9583. }).join('');
  9584. chainSelect.value = currentVal;
  9585. }
  9586. if (chainDatalist) {
  9587. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  9588. }
  9589. renderRoutingFilterRules();
  9590. renderRoutingFilterSelectRules();
  9591. renderRoutingFilterCommunityLists();
  9592. renderRoutingFilterASLists();
  9593. }
  9594. function filterRoutingFiltersByChain(chain) {
  9595. state.filterChainSelected = chain;
  9596. renderRoutingFilters();
  9597. }
  9598. // -------------------------------------------------------------
  9599. // TAB 1: RULES (/routing filter rule)
  9600. // -------------------------------------------------------------
  9601. function renderRoutingFilterRules() {
  9602. const tbody = document.getElementById('routing-filter-rules-tbody');
  9603. if (!tbody) return;
  9604. const empty = document.getElementById('rf-rules-empty');
  9605. const statusCount = document.getElementById('rf-status-count');
  9606. let list = (state.routingFilters || []).slice();
  9607. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  9608. list = list.filter(r => r.chain === state.filterChainSelected);
  9609. }
  9610. const q = state.rfSearchQuery;
  9611. if (q) {
  9612. list = list.filter(r =>
  9613. (r.chain && r.chain.toLowerCase().includes(q)) ||
  9614. (r.rule && r.rule.toLowerCase().includes(q)) ||
  9615. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  9616. (r.comment && r.comment.toLowerCase().includes(q))
  9617. );
  9618. }
  9619. if (!state.rfSort?.['rules']) {
  9620. list.sort((a, b) => {
  9621. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  9622. return (a.rule_order || 0) - (b.rule_order || 0);
  9623. });
  9624. }
  9625. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  9626. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9627. }
  9628. if (list.length === 0) {
  9629. tbody.innerHTML = '';
  9630. if (empty) empty.classList.remove('hidden');
  9631. return;
  9632. }
  9633. if (empty) empty.classList.add('hidden');
  9634. tbody.innerHTML = list.map(r => {
  9635. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  9636. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  9637. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9638. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  9639. let ruleDisplay = '';
  9640. if (r.rule && r.rule.trim() !== '') {
  9641. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  9642. } else {
  9643. let conds = [];
  9644. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  9645. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  9646. let act = r.action || 'accept';
  9647. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  9648. }
  9649. return `
  9650. <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'}">
  9651. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  9652. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  9653. <td class="py-2 px-3">
  9654. <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>
  9655. </td>
  9656. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  9657. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  9658. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9659. <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>
  9660. <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>
  9661. <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'}">
  9662. ${r.disabled ? 'Enable' : 'Disable'}
  9663. </button>
  9664. <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">
  9665. Edit
  9666. </button>
  9667. <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">
  9668. ✕
  9669. </button>
  9670. </td>
  9671. </tr>
  9672. `;
  9673. }).join('');
  9674. }
  9675. // -------------------------------------------------------------
  9676. // TAB 2: SELECT RULES (/routing filter select-rule)
  9677. // -------------------------------------------------------------
  9678. function renderRoutingFilterSelectRules() {
  9679. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  9680. if (!tbody) return;
  9681. const empty = document.getElementById('rf-select-rules-empty');
  9682. const statusCount = document.getElementById('rf-status-count');
  9683. let list = (state.routingSelectRules || []).slice();
  9684. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  9685. list = list.filter(r => r.chain === state.filterChainSelected);
  9686. }
  9687. const q = state.rfSearchQuery;
  9688. if (q) {
  9689. list = list.filter(r =>
  9690. (r.chain && r.chain.toLowerCase().includes(q)) ||
  9691. (r.rule && r.rule.toLowerCase().includes(q)) ||
  9692. (r.comment && r.comment.toLowerCase().includes(q))
  9693. );
  9694. }
  9695. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  9696. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9697. }
  9698. if (list.length === 0) {
  9699. tbody.innerHTML = '';
  9700. if (empty) empty.classList.remove('hidden');
  9701. return;
  9702. }
  9703. if (empty) empty.classList.add('hidden');
  9704. tbody.innerHTML = list.map(r => {
  9705. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  9706. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9707. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9708. return `
  9709. <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'}">
  9710. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9711. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  9712. <td class="py-2 px-3">
  9713. <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>
  9714. </td>
  9715. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  9716. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  9717. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9718. <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'}">
  9719. ${r.disabled ? 'Enable' : 'Disable'}
  9720. </button>
  9721. <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">
  9722. Edit
  9723. </button>
  9724. <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">
  9725. ✕
  9726. </button>
  9727. </td>
  9728. </tr>
  9729. `;
  9730. }).join('');
  9731. }
  9732. // -------------------------------------------------------------
  9733. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  9734. // -------------------------------------------------------------
  9735. function renderRoutingFilterCommunityLists() {
  9736. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  9737. if (!tbody) return;
  9738. const empty = document.getElementById('rf-comm-lists-empty');
  9739. const statusCount = document.getElementById('rf-status-count');
  9740. let list = (state.routingCommunityLists || []).slice();
  9741. const q = state.rfSearchQuery;
  9742. if (q) {
  9743. list = list.filter(cl =>
  9744. (cl.name && cl.name.toLowerCase().includes(q)) ||
  9745. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  9746. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  9747. );
  9748. }
  9749. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  9750. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9751. }
  9752. if (list.length === 0) {
  9753. tbody.innerHTML = '';
  9754. if (empty) empty.classList.remove('hidden');
  9755. return;
  9756. }
  9757. if (empty) empty.classList.add('hidden');
  9758. tbody.innerHTML = list.map(cl => {
  9759. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  9760. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9761. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9762. const commBadges = (cl.communities || []).map(c =>
  9763. `<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>`
  9764. ).join(' ');
  9765. return `
  9766. <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'}">
  9767. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9768. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  9769. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  9770. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  9771. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  9772. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9773. <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'}">
  9774. ${cl.disabled ? 'Enable' : 'Disable'}
  9775. </button>
  9776. <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">
  9777. Edit
  9778. </button>
  9779. <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">
  9780. ✕
  9781. </button>
  9782. </td>
  9783. </tr>
  9784. `;
  9785. }).join('');
  9786. }
  9787. // -------------------------------------------------------------
  9788. // TAB 4: AS LISTS (/routing filter num-list)
  9789. // -------------------------------------------------------------
  9790. function renderRoutingFilterASLists() {
  9791. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  9792. if (!tbody) return;
  9793. const empty = document.getElementById('rf-as-lists-empty');
  9794. const statusCount = document.getElementById('rf-status-count');
  9795. let list = (state.routingASLists || []).slice();
  9796. const q = state.rfSearchQuery;
  9797. if (q) {
  9798. list = list.filter(al =>
  9799. (al.name && al.name.toLowerCase().includes(q)) ||
  9800. (al.range && al.range.toLowerCase().includes(q)) ||
  9801. (al.comment && al.comment.toLowerCase().includes(q))
  9802. );
  9803. }
  9804. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  9805. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9806. }
  9807. if (list.length === 0) {
  9808. tbody.innerHTML = '';
  9809. if (empty) empty.classList.remove('hidden');
  9810. return;
  9811. }
  9812. if (empty) empty.classList.add('hidden');
  9813. tbody.innerHTML = list.map(al => {
  9814. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  9815. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9816. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9817. return `
  9818. <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'}">
  9819. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9820. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  9821. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  9822. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  9823. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9824. <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'}">
  9825. ${al.disabled ? 'Enable' : 'Disable'}
  9826. </button>
  9827. <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">
  9828. Edit
  9829. </button>
  9830. <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">
  9831. ✕
  9832. </button>
  9833. </td>
  9834. </tr>
  9835. `;
  9836. }).join('');
  9837. }
  9838. // -------------------------------------------------------------
  9839. // SNIPPETS & WIZARD HELPERS
  9840. // -------------------------------------------------------------
  9841. function insertRuleSnippet(type) {
  9842. const textarea = document.getElementById('modal-rf-rule');
  9843. if (!textarea) return;
  9844. let snippet = '';
  9845. switch (type) {
  9846. case 'accept-default':
  9847. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  9848. break;
  9849. case 'drop-rfc1918':
  9850. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  9851. break;
  9852. case 'len-24':
  9853. snippet = 'if (dst-len > 24) { reject; }';
  9854. break;
  9855. case 'local-pref-150':
  9856. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  9857. break;
  9858. case 'as-prepend-2':
  9859. snippet = 'set bgp-path-prepend 2; accept;';
  9860. break;
  9861. case 'set-comm':
  9862. snippet = 'set bgp-communities.add 65000:100; accept;';
  9863. break;
  9864. case 'match-comm':
  9865. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  9866. break;
  9867. case 'reject-all':
  9868. snippet = 'reject;';
  9869. break;
  9870. }
  9871. if (!snippet) return;
  9872. if (!textarea.value.trim()) {
  9873. textarea.value = snippet;
  9874. } else {
  9875. textarea.value = textarea.value.trim() + '\n' + snippet;
  9876. }
  9877. }
  9878. function generateScriptFromWizard() {
  9879. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  9880. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  9881. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  9882. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  9883. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  9884. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  9885. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  9886. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  9887. const conds = [];
  9888. if (pfx) {
  9889. if (pfxLen) {
  9890. if (pfxLen.includes('-')) {
  9891. const parts = pfxLen.split('-');
  9892. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  9893. } else {
  9894. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  9895. }
  9896. } else {
  9897. conds.push(`dst in ${pfx}`);
  9898. }
  9899. }
  9900. if (proto && proto !== 'any') {
  9901. conds.push(`protocol ${proto}`);
  9902. }
  9903. if (asp) {
  9904. conds.push(`bgp-as-path "${asp}"`);
  9905. }
  9906. if (comm) {
  9907. conds.push(`bgp-communities includes ${comm}`);
  9908. }
  9909. const actions = [];
  9910. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  9911. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  9912. actions.push(`${act};`);
  9913. let code = '';
  9914. if (conds.length > 0) {
  9915. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  9916. } else {
  9917. code = actions.join(' ');
  9918. }
  9919. const textarea = document.getElementById('modal-rf-rule');
  9920. if (textarea) textarea.value = code;
  9921. }
  9922. // -------------------------------------------------------------
  9923. // MODAL CRUD: RULES (/routing filter rule)
  9924. // -------------------------------------------------------------
  9925. function openAddRoutingFilterModal(defaultChain = '') {
  9926. const form = document.getElementById('routing-filter-form');
  9927. if (form) form.reset();
  9928. const idEl = document.getElementById('modal-rf-id');
  9929. if (idEl) idEl.value = '';
  9930. const titleEl = document.getElementById('modal-rf-title');
  9931. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  9932. const chainEl = document.getElementById('modal-rf-chain');
  9933. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  9934. const orderEl = document.getElementById('modal-rf-order');
  9935. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  9936. const ruleEl = document.getElementById('modal-rf-rule');
  9937. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  9938. const disEl = document.getElementById('modal-rf-disabled');
  9939. if (disEl) disEl.checked = false;
  9940. const modal = document.getElementById('modal-routing-filter');
  9941. if (modal) modal.classList.remove('hidden');
  9942. }
  9943. function openEditRoutingFilterModal(id) {
  9944. const r = (state.routingFilters || []).find(item => item.id === id);
  9945. if (!r) return;
  9946. const idEl = document.getElementById('modal-rf-id');
  9947. if (idEl) idEl.value = r.id;
  9948. const titleEl = document.getElementById('modal-rf-title');
  9949. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  9950. const chainEl = document.getElementById('modal-rf-chain');
  9951. if (chainEl) chainEl.value = r.chain || '';
  9952. const orderEl = document.getElementById('modal-rf-order');
  9953. if (orderEl) orderEl.value = r.rule_order || 10;
  9954. const ruleEl = document.getElementById('modal-rf-rule');
  9955. if (ruleEl) {
  9956. if (r.rule) {
  9957. ruleEl.value = r.rule;
  9958. } else {
  9959. let conds = [];
  9960. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  9961. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  9962. let act = r.action || 'accept';
  9963. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  9964. }
  9965. }
  9966. const comEl = document.getElementById('modal-rf-comment');
  9967. if (comEl) comEl.value = r.comment || '';
  9968. const disEl = document.getElementById('modal-rf-disabled');
  9969. if (disEl) disEl.checked = !!r.disabled;
  9970. const modal = document.getElementById('modal-routing-filter');
  9971. if (modal) modal.classList.remove('hidden');
  9972. }
  9973. function closeRoutingFilterModal() {
  9974. const modal = document.getElementById('modal-routing-filter');
  9975. if (modal) modal.classList.add('hidden');
  9976. }
  9977. async function submitRoutingFilter(e) {
  9978. if (e) e.preventDefault();
  9979. const payload = {
  9980. id: document.getElementById('modal-rf-id').value,
  9981. chain: document.getElementById('modal-rf-chain').value.trim(),
  9982. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  9983. rule: document.getElementById('modal-rf-rule').value.trim(),
  9984. comment: document.getElementById('modal-rf-comment').value.trim(),
  9985. disabled: document.getElementById('modal-rf-disabled').checked
  9986. };
  9987. try {
  9988. const res = await fetch(`${API_BASE}/routing/filters`, {
  9989. method: 'POST',
  9990. headers: { 'Content-Type': 'application/json' },
  9991. body: JSON.stringify(payload)
  9992. });
  9993. if (res.ok) {
  9994. closeRoutingFilterModal();
  9995. showToast('Success', 'Routing filter rule saved', 'success');
  9996. loadDynamicRouting();
  9997. } else {
  9998. const err = await res.json();
  9999. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  10000. }
  10001. } catch (err) {
  10002. showToast('Error', err.message, 'error');
  10003. }
  10004. }
  10005. async function applyRoutingFilterForm() {
  10006. const payload = {
  10007. id: document.getElementById('modal-rf-id').value,
  10008. chain: document.getElementById('modal-rf-chain').value.trim(),
  10009. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10010. rule: document.getElementById('modal-rf-rule').value.trim(),
  10011. comment: document.getElementById('modal-rf-comment').value.trim(),
  10012. disabled: document.getElementById('modal-rf-disabled').checked
  10013. };
  10014. try {
  10015. const res = await fetch(`${API_BASE}/routing/filters`, {
  10016. method: 'POST',
  10017. headers: { 'Content-Type': 'application/json' },
  10018. body: JSON.stringify(payload)
  10019. });
  10020. if (res.ok) {
  10021. const data = await res.json();
  10022. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  10023. showToast('Applied', 'Routing filter configuration applied', 'success');
  10024. loadDynamicRouting();
  10025. } else {
  10026. const err = await res.json();
  10027. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  10028. }
  10029. } catch (err) {
  10030. showToast('Error', err.message, 'error');
  10031. }
  10032. }
  10033. async function moveRoutingFilterOrder(id, delta) {
  10034. const list = state.routingFilters || [];
  10035. const idx = list.findIndex(r => r.id === id);
  10036. if (idx < 0) return;
  10037. const targetIdx = idx + delta;
  10038. if (targetIdx < 0 || targetIdx >= list.length) return;
  10039. const currentOrder = list[idx].rule_order || 10;
  10040. const targetOrder = list[targetIdx].rule_order || 20;
  10041. list[idx].rule_order = targetOrder;
  10042. list[targetIdx].rule_order = currentOrder;
  10043. try {
  10044. await fetch(`${API_BASE}/routing/filters`, {
  10045. method: 'POST',
  10046. headers: { 'Content-Type': 'application/json' },
  10047. body: JSON.stringify(list[idx])
  10048. });
  10049. await fetch(`${API_BASE}/routing/filters`, {
  10050. method: 'POST',
  10051. headers: { 'Content-Type': 'application/json' },
  10052. body: JSON.stringify(list[targetIdx])
  10053. });
  10054. loadDynamicRouting();
  10055. } catch (e) {
  10056. console.error('Reorder error:', e);
  10057. }
  10058. }
  10059. async function deleteRoutingFilter(id) {
  10060. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  10061. try {
  10062. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10063. if (res.ok) {
  10064. showToast('Deleted', 'Routing filter rule removed', 'info');
  10065. loadDynamicRouting();
  10066. } else {
  10067. const err = await res.json();
  10068. showToast('Error', err.error || 'Failed to delete rule', 'error');
  10069. }
  10070. } catch (err) {
  10071. showToast('Error', err.message, 'error');
  10072. }
  10073. }
  10074. async function toggleRoutingFilterState(id, disabled) {
  10075. try {
  10076. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  10077. method: 'POST',
  10078. headers: { 'Content-Type': 'application/json' },
  10079. body: JSON.stringify({ disabled })
  10080. });
  10081. if (res.ok) {
  10082. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10083. loadDynamicRouting();
  10084. } else {
  10085. const err = await res.json();
  10086. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  10087. }
  10088. } catch (err) {
  10089. showToast('Error', err.message, 'error');
  10090. }
  10091. }
  10092. // -------------------------------------------------------------
  10093. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  10094. // -------------------------------------------------------------
  10095. function openAddSelectRuleModal() {
  10096. document.getElementById('modal-rf-sr-id').value = '';
  10097. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  10098. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  10099. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  10100. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  10101. document.getElementById('modal-rf-sr-comment').value = '';
  10102. document.getElementById('modal-rf-sr-disabled').checked = false;
  10103. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10104. }
  10105. function openEditSelectRuleModal(id) {
  10106. const r = (state.routingSelectRules || []).find(item => item.id === id);
  10107. if (!r) return;
  10108. document.getElementById('modal-rf-sr-id').value = r.id;
  10109. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  10110. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  10111. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  10112. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  10113. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  10114. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  10115. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10116. }
  10117. function closeSelectRuleModal() {
  10118. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  10119. }
  10120. async function submitSelectRule(e) {
  10121. e.preventDefault();
  10122. const payload = {
  10123. id: document.getElementById('modal-rf-sr-id').value,
  10124. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  10125. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  10126. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  10127. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  10128. disabled: document.getElementById('modal-rf-sr-disabled').checked
  10129. };
  10130. try {
  10131. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  10132. method: 'POST',
  10133. headers: { 'Content-Type': 'application/json' },
  10134. body: JSON.stringify(payload)
  10135. });
  10136. if (res.ok) {
  10137. closeSelectRuleModal();
  10138. showToast('Success', 'Select rule saved', 'success');
  10139. loadDynamicRouting();
  10140. } else {
  10141. const err = await res.json();
  10142. showToast('Error', err.error || 'Failed to save select rule', 'error');
  10143. }
  10144. } catch (err) {
  10145. showToast('Error', err.message, 'error');
  10146. }
  10147. }
  10148. async function deleteSelectRule(id) {
  10149. if (!confirm('Are you sure you want to delete this select rule?')) return;
  10150. try {
  10151. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10152. if (res.ok) {
  10153. showToast('Deleted', 'Select rule removed', 'info');
  10154. loadDynamicRouting();
  10155. } else {
  10156. const err = await res.json();
  10157. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  10158. }
  10159. } catch (err) {
  10160. showToast('Error', err.message, 'error');
  10161. }
  10162. }
  10163. async function toggleSelectRuleState(id, disabled) {
  10164. try {
  10165. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  10166. method: 'POST',
  10167. headers: { 'Content-Type': 'application/json' },
  10168. body: JSON.stringify({ disabled })
  10169. });
  10170. if (res.ok) {
  10171. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10172. loadDynamicRouting();
  10173. } else {
  10174. const err = await res.json();
  10175. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  10176. }
  10177. } catch (err) {
  10178. showToast('Error', err.message, 'error');
  10179. }
  10180. }
  10181. // -------------------------------------------------------------
  10182. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  10183. // -------------------------------------------------------------
  10184. function openAddCommunityListModal() {
  10185. document.getElementById('modal-rf-cl-id').value = '';
  10186. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  10187. document.getElementById('modal-rf-cl-name').value = '';
  10188. document.getElementById('modal-rf-cl-communities').value = '';
  10189. document.getElementById('modal-rf-cl-regexp').value = '';
  10190. document.getElementById('modal-rf-cl-comment').value = '';
  10191. document.getElementById('modal-rf-cl-disabled').checked = false;
  10192. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  10193. }
  10194. function openEditCommunityListModal(id) {
  10195. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  10196. if (!cl) return;
  10197. document.getElementById('modal-rf-cl-id').value = cl.id;
  10198. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  10199. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  10200. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  10201. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  10202. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  10203. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  10204. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  10205. }
  10206. function closeCommunityListModal() {
  10207. document.getElementById('modal-rf-community-list').classList.add('hidden');
  10208. }
  10209. async function submitCommunityList(e) {
  10210. e.preventDefault();
  10211. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  10212. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  10213. const payload = {
  10214. id: document.getElementById('modal-rf-cl-id').value,
  10215. name: document.getElementById('modal-rf-cl-name').value.trim(),
  10216. communities: comms,
  10217. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  10218. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  10219. disabled: document.getElementById('modal-rf-cl-disabled').checked
  10220. };
  10221. try {
  10222. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  10223. method: 'POST',
  10224. headers: { 'Content-Type': 'application/json' },
  10225. body: JSON.stringify(payload)
  10226. });
  10227. if (res.ok) {
  10228. closeCommunityListModal();
  10229. showToast('Success', 'Community list saved', 'success');
  10230. loadDynamicRouting();
  10231. } else {
  10232. const err = await res.json();
  10233. showToast('Error', err.error || 'Failed to save community list', 'error');
  10234. }
  10235. } catch (err) {
  10236. showToast('Error', err.message, 'error');
  10237. }
  10238. }
  10239. async function deleteCommunityList(id) {
  10240. if (!confirm('Are you sure you want to delete this community list?')) return;
  10241. try {
  10242. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10243. if (res.ok) {
  10244. showToast('Deleted', 'Community list removed', 'info');
  10245. loadDynamicRouting();
  10246. } else {
  10247. const err = await res.json();
  10248. showToast('Error', err.error || 'Failed to delete community list', 'error');
  10249. }
  10250. } catch (err) {
  10251. showToast('Error', err.message, 'error');
  10252. }
  10253. }
  10254. async function toggleCommunityListState(id, disabled) {
  10255. try {
  10256. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  10257. method: 'POST',
  10258. headers: { 'Content-Type': 'application/json' },
  10259. body: JSON.stringify({ disabled })
  10260. });
  10261. if (res.ok) {
  10262. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10263. loadDynamicRouting();
  10264. } else {
  10265. const err = await res.json();
  10266. showToast('Error', err.error || 'Failed to update community list state', 'error');
  10267. }
  10268. } catch (err) {
  10269. showToast('Error', err.message, 'error');
  10270. }
  10271. }
  10272. // -------------------------------------------------------------
  10273. // MODAL CRUD: AS LISTS (/routing filter num-list)
  10274. // -------------------------------------------------------------
  10275. function openAddASListModal() {
  10276. document.getElementById('modal-rf-al-id').value = '';
  10277. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  10278. document.getElementById('modal-rf-al-name').value = '';
  10279. document.getElementById('modal-rf-al-range').value = '';
  10280. document.getElementById('modal-rf-al-comment').value = '';
  10281. document.getElementById('modal-rf-al-disabled').checked = false;
  10282. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  10283. }
  10284. function openEditASListModal(id) {
  10285. const al = (state.routingASLists || []).find(item => item.id === id);
  10286. if (!al) return;
  10287. document.getElementById('modal-rf-al-id').value = al.id;
  10288. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  10289. document.getElementById('modal-rf-al-name').value = al.name || '';
  10290. document.getElementById('modal-rf-al-range').value = al.range || '';
  10291. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  10292. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  10293. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  10294. }
  10295. function closeASListModal() {
  10296. document.getElementById('modal-rf-as-list').classList.add('hidden');
  10297. }
  10298. async function submitASList(e) {
  10299. e.preventDefault();
  10300. const payload = {
  10301. id: document.getElementById('modal-rf-al-id').value,
  10302. name: document.getElementById('modal-rf-al-name').value.trim(),
  10303. range: document.getElementById('modal-rf-al-range').value.trim(),
  10304. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  10305. disabled: document.getElementById('modal-rf-al-disabled').checked
  10306. };
  10307. try {
  10308. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  10309. method: 'POST',
  10310. headers: { 'Content-Type': 'application/json' },
  10311. body: JSON.stringify(payload)
  10312. });
  10313. if (res.ok) {
  10314. closeASListModal();
  10315. showToast('Success', 'AS number list saved', 'success');
  10316. loadDynamicRouting();
  10317. } else {
  10318. const err = await res.json();
  10319. showToast('Error', err.error || 'Failed to save AS list', 'error');
  10320. }
  10321. } catch (err) {
  10322. showToast('Error', err.message, 'error');
  10323. }
  10324. }
  10325. async function deleteASList(id) {
  10326. if (!confirm('Are you sure you want to delete this AS list?')) return;
  10327. try {
  10328. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10329. if (res.ok) {
  10330. showToast('Deleted', 'AS list removed', 'info');
  10331. loadDynamicRouting();
  10332. } else {
  10333. const err = await res.json();
  10334. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  10335. }
  10336. } catch (err) {
  10337. showToast('Error', err.message, 'error');
  10338. }
  10339. }
  10340. async function toggleASListState(id, disabled) {
  10341. try {
  10342. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  10343. method: 'POST',
  10344. headers: { 'Content-Type': 'application/json' },
  10345. body: JSON.stringify({ disabled })
  10346. });
  10347. if (res.ok) {
  10348. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10349. loadDynamicRouting();
  10350. } else {
  10351. const err = await res.json();
  10352. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  10353. }
  10354. } catch (err) {
  10355. showToast('Error', err.message, 'error');
  10356. }
  10357. }
  10358. // ==========================================
  10359. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  10360. // ==========================================
  10361. function loadToolsView() {
  10362. populateToolsInterfaces();
  10363. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  10364. }
  10365. function populateToolsInterfaces() {
  10366. const pingSel = document.getElementById('tools-ping-iface');
  10367. const traceSel = document.getElementById('tools-tr-iface');
  10368. let opts = '<option value="">Auto (Default Route)</option>';
  10369. if (Array.isArray(state.interfaces)) {
  10370. state.interfaces.forEach(iface => {
  10371. if (iface.name) {
  10372. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  10373. }
  10374. });
  10375. }
  10376. if (pingSel) {
  10377. const cur = pingSel.value;
  10378. pingSel.innerHTML = opts;
  10379. if (cur) pingSel.value = cur;
  10380. }
  10381. if (traceSel) {
  10382. const cur = traceSel.value;
  10383. traceSel.innerHTML = opts;
  10384. if (cur) traceSel.value = cur;
  10385. }
  10386. }
  10387. function switchToolsSubTab(subTab) {
  10388. state.activeToolsSubTab = subTab;
  10389. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  10390. tabs.forEach(t => {
  10391. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  10392. const view = document.getElementById(`tools-view-${t}`);
  10393. if (btn) {
  10394. if (t === subTab) {
  10395. 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';
  10396. } else {
  10397. 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';
  10398. }
  10399. }
  10400. if (view) {
  10401. if (t === subTab) {
  10402. view.classList.remove('hidden');
  10403. } else {
  10404. view.classList.add('hidden');
  10405. }
  10406. }
  10407. });
  10408. }
  10409. function setPortPreset(port) {
  10410. const input = document.getElementById('tools-port-num');
  10411. if (input) input.value = port;
  10412. }
  10413. let pingAbortController = null;
  10414. let tracerouteAbortController = null;
  10415. function clearPingTable() {
  10416. const tbody = document.getElementById('tools-ping-tbody');
  10417. if (tbody) tbody.innerHTML = '';
  10418. const rawEl = document.getElementById('tools-ping-raw');
  10419. if (rawEl) rawEl.innerText = '';
  10420. const sentEl = document.getElementById('tools-ping-stat-sent');
  10421. if (sentEl) sentEl.innerText = '0';
  10422. const recvEl = document.getElementById('tools-ping-stat-recv');
  10423. if (recvEl) recvEl.innerText = '0';
  10424. const lossEl = document.getElementById('tools-ping-stat-loss');
  10425. if (lossEl) lossEl.innerText = '0%';
  10426. const avgEl = document.getElementById('tools-ping-stat-avg');
  10427. if (avgEl) avgEl.innerText = '0 ms';
  10428. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  10429. if (minMaxEl) minMaxEl.innerText = '-';
  10430. const badge = document.getElementById('tools-ping-status-badge');
  10431. if (badge) {
  10432. badge.className = '';
  10433. badge.innerText = '';
  10434. }
  10435. }
  10436. function clearTracerouteTable() {
  10437. const tbody = document.getElementById('tools-tr-tbody');
  10438. if (tbody) tbody.innerHTML = '';
  10439. const rawEl = document.getElementById('tools-tr-raw');
  10440. if (rawEl) rawEl.innerText = '';
  10441. const statHops = document.getElementById('tools-tr-hops-count');
  10442. if (statHops) statHops.innerText = '0 Hops';
  10443. }
  10444. function resetPingButton() {
  10445. const btn = document.getElementById('tools-ping-btn');
  10446. const btnText = document.getElementById('tools-ping-btn-text');
  10447. const spinner = document.getElementById('tools-ping-spinner');
  10448. if (btn) {
  10449. btn.disabled = false;
  10450. 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';
  10451. }
  10452. if (btnText) btnText.innerText = 'Start Ping';
  10453. if (spinner) spinner.classList.add('hidden');
  10454. }
  10455. function setPingRunningButton() {
  10456. const btn = document.getElementById('tools-ping-btn');
  10457. const btnText = document.getElementById('tools-ping-btn-text');
  10458. const spinner = document.getElementById('tools-ping-spinner');
  10459. if (btn) {
  10460. btn.disabled = false;
  10461. 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';
  10462. }
  10463. if (btnText) btnText.innerText = 'Stop Ping';
  10464. if (spinner) spinner.classList.remove('hidden');
  10465. }
  10466. function resetTracerouteButton() {
  10467. const btn = document.getElementById('tools-tr-btn');
  10468. const btnText = document.getElementById('tools-tr-btn-text');
  10469. const spinner = document.getElementById('tools-tr-spinner');
  10470. if (btn) {
  10471. btn.disabled = false;
  10472. 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';
  10473. }
  10474. if (btnText) btnText.innerText = 'Start Traceroute';
  10475. if (spinner) spinner.classList.add('hidden');
  10476. }
  10477. function setTracerouteRunningButton() {
  10478. const btn = document.getElementById('tools-tr-btn');
  10479. const btnText = document.getElementById('tools-tr-btn-text');
  10480. const spinner = document.getElementById('tools-tr-spinner');
  10481. if (btn) {
  10482. btn.disabled = false;
  10483. 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';
  10484. }
  10485. if (btnText) btnText.innerText = 'Stop Traceroute';
  10486. if (spinner) spinner.classList.remove('hidden');
  10487. }
  10488. async function executePing(e) {
  10489. if (e) e.preventDefault();
  10490. // If already running, clicking the button stops the stream!
  10491. if (pingAbortController) {
  10492. pingAbortController.abort();
  10493. pingAbortController = null;
  10494. resetPingButton();
  10495. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  10496. return;
  10497. }
  10498. const target = document.getElementById('tools-ping-target')?.value?.trim();
  10499. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  10500. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  10501. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  10502. const iface = document.getElementById('tools-ping-iface')?.value || '';
  10503. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  10504. if (!target) {
  10505. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10506. return;
  10507. }
  10508. clearPingTable();
  10509. const resCard = document.getElementById('tools-ping-results');
  10510. if (resCard) resCard.classList.remove('hidden');
  10511. pingAbortController = new AbortController();
  10512. setPingRunningButton();
  10513. try {
  10514. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  10515. method: 'POST',
  10516. headers: { 'Content-Type': 'application/json' },
  10517. body: JSON.stringify({
  10518. target,
  10519. count,
  10520. size,
  10521. timeout,
  10522. interface: iface,
  10523. dont_frag: dontFrag
  10524. }),
  10525. signal: pingAbortController.signal
  10526. });
  10527. if (!res.ok) {
  10528. const errText = await res.text();
  10529. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  10530. resetPingButton();
  10531. pingAbortController = null;
  10532. return;
  10533. }
  10534. const reader = res.body.getReader();
  10535. const decoder = new TextDecoder('utf-8');
  10536. let buffer = '';
  10537. while (true) {
  10538. const { done, value } = await reader.read();
  10539. if (done) break;
  10540. buffer += decoder.decode(value, { stream: true });
  10541. const blocks = buffer.split('\n\n');
  10542. buffer = blocks.pop() || '';
  10543. for (const block of blocks) {
  10544. const trimmed = block.trim();
  10545. if (!trimmed) continue;
  10546. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  10547. try {
  10548. const evt = JSON.parse(line);
  10549. handleLivePingEvent(evt);
  10550. } catch (parseErr) {
  10551. console.warn('Ping SSE parse error:', parseErr, line);
  10552. }
  10553. }
  10554. }
  10555. } catch (err) {
  10556. if (err.name === 'AbortError') {
  10557. // User aborted normally
  10558. } else {
  10559. showToast('Ping Error', err.message, 'error');
  10560. }
  10561. } finally {
  10562. pingAbortController = null;
  10563. resetPingButton();
  10564. }
  10565. }
  10566. function handleLivePingEvent(evt) {
  10567. const sentEl = document.getElementById('tools-ping-stat-sent');
  10568. const recvEl = document.getElementById('tools-ping-stat-recv');
  10569. const lossEl = document.getElementById('tools-ping-stat-loss');
  10570. const avgEl = document.getElementById('tools-ping-stat-avg');
  10571. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  10572. const badge = document.getElementById('tools-ping-status-badge');
  10573. const tbody = document.getElementById('tools-ping-tbody');
  10574. const rawEl = document.getElementById('tools-ping-raw');
  10575. if (evt.raw && rawEl) {
  10576. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  10577. rawEl.scrollTop = rawEl.scrollHeight;
  10578. }
  10579. if (evt.type === 'reply') {
  10580. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10581. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  10582. if (lossEl && evt.packet_loss_pct !== undefined) {
  10583. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10584. lossEl.className = evt.packet_loss_pct === 0
  10585. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  10586. : (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');
  10587. }
  10588. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  10589. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  10590. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  10591. }
  10592. if (badge) {
  10593. if (evt.packet_loss_pct === 0) {
  10594. 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';
  10595. badge.innerText = '100% OK';
  10596. } else {
  10597. 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';
  10598. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  10599. }
  10600. }
  10601. if (tbody) {
  10602. const tr = document.createElement('tr');
  10603. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  10604. tr.innerHTML = `
  10605. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  10606. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  10607. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  10608. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  10609. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  10610. <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>
  10611. `;
  10612. tbody.appendChild(tr);
  10613. }
  10614. } else if (evt.type === 'timeout') {
  10615. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10616. if (lossEl && evt.packet_loss_pct !== undefined) {
  10617. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10618. 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';
  10619. }
  10620. if (badge) {
  10621. 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';
  10622. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  10623. }
  10624. if (tbody) {
  10625. const tr = document.createElement('tr');
  10626. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  10627. tr.innerHTML = `
  10628. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  10629. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  10630. <td class="py-2 px-3 text-slate-600">--</td>
  10631. <td class="py-2 px-3 text-slate-600">--</td>
  10632. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  10633. <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>
  10634. `;
  10635. tbody.appendChild(tr);
  10636. }
  10637. } else if (evt.type === 'unreach') {
  10638. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10639. if (lossEl && evt.packet_loss_pct !== undefined) {
  10640. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10641. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  10642. }
  10643. if (badge) {
  10644. 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';
  10645. badge.innerText = 'UNREACHABLE';
  10646. }
  10647. if (tbody) {
  10648. const tr = document.createElement('tr');
  10649. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  10650. tr.innerHTML = `
  10651. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  10652. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  10653. <td class="py-2 px-3 text-slate-600">--</td>
  10654. <td class="py-2 px-3 text-slate-600">--</td>
  10655. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  10656. <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>
  10657. `;
  10658. tbody.appendChild(tr);
  10659. }
  10660. } else if (evt.type === 'stats') {
  10661. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10662. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  10663. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10664. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  10665. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  10666. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  10667. }
  10668. } else if (evt.type === 'done') {
  10669. 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');
  10670. }
  10671. }
  10672. async function executeTraceroute(e) {
  10673. if (e) e.preventDefault();
  10674. if (tracerouteAbortController) {
  10675. tracerouteAbortController.abort();
  10676. tracerouteAbortController = null;
  10677. resetTracerouteButton();
  10678. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  10679. return;
  10680. }
  10681. const target = document.getElementById('tools-tr-target')?.value?.trim();
  10682. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  10683. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  10684. const iface = document.getElementById('tools-tr-iface')?.value || '';
  10685. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  10686. if (!target) {
  10687. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10688. return;
  10689. }
  10690. clearTracerouteTable();
  10691. const resCard = document.getElementById('tools-tr-results');
  10692. if (resCard) resCard.classList.remove('hidden');
  10693. tracerouteAbortController = new AbortController();
  10694. setTracerouteRunningButton();
  10695. try {
  10696. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  10697. method: 'POST',
  10698. headers: { 'Content-Type': 'application/json' },
  10699. body: JSON.stringify({
  10700. target,
  10701. max_hops: maxHops,
  10702. protocol,
  10703. interface: iface,
  10704. resolve
  10705. }),
  10706. signal: tracerouteAbortController.signal
  10707. });
  10708. if (!res.ok) {
  10709. const errText = await res.text();
  10710. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  10711. resetTracerouteButton();
  10712. tracerouteAbortController = null;
  10713. return;
  10714. }
  10715. const reader = res.body.getReader();
  10716. const decoder = new TextDecoder('utf-8');
  10717. let buffer = '';
  10718. while (true) {
  10719. const { done, value } = await reader.read();
  10720. if (done) break;
  10721. buffer += decoder.decode(value, { stream: true });
  10722. const blocks = buffer.split('\n\n');
  10723. buffer = blocks.pop() || '';
  10724. for (const block of blocks) {
  10725. const trimmed = block.trim();
  10726. if (!trimmed) continue;
  10727. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  10728. try {
  10729. const evt = JSON.parse(line);
  10730. handleLiveTracerouteEvent(evt);
  10731. } catch (parseErr) {
  10732. console.warn('Traceroute SSE parse error:', parseErr, line);
  10733. }
  10734. }
  10735. }
  10736. } catch (err) {
  10737. if (err.name === 'AbortError') {
  10738. // User aborted normally
  10739. } else {
  10740. showToast('Traceroute Error', err.message, 'error');
  10741. }
  10742. } finally {
  10743. tracerouteAbortController = null;
  10744. resetTracerouteButton();
  10745. }
  10746. }
  10747. function handleLiveTracerouteEvent(evt) {
  10748. const statHops = document.getElementById('tools-tr-hops-count');
  10749. const tbody = document.getElementById('tools-tr-tbody');
  10750. const rawEl = document.getElementById('tools-tr-raw');
  10751. if (evt.raw && rawEl) {
  10752. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  10753. rawEl.scrollTop = rawEl.scrollHeight;
  10754. }
  10755. if (evt.hops_count !== undefined && statHops) {
  10756. statHops.innerText = `${evt.hops_count} Hops`;
  10757. }
  10758. if (evt.type === 'hop' && evt.hop && tbody) {
  10759. const h = evt.hop;
  10760. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  10761. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  10762. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  10763. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  10764. const tr = document.createElement('tr');
  10765. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  10766. tr.innerHTML = `
  10767. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  10768. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  10769. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  10770. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  10771. <td class="py-2.5 px-3 text-right">
  10772. ${isTimeout
  10773. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  10774. : '<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>'}
  10775. </td>
  10776. `;
  10777. tbody.appendChild(tr);
  10778. } else if (evt.type === 'done') {
  10779. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  10780. }
  10781. }
  10782. async function executeMTR(e) {
  10783. if (e) e.preventDefault();
  10784. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  10785. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  10786. if (!target) {
  10787. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10788. return;
  10789. }
  10790. const btn = document.getElementById('tools-mtr-btn');
  10791. const spinner = document.getElementById('tools-mtr-spinner');
  10792. if (btn) btn.disabled = true;
  10793. if (spinner) spinner.classList.remove('hidden');
  10794. try {
  10795. const res = await fetch(`${API_BASE}/tools/mtr`, {
  10796. method: 'POST',
  10797. headers: { 'Content-Type': 'application/json' },
  10798. body: JSON.stringify({ target, count: cycles })
  10799. });
  10800. const data = await res.json();
  10801. if (!res.ok) {
  10802. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  10803. return;
  10804. }
  10805. const resCard = document.getElementById('tools-mtr-results');
  10806. if (resCard) resCard.classList.remove('hidden');
  10807. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  10808. const statHops = document.getElementById('tools-mtr-hops-count');
  10809. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  10810. const tbody = document.getElementById('tools-mtr-tbody');
  10811. if (tbody) {
  10812. if (hopsCount > 0) {
  10813. tbody.innerHTML = data.hops.map(h => {
  10814. 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');
  10815. return `
  10816. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  10817. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  10818. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  10819. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  10820. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  10821. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  10822. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  10823. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  10824. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  10825. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  10826. </tr>
  10827. `;
  10828. }).join('');
  10829. } else {
  10830. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  10831. }
  10832. }
  10833. const rawEl = document.getElementById('tools-mtr-raw');
  10834. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  10835. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  10836. } catch (err) {
  10837. showToast('MTR Error', err.message, 'error');
  10838. } finally {
  10839. if (btn) btn.disabled = false;
  10840. if (spinner) spinner.classList.add('hidden');
  10841. }
  10842. }
  10843. async function executeDNS(e) {
  10844. if (e) e.preventDefault();
  10845. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  10846. const type = document.getElementById('tools-dns-type')?.value || 'A';
  10847. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  10848. if (!domain) {
  10849. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  10850. return;
  10851. }
  10852. const btn = document.getElementById('tools-dns-btn');
  10853. const spinner = document.getElementById('tools-dns-spinner');
  10854. if (btn) btn.disabled = true;
  10855. if (spinner) spinner.classList.remove('hidden');
  10856. try {
  10857. const res = await fetch(`${API_BASE}/tools/dns`, {
  10858. method: 'POST',
  10859. headers: { 'Content-Type': 'application/json' },
  10860. body: JSON.stringify({ domain, type, server })
  10861. });
  10862. const data = await res.json();
  10863. if (!res.ok) {
  10864. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  10865. return;
  10866. }
  10867. const resCard = document.getElementById('tools-dns-results');
  10868. if (resCard) resCard.classList.remove('hidden');
  10869. const metaEl = document.getElementById('tools-dns-meta');
  10870. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  10871. const tbody = document.getElementById('tools-dns-tbody');
  10872. if (tbody) {
  10873. if (Array.isArray(data.records) && data.records.length > 0) {
  10874. tbody.innerHTML = data.records.map(r => `
  10875. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  10876. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  10877. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  10878. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  10879. <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>
  10880. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  10881. </tr>
  10882. `).join('');
  10883. } else {
  10884. 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>`;
  10885. }
  10886. }
  10887. const rawEl = document.getElementById('tools-dns-raw');
  10888. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  10889. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  10890. } catch (err) {
  10891. showToast('DNS Error', err.message, 'error');
  10892. } finally {
  10893. if (btn) btn.disabled = false;
  10894. if (spinner) spinner.classList.add('hidden');
  10895. }
  10896. }
  10897. async function executePortProbe(e) {
  10898. if (e) e.preventDefault();
  10899. const target = document.getElementById('tools-port-target')?.value?.trim();
  10900. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  10901. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  10902. if (!target || !port) {
  10903. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  10904. return;
  10905. }
  10906. const btn = document.getElementById('tools-port-btn');
  10907. const spinner = document.getElementById('tools-port-spinner');
  10908. if (btn) btn.disabled = true;
  10909. if (spinner) spinner.classList.remove('hidden');
  10910. try {
  10911. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  10912. method: 'POST',
  10913. headers: { 'Content-Type': 'application/json' },
  10914. body: JSON.stringify({ target, port, timeout })
  10915. });
  10916. const data = await res.json();
  10917. if (!res.ok) {
  10918. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  10919. return;
  10920. }
  10921. const resCard = document.getElementById('tools-port-results');
  10922. if (resCard) resCard.classList.remove('hidden');
  10923. const banner = document.getElementById('tools-port-banner');
  10924. const icon = document.getElementById('tools-port-icon');
  10925. const title = document.getElementById('tools-port-title');
  10926. const sub = document.getElementById('tools-port-sub');
  10927. const latency = document.getElementById('tools-port-latency');
  10928. if (data.open) {
  10929. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  10930. if (icon) {
  10931. 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';
  10932. icon.innerText = '✓';
  10933. }
  10934. if (title) {
  10935. title.className = 'text-sm font-bold text-emerald-300';
  10936. title.innerText = `PORT ${port} OPEN / LISTENING`;
  10937. }
  10938. if (sub) {
  10939. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  10940. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  10941. }
  10942. if (latency) {
  10943. latency.className = 'text-base font-bold font-mono text-emerald-300';
  10944. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  10945. }
  10946. } else {
  10947. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  10948. if (icon) {
  10949. 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';
  10950. icon.innerText = '✕';
  10951. }
  10952. if (title) {
  10953. title.className = 'text-sm font-bold text-rose-300';
  10954. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  10955. }
  10956. if (sub) {
  10957. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  10958. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  10959. }
  10960. if (latency) {
  10961. latency.className = 'text-base font-bold font-mono text-slate-500';
  10962. latency.innerText = '--';
  10963. }
  10964. }
  10965. const rawEl = document.getElementById('tools-port-raw');
  10966. 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'}`);
  10967. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  10968. } catch (err) {
  10969. showToast('Probe Error', err.message, 'error');
  10970. } finally {
  10971. if (btn) btn.disabled = false;
  10972. if (spinner) spinner.classList.add('hidden');
  10973. }
  10974. }
  10975. // ==========================================
  10976. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  10977. // ==========================================
  10978. async function loadDHCPClients(showToastMsg = false) {
  10979. try {
  10980. const [clientsRes, sumRes] = await Promise.all([
  10981. fetch(`${API_BASE}/dhcp/clients`),
  10982. fetch(`${API_BASE}/dhcp/clients/summary`)
  10983. ]);
  10984. if (clientsRes.ok) {
  10985. state.dhcpClients = await clientsRes.json();
  10986. }
  10987. if (sumRes.ok) {
  10988. state.dhcpSummary = await sumRes.json();
  10989. }
  10990. renderDHCPClients();
  10991. updateDHCPSummaryCards();
  10992. const bDhcp = document.getElementById('badge-dhcp-client-count');
  10993. if (bDhcp && state.dhcpSummary) {
  10994. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  10995. }
  10996. if (showToastMsg) {
  10997. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  10998. }
  10999. } catch (err) {
  11000. console.error('Failed to load DHCP clients:', err);
  11001. if (showToastMsg) {
  11002. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  11003. }
  11004. }
  11005. }
  11006. function updateDHCPSummaryCards() {
  11007. const sum = state.dhcpSummary || {
  11008. total_clients: (state.dhcpClients || []).length,
  11009. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  11010. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  11011. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  11012. };
  11013. const totalEl = document.getElementById('dhcp-stat-total');
  11014. const boundEl = document.getElementById('dhcp-stat-bound');
  11015. const searchEl = document.getElementById('dhcp-stat-searching');
  11016. const disEl = document.getElementById('dhcp-stat-disabled');
  11017. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  11018. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  11019. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  11020. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  11021. }
  11022. function renderDHCPClients() {
  11023. const tbody = document.getElementById('dhcp-clients-tbody');
  11024. const emptyState = document.getElementById('dhcp-clients-empty');
  11025. if (!tbody) return;
  11026. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  11027. if (clients.length === 0) {
  11028. tbody.innerHTML = '';
  11029. if (emptyState) emptyState.classList.remove('hidden');
  11030. return;
  11031. }
  11032. if (emptyState) emptyState.classList.add('hidden');
  11033. tbody.innerHTML = clients.map(c => {
  11034. let statusBadge = '';
  11035. if (!c.enabled) {
  11036. 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>';
  11037. } else if (c.status === 'bound') {
  11038. 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>';
  11039. } else if (c.status === 'searching') {
  11040. 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>';
  11041. } else if (c.status === 'stopped') {
  11042. 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>';
  11043. } else {
  11044. 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>`;
  11045. }
  11046. 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>';
  11047. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  11048. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  11049. 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>';
  11050. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  11051. // Option flags
  11052. const flags = [];
  11053. 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>');
  11054. 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>');
  11055. 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>');
  11056. 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>`);
  11057. return `
  11058. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  11059. <td class="py-3 px-4">
  11060. <div class="flex items-center gap-2">
  11061. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  11062. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  11063. </div>
  11064. </td>
  11065. <td class="py-3 px-4">${statusBadge}</td>
  11066. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  11067. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  11068. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  11069. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  11070. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  11071. <td class="py-3 px-4">
  11072. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  11073. </td>
  11074. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  11075. ${c.enabled ? `
  11076. <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>
  11077. <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>
  11078. <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>
  11079. ` : `
  11080. <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>
  11081. `}
  11082. <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>
  11083. <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>
  11084. </td>
  11085. </tr>
  11086. `;
  11087. }).join('');
  11088. }
  11089. function openDHCPClientModal(clientId = null) {
  11090. const modal = document.getElementById('modal-dhcp-client');
  11091. if (!modal) return;
  11092. const title = document.getElementById('modal-dhcp-title');
  11093. const idInput = document.getElementById('modal-dhcp-id');
  11094. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11095. const distInput = document.getElementById('modal-dhcp-distance');
  11096. const commentInput = document.getElementById('modal-dhcp-comment');
  11097. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  11098. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  11099. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  11100. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  11101. // Populate interfaces
  11102. if (ifaceSelect) {
  11103. let opts = '<option value="">Select interface...</option>';
  11104. const allIfaces = state.interfaces || [];
  11105. const allVlans = state.vlans || [];
  11106. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  11107. // Group 1: Physical & Bridge Interfaces
  11108. opts += '<optgroup label="Physical & Bridge Interfaces">';
  11109. allIfaces.forEach(i => {
  11110. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  11111. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  11112. });
  11113. opts += '</optgroup>';
  11114. // Group 2: VLAN Interfaces
  11115. if (allVlans.length > 0) {
  11116. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  11117. allVlans.forEach(v => {
  11118. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  11119. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  11120. });
  11121. opts += '</optgroup>';
  11122. }
  11123. ifaceSelect.innerHTML = opts;
  11124. }
  11125. if (clientId) {
  11126. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  11127. if (client) {
  11128. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  11129. if (idInput) idInput.value = client.id;
  11130. if (ifaceSelect) {
  11131. ifaceSelect.value = client.interface;
  11132. ifaceSelect.disabled = true; // interface cannot be changed on edit
  11133. }
  11134. if (distInput) distInput.value = client.default_route_distance || 1;
  11135. if (commentInput) commentInput.value = client.comment || '';
  11136. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  11137. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  11138. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  11139. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  11140. }
  11141. } else {
  11142. if (title) title.innerText = 'Add DHCP Client';
  11143. if (idInput) idInput.value = '';
  11144. if (ifaceSelect) {
  11145. ifaceSelect.value = '';
  11146. ifaceSelect.disabled = false;
  11147. }
  11148. if (distInput) distInput.value = 1;
  11149. if (commentInput) commentInput.value = '';
  11150. if (defRouteCheck) defRouteCheck.checked = true;
  11151. if (peerDnsCheck) peerDnsCheck.checked = true;
  11152. if (peerNtpCheck) peerNtpCheck.checked = true;
  11153. if (enabledCheck) enabledCheck.checked = true;
  11154. }
  11155. modal.classList.remove('hidden');
  11156. }
  11157. function openDHCPClientModalForIface(ifaceName) {
  11158. openDHCPClientModal();
  11159. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11160. if (ifaceSelect && ifaceName) {
  11161. ifaceSelect.value = ifaceName;
  11162. }
  11163. }
  11164. function closeDHCPClientModal() {
  11165. const modal = document.getElementById('modal-dhcp-client');
  11166. if (modal) modal.classList.add('hidden');
  11167. }
  11168. async function submitSaveDHCPClient(e) {
  11169. if (e) e.preventDefault();
  11170. const id = document.getElementById('modal-dhcp-id')?.value;
  11171. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  11172. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  11173. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  11174. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  11175. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  11176. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  11177. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  11178. if (!id && !iface) {
  11179. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  11180. return;
  11181. }
  11182. try {
  11183. let res;
  11184. if (id) {
  11185. // PUT update
  11186. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  11187. method: 'PUT',
  11188. headers: { 'Content-Type': 'application/json' },
  11189. body: JSON.stringify({
  11190. enabled,
  11191. add_default_route: defRoute,
  11192. default_route_distance: distance,
  11193. use_peer_dns: peerDns,
  11194. use_peer_ntp: peerNtp,
  11195. comment
  11196. })
  11197. });
  11198. } else {
  11199. // POST create
  11200. res = await fetch(`${API_BASE}/dhcp/clients`, {
  11201. method: 'POST',
  11202. headers: { 'Content-Type': 'application/json' },
  11203. body: JSON.stringify({
  11204. interface: iface,
  11205. enabled,
  11206. add_default_route: defRoute,
  11207. default_route_distance: distance,
  11208. use_peer_dns: peerDns,
  11209. use_peer_ntp: peerNtp,
  11210. comment
  11211. })
  11212. });
  11213. }
  11214. const data = await res.json();
  11215. if (!res.ok) {
  11216. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  11217. return;
  11218. }
  11219. closeDHCPClientModal();
  11220. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  11221. await loadDHCPClients();
  11222. fetchData(); // refresh interfaces list with new lease/status
  11223. } catch (err) {
  11224. showToast('Error', err.message, 'error');
  11225. }
  11226. }
  11227. async function toggleDHCPClientState(id, enabled) {
  11228. try {
  11229. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  11230. method: 'POST',
  11231. headers: { 'Content-Type': 'application/json' },
  11232. body: JSON.stringify({ enabled })
  11233. });
  11234. const data = await res.json();
  11235. if (!res.ok) {
  11236. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  11237. return;
  11238. }
  11239. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  11240. await loadDHCPClients();
  11241. fetchData();
  11242. } catch (err) {
  11243. showToast('Error', err.message, 'error');
  11244. }
  11245. }
  11246. async function renewDHCPClient(id) {
  11247. try {
  11248. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  11249. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  11250. method: 'POST'
  11251. });
  11252. const data = await res.json();
  11253. if (!res.ok) {
  11254. showToast('Error', data.error || 'Failed to renew lease', 'error');
  11255. return;
  11256. }
  11257. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  11258. setTimeout(() => {
  11259. loadDHCPClients();
  11260. fetchData();
  11261. }, 1500);
  11262. } catch (err) {
  11263. showToast('Error', err.message, 'error');
  11264. }
  11265. }
  11266. async function releaseDHCPClient(id) {
  11267. try {
  11268. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  11269. method: 'POST'
  11270. });
  11271. const data = await res.json();
  11272. if (!res.ok) {
  11273. showToast('Error', data.error || 'Failed to release lease', 'error');
  11274. return;
  11275. }
  11276. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  11277. await loadDHCPClients();
  11278. fetchData();
  11279. } catch (err) {
  11280. showToast('Error', err.message, 'error');
  11281. }
  11282. }
  11283. async function deleteDHCPClient(id, ifaceName) {
  11284. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  11285. return;
  11286. }
  11287. try {
  11288. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  11289. method: 'DELETE'
  11290. });
  11291. const data = await res.json();
  11292. if (!res.ok) {
  11293. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  11294. return;
  11295. }
  11296. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  11297. await loadDHCPClients();
  11298. fetchData();
  11299. } catch (err) {
  11300. showToast('Error', err.message, 'error');
  11301. }
  11302. }
  11303. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  11304. async function loadDHCPServer(populate = true) {
  11305. try {
  11306. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  11307. fetch(`${API_BASE}/dhcp-server/summary`),
  11308. fetch(`${API_BASE}/dhcp-server/servers`),
  11309. fetch(`${API_BASE}/dhcp-server/networks`),
  11310. fetch(`${API_BASE}/dhcp-server/leases`),
  11311. fetch(`${API_BASE}/dhcp-server/options`)
  11312. ]);
  11313. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  11314. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  11315. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  11316. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  11317. if (optRes.ok) state.dhcpOptions = await optRes.json();
  11318. const sum = state.dhcpServerSummary || {};
  11319. const srvs = state.dhcpServers || [];
  11320. const nets = state.dhcpNetworks || [];
  11321. const leases = state.dhcpLeases || [];
  11322. const opts = state.dhcpOptions || [];
  11323. // KPI Cards
  11324. const statActive = document.getElementById('dhcp-server-stat-active');
  11325. if (statActive) {
  11326. const activeCount = srvs.filter(s => s.running).length;
  11327. statActive.innerText = `${activeCount} / ${srvs.length}`;
  11328. }
  11329. const statLeases = document.getElementById('dhcp-server-stat-leases');
  11330. if (statLeases) {
  11331. statLeases.innerText = leases.length;
  11332. }
  11333. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  11334. if (statLeasesSub) {
  11335. const dyn = leases.filter(l => l.dynamic).length;
  11336. const st = leases.filter(l => !l.dynamic).length;
  11337. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  11338. }
  11339. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  11340. if (statNetworks) {
  11341. statNetworks.innerText = nets.length;
  11342. }
  11343. // Subtab Badges
  11344. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  11345. if (bSrv) bSrv.innerText = srvs.length;
  11346. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  11347. if (bNet) bNet.innerText = nets.length;
  11348. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  11349. if (bLease) bLease.innerText = leases.length;
  11350. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  11351. if (bOpt) bOpt.innerText = opts.length;
  11352. // Sidebar Badge
  11353. const sideBadge = document.getElementById('badge-dhcp-server-count');
  11354. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  11355. renderCurrentDHCPServerTab();
  11356. } catch (err) {
  11357. console.error('Failed to load DHCP Server:', err);
  11358. }
  11359. }
  11360. function switchDHCPServerTab(tab) {
  11361. state.dhcpServerTab = tab;
  11362. const tabs = ['servers', 'networks', 'leases', 'options'];
  11363. tabs.forEach(t => {
  11364. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  11365. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  11366. if (panel) {
  11367. if (t === tab) panel.classList.remove('hidden');
  11368. else panel.classList.add('hidden');
  11369. }
  11370. if (btn) {
  11371. if (t === tab) {
  11372. 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';
  11373. } else {
  11374. 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';
  11375. }
  11376. }
  11377. });
  11378. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  11379. if (addBtn) {
  11380. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  11381. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  11382. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  11383. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  11384. }
  11385. renderCurrentDHCPServerTab();
  11386. }
  11387. function handleDHCPServerPrimaryAdd() {
  11388. const tab = state.dhcpServerTab || 'servers';
  11389. if (tab === 'servers') openAddDHCPServerModal();
  11390. else if (tab === 'networks') openAddDHCPNetworkModal();
  11391. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  11392. else if (tab === 'options') openAddDHCPOptionModal();
  11393. }
  11394. function renderCurrentDHCPServerTab() {
  11395. const tab = state.dhcpServerTab || 'servers';
  11396. if (tab === 'servers') renderDHCPServers();
  11397. else if (tab === 'networks') renderDHCPNetworks();
  11398. else if (tab === 'leases') renderDHCPLeases();
  11399. else if (tab === 'options') renderDHCPOptions();
  11400. }
  11401. function renderDHCPServers() {
  11402. const tbody = document.getElementById('dhcp-server-tbody');
  11403. const empty = document.getElementById('dhcp-server-empty');
  11404. if (!tbody) return;
  11405. tbody.innerHTML = '';
  11406. const servers = state.dhcpServers || [];
  11407. if (servers.length === 0) {
  11408. empty?.classList.remove('hidden');
  11409. return;
  11410. }
  11411. empty?.classList.add('hidden');
  11412. servers.forEach(s => {
  11413. const tr = document.createElement('tr');
  11414. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  11415. tr.innerHTML = `
  11416. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  11417. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  11418. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  11419. <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>
  11420. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  11421. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  11422. <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>
  11423. <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>
  11424. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  11425. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11426. <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>
  11427. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11428. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  11429. </td>
  11430. `;
  11431. tbody.appendChild(tr);
  11432. });
  11433. }
  11434. function renderDHCPNetworks() {
  11435. const tbody = document.getElementById('dhcp-networks-tbody');
  11436. const empty = document.getElementById('dhcp-networks-empty');
  11437. if (!tbody) return;
  11438. tbody.innerHTML = '';
  11439. const networks = state.dhcpNetworks || [];
  11440. if (networks.length === 0) {
  11441. empty?.classList.remove('hidden');
  11442. return;
  11443. }
  11444. empty?.classList.add('hidden');
  11445. networks.forEach(n => {
  11446. const tr = document.createElement('tr');
  11447. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  11448. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  11449. const ntpStr = (n.ntp_servers || []).join(', ') || '-';
  11450. tr.innerHTML = `
  11451. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  11452. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  11453. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  11454. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[120px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  11455. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  11456. <td class="py-2.5 px-3 font-mono text-purple-300 truncate max-w-[120px]" title="${escapeHtml(ntpStr)}">${escapeHtml(ntpStr)}</td>
  11457. <td class="py-2.5 px-3 font-mono text-amber-300">${escapeHtml(n.next_server || '-')}</td>
  11458. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.boot_file_name || '-')}</td>
  11459. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  11460. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11461. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11462. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  11463. </td>
  11464. `;
  11465. tbody.appendChild(tr);
  11466. });
  11467. }
  11468. function renderDHCPLeases() {
  11469. const tbody = document.getElementById('dhcp-leases-tbody');
  11470. const empty = document.getElementById('dhcp-leases-empty');
  11471. if (!tbody) return;
  11472. tbody.innerHTML = '';
  11473. const leases = state.dhcpLeases || [];
  11474. if (leases.length === 0) {
  11475. empty?.classList.remove('hidden');
  11476. return;
  11477. }
  11478. empty?.classList.add('hidden');
  11479. leases.forEach(l => {
  11480. const tr = document.createElement('tr');
  11481. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  11482. 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>';
  11483. const statusBadge = l.status === 'bound'
  11484. ? '<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>'
  11485. : l.status === 'static'
  11486. ? '<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>'
  11487. : '<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>';
  11488. const makeStaticBtn = l.dynamic
  11489. ? `<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>`
  11490. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  11491. tr.innerHTML = `
  11492. <td class="py-2.5 px-3 text-center">${flag}</td>
  11493. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  11494. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  11495. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  11496. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  11497. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  11498. <td class="py-2.5 px-3">${statusBadge}</td>
  11499. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  11500. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11501. ${makeStaticBtn}
  11502. </td>
  11503. `;
  11504. tbody.appendChild(tr);
  11505. });
  11506. }
  11507. function renderDHCPOptions() {
  11508. const tbody = document.getElementById('dhcp-options-tbody');
  11509. const empty = document.getElementById('dhcp-options-empty');
  11510. if (!tbody) return;
  11511. tbody.innerHTML = '';
  11512. const options = state.dhcpOptions || [];
  11513. if (options.length === 0) {
  11514. empty?.classList.remove('hidden');
  11515. return;
  11516. }
  11517. empty?.classList.add('hidden');
  11518. options.forEach(o => {
  11519. const tr = document.createElement('tr');
  11520. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  11521. tr.innerHTML = `
  11522. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  11523. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  11524. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  11525. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  11526. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11527. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11528. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  11529. </td>
  11530. `;
  11531. tbody.appendChild(tr);
  11532. });
  11533. }
  11534. // ==================== MODALS & ACTIONS: SERVER ====================
  11535. function populateDHCPNetworkSelect(elemId, selectedVal) {
  11536. const sel = document.getElementById(elemId);
  11537. if (!sel) return;
  11538. sel.innerHTML = '<option value="">Select network subnet...</option>';
  11539. const networks = state.dhcpNetworks || [];
  11540. networks.forEach(n => {
  11541. const opt = document.createElement('option');
  11542. opt.value = n.address;
  11543. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  11544. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  11545. opt.selected = true;
  11546. }
  11547. sel.appendChild(opt);
  11548. });
  11549. }
  11550. function onDHCPServerNetworkChange() {
  11551. const netSel = document.getElementById('dhcp-server-modal-network');
  11552. if (!netSel) return;
  11553. const netVal = netSel.value;
  11554. if (!netVal) return;
  11555. const poolInput = document.getElementById('dhcp-server-modal-pool');
  11556. if (!poolInput) return;
  11557. // Auto-calculate suggested address pool based on subnet CIDR
  11558. const parts = netVal.split('/');
  11559. const ip = parts[0];
  11560. const cidr = parseInt(parts[1] || '24', 10);
  11561. if (cidr === 24) {
  11562. const octets = ip.split('.');
  11563. if (octets.length === 4) {
  11564. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  11565. poolInput.value = `${base}.10-${base}.254`;
  11566. }
  11567. }
  11568. }
  11569. function openAddDHCPServerModal() {
  11570. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  11571. document.getElementById('dhcp-server-modal-id').value = '';
  11572. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  11573. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  11574. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  11575. document.getElementById('dhcp-server-modal-comment').value = '';
  11576. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  11577. document.getElementById('dhcp-server-modal-disabled').checked = false;
  11578. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  11579. const networks = state.dhcpNetworks || [];
  11580. const defaultNet = networks.length > 0 ? networks[0].address : '';
  11581. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  11582. if (defaultNet) {
  11583. onDHCPServerNetworkChange();
  11584. }
  11585. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  11586. }
  11587. function openEditDHCPServerModal(id) {
  11588. const s = (state.dhcpServers || []).find(item => item.id === id);
  11589. if (!s) return;
  11590. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  11591. document.getElementById('dhcp-server-modal-id').value = s.id;
  11592. document.getElementById('dhcp-server-modal-name').value = s.name;
  11593. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  11594. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  11595. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  11596. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  11597. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  11598. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  11599. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  11600. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  11601. }
  11602. function closeDHCPServerModal() {
  11603. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  11604. }
  11605. async function submitSaveDHCPServer(e) {
  11606. e.preventDefault();
  11607. const id = document.getElementById('dhcp-server-modal-id').value;
  11608. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  11609. const iface = document.getElementById('dhcp-server-modal-iface').value;
  11610. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  11611. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  11612. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  11613. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  11614. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  11615. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  11616. try {
  11617. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  11618. method: 'POST',
  11619. headers: { 'Content-Type': 'application/json' },
  11620. body: JSON.stringify({
  11621. id,
  11622. name,
  11623. interface: iface,
  11624. network,
  11625. address_pool: pool,
  11626. lease_time: leaseTime,
  11627. authoritative,
  11628. disabled,
  11629. comment
  11630. })
  11631. });
  11632. if (res.ok) {
  11633. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  11634. closeDHCPServerModal();
  11635. loadDHCPServer(false);
  11636. fetchData(false);
  11637. } else {
  11638. const err = await res.text();
  11639. showToast('Error', err, 'error');
  11640. }
  11641. } catch (err) {
  11642. showToast('Error', err.message, 'error');
  11643. }
  11644. }
  11645. async function toggleDHCPServerState(id, disabled) {
  11646. try {
  11647. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  11648. method: 'POST',
  11649. headers: { 'Content-Type': 'application/json' },
  11650. body: JSON.stringify({ disabled })
  11651. });
  11652. if (res.ok) {
  11653. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  11654. loadDHCPServer(false);
  11655. fetchData(false);
  11656. }
  11657. } catch (err) {
  11658. showToast('Error', err.message, 'error');
  11659. }
  11660. }
  11661. async function deleteDHCPServer(id, name) {
  11662. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  11663. try {
  11664. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11665. if (res.ok) {
  11666. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  11667. loadDHCPServer(false);
  11668. fetchData(false);
  11669. }
  11670. } catch (err) {
  11671. showToast('Error', err.message, 'error');
  11672. }
  11673. }
  11674. // ==================== MODALS & ACTIONS: NETWORKS ====================
  11675. function openAddDHCPNetworkModal() {
  11676. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  11677. document.getElementById('dhcp-network-modal-id').value = '';
  11678. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  11679. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  11680. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  11681. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  11682. document.getElementById('dhcp-network-modal-ntp').value = '192.168.88.1, time.cloudflare.com';
  11683. document.getElementById('dhcp-network-modal-tftp').value = '';
  11684. document.getElementById('dhcp-network-modal-bootfile').value = '';
  11685. document.getElementById('dhcp-network-modal-wins').value = '';
  11686. document.getElementById('dhcp-network-modal-netmask').value = '';
  11687. document.getElementById('dhcp-network-modal-comment').value = '';
  11688. renderDHCPNetworkOptionsCheckboxes([]);
  11689. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  11690. }
  11691. function openEditDHCPNetworkModal(id) {
  11692. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  11693. if (!n) return;
  11694. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  11695. document.getElementById('dhcp-network-modal-id').value = n.id;
  11696. document.getElementById('dhcp-network-modal-address').value = n.address;
  11697. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  11698. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  11699. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  11700. document.getElementById('dhcp-network-modal-ntp').value = (n.ntp_servers || []).join(', ');
  11701. document.getElementById('dhcp-network-modal-tftp').value = n.next_server || '';
  11702. document.getElementById('dhcp-network-modal-bootfile').value = n.boot_file_name || '';
  11703. document.getElementById('dhcp-network-modal-wins').value = (n.wins_servers || []).join(', ');
  11704. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  11705. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  11706. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  11707. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  11708. }
  11709. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  11710. const container = document.getElementById('dhcp-network-modal-options-list');
  11711. if (!container) return;
  11712. container.innerHTML = '';
  11713. const opts = state.dhcpOptions || [];
  11714. if (opts.length === 0) {
  11715. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  11716. return;
  11717. }
  11718. opts.forEach(o => {
  11719. const isChecked = selectedIds.includes(o.id);
  11720. const label = document.createElement('label');
  11721. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  11722. label.innerHTML = `
  11723. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  11724. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  11725. `;
  11726. container.appendChild(label);
  11727. });
  11728. }
  11729. function closeDHCPNetworkModal() {
  11730. document.getElementById('dhcp-network-modal').classList.add('hidden');
  11731. }
  11732. async function submitSaveDHCPNetwork(e) {
  11733. e.preventDefault();
  11734. const id = document.getElementById('dhcp-network-modal-id').value;
  11735. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  11736. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  11737. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  11738. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  11739. const ntpStr = document.getElementById('dhcp-network-modal-ntp').value.trim();
  11740. const tftp = document.getElementById('dhcp-network-modal-tftp').value.trim();
  11741. const bootfile = document.getElementById('dhcp-network-modal-bootfile').value.trim();
  11742. const winsStr = document.getElementById('dhcp-network-modal-wins').value.trim();
  11743. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  11744. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  11745. const selectedOpts = [];
  11746. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  11747. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  11748. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  11749. const winsServers = winsStr ? winsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  11750. try {
  11751. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  11752. method: 'POST',
  11753. headers: { 'Content-Type': 'application/json' },
  11754. body: JSON.stringify({
  11755. id,
  11756. address,
  11757. gateway,
  11758. netmask,
  11759. dns_servers: dnsServers,
  11760. domain,
  11761. ntp_servers: ntpServers,
  11762. next_server: tftp,
  11763. boot_file_name: bootfile,
  11764. wins_servers: winsServers,
  11765. dhcp_options: selectedOpts,
  11766. comment
  11767. })
  11768. });
  11769. if (res.ok) {
  11770. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  11771. closeDHCPNetworkModal();
  11772. loadDHCPServer(false);
  11773. fetchData(false);
  11774. } else {
  11775. const err = await res.text();
  11776. showToast('Error', err, 'error');
  11777. }
  11778. } catch (err) {
  11779. showToast('Error', err.message, 'error');
  11780. }
  11781. }
  11782. async function deleteDHCPNetwork(id, addr) {
  11783. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  11784. try {
  11785. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11786. if (res.ok) {
  11787. showToast('Deleted', `Network ${addr} removed`, 'success');
  11788. loadDHCPServer(false);
  11789. fetchData(false);
  11790. }
  11791. } catch (err) {
  11792. showToast('Error', err.message, 'error');
  11793. }
  11794. }
  11795. // ==================== MODALS & ACTIONS: LEASES ====================
  11796. function openAddDHCPStaticLeaseModal() {
  11797. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  11798. document.getElementById('dhcp-static-lease-modal-id').value = '';
  11799. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  11800. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  11801. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  11802. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  11803. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  11804. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  11805. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  11806. }
  11807. function closeDHCPStaticLeaseModal() {
  11808. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  11809. }
  11810. async function submitSaveDHCPStaticLease(e) {
  11811. e.preventDefault();
  11812. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  11813. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  11814. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  11815. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  11816. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  11817. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  11818. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  11819. try {
  11820. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  11821. method: 'POST',
  11822. headers: { 'Content-Type': 'application/json' },
  11823. body: JSON.stringify({
  11824. id,
  11825. mac_address: mac,
  11826. address: ip,
  11827. hostname,
  11828. server,
  11829. comment,
  11830. disabled
  11831. })
  11832. });
  11833. if (res.ok) {
  11834. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  11835. closeDHCPStaticLeaseModal();
  11836. loadDHCPServer(false);
  11837. fetchData(false);
  11838. } else {
  11839. const err = await res.text();
  11840. showToast('Error', err, 'error');
  11841. }
  11842. } catch (err) {
  11843. showToast('Error', err.message, 'error');
  11844. }
  11845. }
  11846. async function deleteDHCPStaticLease(id) {
  11847. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  11848. try {
  11849. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11850. if (res.ok) {
  11851. showToast('Deleted', 'Static lease removed', 'success');
  11852. loadDHCPServer(false);
  11853. fetchData(false);
  11854. }
  11855. } catch (err) {
  11856. showToast('Error', err.message, 'error');
  11857. }
  11858. }
  11859. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  11860. try {
  11861. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  11862. method: 'POST',
  11863. headers: { 'Content-Type': 'application/json' },
  11864. body: JSON.stringify({
  11865. mac_address: mac,
  11866. address: ip,
  11867. hostname,
  11868. comment: comment || 'Converted to static'
  11869. })
  11870. });
  11871. if (res.ok) {
  11872. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  11873. loadDHCPServer(false);
  11874. fetchData(false);
  11875. } else {
  11876. const err = await res.text();
  11877. showToast('Error', err, 'error');
  11878. }
  11879. } catch (err) {
  11880. showToast('Error', err.message, 'error');
  11881. }
  11882. }
  11883. // ==================== MODALS & ACTIONS: OPTIONS ====================
  11884. function openAddDHCPOptionModal() {
  11885. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  11886. document.getElementById('dhcp-option-modal-id').value = '';
  11887. document.getElementById('dhcp-option-modal-name').value = '';
  11888. document.getElementById('dhcp-option-modal-code').value = '';
  11889. document.getElementById('dhcp-option-modal-value').value = '';
  11890. document.getElementById('dhcp-option-modal-comment').value = '';
  11891. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  11892. }
  11893. function openEditDHCPOptionModal(id) {
  11894. const o = (state.dhcpOptions || []).find(item => item.id === id);
  11895. if (!o) return;
  11896. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  11897. document.getElementById('dhcp-option-modal-id').value = o.id;
  11898. document.getElementById('dhcp-option-modal-name').value = o.name;
  11899. document.getElementById('dhcp-option-modal-code').value = o.code;
  11900. document.getElementById('dhcp-option-modal-value').value = o.value;
  11901. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  11902. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  11903. }
  11904. function closeDHCPOptionModal() {
  11905. document.getElementById('dhcp-option-modal').classList.add('hidden');
  11906. }
  11907. async function submitSaveDHCPOption(e) {
  11908. e.preventDefault();
  11909. const id = document.getElementById('dhcp-option-modal-id').value;
  11910. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  11911. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  11912. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  11913. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  11914. try {
  11915. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  11916. method: 'POST',
  11917. headers: { 'Content-Type': 'application/json' },
  11918. body: JSON.stringify({ id, name, code, value, comment })
  11919. });
  11920. if (res.ok) {
  11921. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  11922. closeDHCPOptionModal();
  11923. loadDHCPServer(false);
  11924. fetchData(false);
  11925. } else {
  11926. const err = await res.text();
  11927. showToast('Error', err, 'error');
  11928. }
  11929. } catch (err) {
  11930. showToast('Error', err.message, 'error');
  11931. }
  11932. }
  11933. async function deleteDHCPOption(id, name) {
  11934. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  11935. try {
  11936. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11937. if (res.ok) {
  11938. showToast('Deleted', `Option ${name} removed`, 'success');
  11939. loadDHCPServer(false);
  11940. fetchData(false);
  11941. }
  11942. } catch (err) {
  11943. showToast('Error', err.message, 'error');
  11944. }
  11945. }
  11946. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  11947. function openDHCPServerSetupModal() {
  11948. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  11949. onDHCPWizardIfaceChange();
  11950. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  11951. }
  11952. function closeDHCPServerSetupModal() {
  11953. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  11954. }
  11955. function onDHCPWizardIfaceChange() {
  11956. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  11957. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  11958. let ip = '192.168.88.1';
  11959. let prefix = '24';
  11960. if (iface && iface.ip_address) {
  11961. const parts = iface.ip_address.split('/');
  11962. ip = parts[0];
  11963. if (parts.length > 1) prefix = parts[1];
  11964. }
  11965. // Calculate subnet base (e.g. 192.168.88.0/24)
  11966. const ipParts = ip.split('.');
  11967. if (ipParts.length === 4) {
  11968. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  11969. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  11970. document.getElementById('dhcp-wizard-space').value = baseSpace;
  11971. document.getElementById('dhcp-wizard-gateway').value = ip;
  11972. document.getElementById('dhcp-wizard-pool').value = pool;
  11973. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  11974. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  11975. }
  11976. }
  11977. async function submitDHCPServerSetupWizard(e) {
  11978. e.preventDefault();
  11979. const iface = document.getElementById('dhcp-wizard-iface').value;
  11980. const space = document.getElementById('dhcp-wizard-space').value.trim();
  11981. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  11982. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  11983. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  11984. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  11985. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  11986. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  11987. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  11988. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  11989. try {
  11990. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  11991. method: 'POST',
  11992. headers: { 'Content-Type': 'application/json' },
  11993. body: JSON.stringify({
  11994. interface: iface,
  11995. address_space: space,
  11996. gateway: gw,
  11997. address_pool: pool,
  11998. dns_servers: dnsServers,
  11999. lease_time: leaseTime,
  12000. ntp_servers: ntpServers,
  12001. next_server: tftp
  12002. })
  12003. });
  12004. if (res.ok) {
  12005. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  12006. closeDHCPServerSetupModal();
  12007. loadDHCPServer(false);
  12008. fetchData(false);
  12009. } else {
  12010. const err = await res.text();
  12011. showToast('Error', err, 'error');
  12012. }
  12013. } catch (err) {
  12014. showToast('Error', err.message, 'error');
  12015. }
  12016. }
  12017. function populateDHCPIfaceSelect(elemId, selectedVal) {
  12018. const sel = document.getElementById(elemId);
  12019. if (!sel) return;
  12020. sel.innerHTML = '<option value="">Select interface...</option>';
  12021. const ifaces = state.interfaces || [];
  12022. ifaces.forEach(i => {
  12023. if (i.name === 'lo') return;
  12024. const opt = document.createElement('option');
  12025. opt.value = i.name;
  12026. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  12027. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  12028. if (i.name === selectedVal) opt.selected = true;
  12029. sel.appendChild(opt);
  12030. });
  12031. }
  12032. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  12033. function initTableSorting() {
  12034. document.querySelectorAll('table').forEach(setupSortableTable);
  12035. }
  12036. function setupSortableTable(table) {
  12037. const thead = table.querySelector('thead');
  12038. const tbody = table.querySelector('tbody');
  12039. if (!thead || !tbody) return;
  12040. const headerRows = thead.querySelectorAll('tr');
  12041. if (headerRows.length === 0) return;
  12042. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  12043. ths.forEach((th, colIdx) => {
  12044. if (th._sortBound) return;
  12045. th._sortBound = true;
  12046. const rawText = th.innerText.trim().toLowerCase();
  12047. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  12048. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  12049. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  12050. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  12051. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  12052. return;
  12053. }
  12054. th.classList.add('table-sortable', 'group');
  12055. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  12056. let icon = th.querySelector('.table-sort-icon');
  12057. if (!icon) {
  12058. icon = document.createElement('span');
  12059. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12060. icon.innerHTML = '⇅';
  12061. th.appendChild(icon);
  12062. }
  12063. th.addEventListener('click', (e) => {
  12064. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  12065. handleHeaderClick(table, th, colIdx);
  12066. });
  12067. });
  12068. if (!tbody._sortObserved) {
  12069. tbody._sortObserved = true;
  12070. let sortDebounceTimer = null;
  12071. const observer = new MutationObserver((mutations) => {
  12072. if (tbody._isSorting) return;
  12073. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  12074. if (!hasChildChanges) return;
  12075. clearTimeout(sortDebounceTimer);
  12076. sortDebounceTimer = setTimeout(() => {
  12077. if (tbody._isSorting) return;
  12078. if (table._activeSort && table._activeSort.dir !== 'none') {
  12079. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  12080. } else {
  12081. tagOriginalRowOrder(tbody);
  12082. }
  12083. }, 10);
  12084. });
  12085. observer.observe(tbody, { childList: true });
  12086. }
  12087. tagOriginalRowOrder(tbody);
  12088. }
  12089. function tagOriginalRowOrder(tbody) {
  12090. let idx = 0;
  12091. Array.from(tbody.children).forEach(tr => {
  12092. if (!tr.querySelector('td[colspan]')) {
  12093. if (!tr.hasAttribute('data-orig-idx')) {
  12094. tr.setAttribute('data-orig-idx', idx++);
  12095. }
  12096. }
  12097. });
  12098. }
  12099. function handleHeaderClick(table, th, colIdx) {
  12100. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  12101. let newDir = 'asc';
  12102. if (currentSort.colIdx === colIdx) {
  12103. if (currentSort.dir === 'asc') newDir = 'desc';
  12104. else if (currentSort.dir === 'desc') newDir = 'none';
  12105. else newDir = 'asc';
  12106. } else {
  12107. newDir = 'asc';
  12108. }
  12109. table._activeSort = { colIdx, dir: newDir };
  12110. updateHeaderIcons(table, colIdx, newDir);
  12111. applyTableSort(table, colIdx, newDir, true);
  12112. }
  12113. function updateHeaderIcons(table, activeColIdx, dir) {
  12114. const thead = table.querySelector('thead');
  12115. if (!thead) return;
  12116. const ths = thead.querySelectorAll('th');
  12117. ths.forEach((th, idx) => {
  12118. const icon = th.querySelector('.table-sort-icon');
  12119. if (!icon) return;
  12120. if (idx === activeColIdx && dir !== 'none') {
  12121. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  12122. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  12123. th.classList.add('table-sorted-active');
  12124. } else {
  12125. icon.innerHTML = '⇅';
  12126. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12127. th.classList.remove('table-sorted-active');
  12128. }
  12129. });
  12130. }
  12131. function applyTableSort(table, colIdx, dir, userInitiated) {
  12132. const tbody = table.querySelector('tbody');
  12133. if (!tbody || tbody.children.length <= 1) return;
  12134. tbody._isSorting = true;
  12135. tagOriginalRowOrder(tbody);
  12136. // Group parent rows and any attached drawer/sub-rows
  12137. const groups = [];
  12138. let currentGroup = null;
  12139. Array.from(tbody.children).forEach(tr => {
  12140. if (tr.querySelector('td[colspan]')) {
  12141. if (currentGroup) {
  12142. currentGroup.subRows.push(tr);
  12143. } else {
  12144. groups.push({ mainRow: tr, subRows: [] });
  12145. }
  12146. } else {
  12147. currentGroup = { mainRow: tr, subRows: [] };
  12148. groups.push(currentGroup);
  12149. }
  12150. });
  12151. if (dir === 'none') {
  12152. groups.sort((a, b) => {
  12153. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  12154. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  12155. return idxA - idxB;
  12156. });
  12157. } else {
  12158. groups.sort((a, b) => {
  12159. const cellA = a.mainRow.children[colIdx];
  12160. const cellB = b.mainRow.children[colIdx];
  12161. const res = compareTableCells(cellA, cellB);
  12162. return dir === 'asc' ? res : -res;
  12163. });
  12164. }
  12165. // Re-append rows in sorted order
  12166. groups.forEach(g => {
  12167. tbody.appendChild(g.mainRow);
  12168. g.subRows.forEach(sub => tbody.appendChild(sub));
  12169. });
  12170. tbody._isSorting = false;
  12171. }
  12172. function getCellRawText(cell) {
  12173. if (!cell) return '';
  12174. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  12175. const input = cell.querySelector('input, select');
  12176. if (input) {
  12177. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  12178. return input.value;
  12179. }
  12180. return cell.innerText.trim();
  12181. }
  12182. function parseTrafficToNumber(str) {
  12183. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  12184. if (!m) return null;
  12185. const num = parseFloat(m[1].replace(/,/g, ''));
  12186. if (isNaN(num)) return null;
  12187. const unit = m[2].toUpperCase();
  12188. let mult = 1;
  12189. if (unit.startsWith('K')) mult = 1024;
  12190. else if (unit.startsWith('M')) mult = 1024 * 1024;
  12191. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  12192. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  12193. return num * mult;
  12194. }
  12195. function parseIpToNumber(str) {
  12196. const clean = str.replace(/^[!~]/, '').trim();
  12197. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  12198. if (!m) return null;
  12199. const o1 = parseInt(m[1], 10);
  12200. const o2 = parseInt(m[2], 10);
  12201. const o3 = parseInt(m[3], 10);
  12202. const o4 = parseInt(m[4], 10);
  12203. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  12204. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  12205. }
  12206. function parseCompoundPackets(str) {
  12207. const m = str.match(/^([\d,]+)p/);
  12208. if (!m) return null;
  12209. return parseInt(m[1].replace(/,/g, ''), 10);
  12210. }
  12211. function compareTableCells(cellA, cellB) {
  12212. const a = getCellRawText(cellA);
  12213. const b = getCellRawText(cellB);
  12214. if (a === '' && b !== '') return 1;
  12215. if (b === '' && a !== '') return -1;
  12216. if (a === b) return 0;
  12217. // 1. IP Addresses / CIDR
  12218. const ipA = parseIpToNumber(a);
  12219. const ipB = parseIpToNumber(b);
  12220. if (ipA !== null && ipB !== null) return ipA - ipB;
  12221. // 2. Packet counts (e.g. "1,250p / 45 KB")
  12222. const pktA = parseCompoundPackets(a);
  12223. const pktB = parseCompoundPackets(b);
  12224. if (pktA !== null && pktB !== null) return pktA - pktB;
  12225. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  12226. const trafA = parseTrafficToNumber(a);
  12227. const trafB = parseTrafficToNumber(b);
  12228. if (trafA !== null && trafB !== null) return trafA - trafB;
  12229. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  12230. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  12231. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  12232. const numA = Number(cleanNumA);
  12233. const numB = Number(cleanNumB);
  12234. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  12235. return numA - numB;
  12236. }
  12237. // 5. Natural case-insensitive string compare
  12238. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  12239. }
  12240. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  12241. async function loadVRRP(showToastNotification = false) {
  12242. try {
  12243. const [instRes, sumRes] = await Promise.all([
  12244. fetch(`${API_BASE}/vrrp/instances`),
  12245. fetch(`${API_BASE}/vrrp/summary`)
  12246. ]);
  12247. if (instRes.ok) {
  12248. state.vrrpInstances = await instRes.json();
  12249. renderVRRP();
  12250. }
  12251. if (sumRes.ok) {
  12252. state.vrrpSummary = await sumRes.json();
  12253. renderVRRPSummary();
  12254. }
  12255. if (showToastNotification) {
  12256. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  12257. }
  12258. } catch (err) {
  12259. console.error('Failed to load VRRP:', err);
  12260. }
  12261. }
  12262. function renderVRRPSummary() {
  12263. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  12264. const elTotal = document.getElementById('vrrp-stat-total');
  12265. if (elTotal) elTotal.innerText = s.total_instances || 0;
  12266. const elMaster = document.getElementById('vrrp-stat-master');
  12267. if (elMaster) elMaster.innerText = s.master_instances || 0;
  12268. const elBackup = document.getElementById('vrrp-stat-backup');
  12269. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  12270. const bCount = document.getElementById('badge-vrrp-count');
  12271. if (bCount) bCount.innerText = s.total_instances || 0;
  12272. const dot = document.getElementById('badge-vrrp-dot');
  12273. if (dot) {
  12274. if (s.master_instances > 0) {
  12275. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  12276. } else if (s.backup_instances > 0) {
  12277. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  12278. } else {
  12279. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  12280. }
  12281. }
  12282. }
  12283. function renderVRRP() {
  12284. const tbody = document.getElementById('vrrp-table-tbody');
  12285. const empty = document.getElementById('vrrp-table-empty');
  12286. if (!tbody) return;
  12287. tbody.innerHTML = '';
  12288. const instances = state.vrrpInstances || [];
  12289. if (instances.length === 0) {
  12290. empty?.classList.remove('hidden');
  12291. return;
  12292. }
  12293. empty?.classList.add('hidden');
  12294. instances.forEach(inst => {
  12295. const tr = document.createElement('tr');
  12296. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  12297. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  12298. 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>`;
  12299. if (inst.disabled) {
  12300. 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>`;
  12301. } else if (inst.state === 'MASTER') {
  12302. 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>`;
  12303. } else if (inst.state === 'BACKUP') {
  12304. 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>`;
  12305. } else if (inst.state === 'FAULT') {
  12306. 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>`;
  12307. }
  12308. // Render State Badge
  12309. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  12310. if (!inst.disabled) {
  12311. if (inst.state === 'MASTER') {
  12312. 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>`;
  12313. } else if (inst.state === 'BACKUP') {
  12314. 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>`;
  12315. } else if (inst.state === 'FAULT') {
  12316. 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>`;
  12317. }
  12318. }
  12319. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  12320. tr.innerHTML = `
  12321. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  12322. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  12323. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  12324. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  12325. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  12326. <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>
  12327. <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>
  12328. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  12329. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  12330. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  12331. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12332. <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>
  12333. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12334. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12335. </td>
  12336. `;
  12337. tbody.appendChild(tr);
  12338. });
  12339. }
  12340. function populateVRRPIfaceSelect(elemId, selectedIface) {
  12341. const sel = document.getElementById(elemId);
  12342. if (!sel) return;
  12343. sel.innerHTML = '<option value="">Select interface...</option>';
  12344. const ifaces = state.interfaces || [];
  12345. ifaces.forEach(i => {
  12346. const opt = document.createElement('option');
  12347. opt.value = i.name;
  12348. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  12349. if (selectedIface && selectedIface === i.name) opt.selected = true;
  12350. sel.appendChild(opt);
  12351. });
  12352. }
  12353. function openAddVRRPModal() {
  12354. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  12355. document.getElementById('modal-vrrp-id').value = '';
  12356. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  12357. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  12358. document.getElementById('modal-vrrp-priority').value = 100;
  12359. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  12360. document.getElementById('modal-vrrp-version').value = '3';
  12361. document.getElementById('modal-vrrp-interval').value = 1;
  12362. document.getElementById('modal-vrrp-authtype').value = 'none';
  12363. document.getElementById('modal-vrrp-authpass').value = '';
  12364. document.getElementById('modal-vrrp-comment').value = '';
  12365. document.getElementById('modal-vrrp-preempt').checked = true;
  12366. document.getElementById('modal-vrrp-disabled').checked = false;
  12367. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  12368. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  12369. }
  12370. function openEditVRRPModal(id) {
  12371. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  12372. if (!inst) return;
  12373. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  12374. document.getElementById('modal-vrrp-id').value = inst.id;
  12375. document.getElementById('modal-vrrp-name').value = inst.name;
  12376. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  12377. document.getElementById('modal-vrrp-priority').value = inst.priority;
  12378. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  12379. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  12380. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  12381. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  12382. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  12383. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  12384. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  12385. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  12386. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  12387. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  12388. }
  12389. function closeVRRPModal() {
  12390. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  12391. }
  12392. async function submitSaveVRRP(e) {
  12393. e.preventDefault();
  12394. const id = document.getElementById('modal-vrrp-id').value;
  12395. const name = document.getElementById('modal-vrrp-name').value.trim();
  12396. const iface = document.getElementById('modal-vrrp-iface').value;
  12397. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  12398. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  12399. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  12400. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  12401. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  12402. const authType = document.getElementById('modal-vrrp-authtype').value;
  12403. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  12404. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  12405. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  12406. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  12407. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  12408. try {
  12409. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  12410. method: 'POST',
  12411. headers: { 'Content-Type': 'application/json' },
  12412. body: JSON.stringify({
  12413. id,
  12414. name,
  12415. interface: iface,
  12416. vrid,
  12417. priority,
  12418. virtual_ips: vips,
  12419. version,
  12420. interval,
  12421. auth_type: authType,
  12422. auth_password: authPass,
  12423. comment,
  12424. preempt,
  12425. disabled
  12426. })
  12427. });
  12428. if (res.ok) {
  12429. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  12430. closeVRRPModal();
  12431. loadVRRP(false);
  12432. fetchData(false);
  12433. } else {
  12434. const err = await res.text();
  12435. showToast('Error', err, 'error');
  12436. }
  12437. } catch (err) {
  12438. showToast('Error', err.message, 'error');
  12439. }
  12440. }
  12441. async function deleteVRRP(id, name) {
  12442. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  12443. try {
  12444. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12445. if (res.ok) {
  12446. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  12447. loadVRRP(false);
  12448. fetchData(false);
  12449. } else {
  12450. const err = await res.text();
  12451. showToast('Error', err, 'error');
  12452. }
  12453. } catch (err) {
  12454. showToast('Error', err.message, 'error');
  12455. }
  12456. }
  12457. async function toggleVRRPState(id, disabled) {
  12458. try {
  12459. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  12460. method: 'POST',
  12461. headers: { 'Content-Type': 'application/json' },
  12462. body: JSON.stringify({ disabled })
  12463. });
  12464. if (res.ok) {
  12465. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  12466. loadVRRP(false);
  12467. fetchData(false);
  12468. } else {
  12469. const err = await res.text();
  12470. showToast('Error', err, 'error');
  12471. }
  12472. } catch (err) {
  12473. showToast('Error', err.message, 'error');
  12474. }
  12475. }
  12476. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  12477. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  12478. const docTableObserver = new MutationObserver((mutations) => {
  12479. let needsInit = false;
  12480. for (const m of mutations) {
  12481. for (const node of m.addedNodes) {
  12482. if (node.nodeType === 1) {
  12483. if (node.tagName === 'TABLE' || (node.querySelector && node.querySelector('table'))) {
  12484. needsInit = true;
  12485. break;
  12486. }
  12487. }
  12488. }
  12489. if (needsInit) break;
  12490. }
  12491. if (needsInit) {
  12492. initTableSorting();
  12493. }
  12494. });
  12495. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  12496. }