app.js 387 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285
  1. // Proxmox RouterOS Frontend Application Logic
  2. let state = {
  3. interfaces: [],
  4. vlans: [],
  5. systemStatus: null,
  6. vpnStatus: null,
  7. routes: [],
  8. activeTab: 'dashboard',
  9. fwSubTab: 'filter',
  10. bridgeSubTab: 'bridges',
  11. bridges: [],
  12. bridgePorts: [],
  13. bridgeVLANs: [],
  14. bridgeHosts: [],
  15. bridgeSummary: null,
  16. routesSubTab: 'routes',
  17. pppSubTab: 'secrets',
  18. eoipTunnels: [],
  19. pppSecrets: [],
  20. pppProfiles: [],
  21. pppActiveSessions: [],
  22. pppoeServer: null,
  23. pptpServer: null,
  24. l2tpServer: null,
  25. ipsecServer: null,
  26. ifaceFilter: 'all',
  27. currentModalIface: null,
  28. isPolling: true,
  29. expandedParents: new Set(['eth0']),
  30. pppoeData: null,
  31. wgData: null,
  32. ipsecData: null,
  33. l2tpData: null,
  34. pptpData: null,
  35. fwSummary: null,
  36. filterRules: [],
  37. natRules: [],
  38. mangleRules: [],
  39. addressLists: [],
  40. connections: [],
  41. policyRules: [],
  42. routingTables: [],
  43. routingFilters: [],
  44. filterChainSelected: 'all',
  45. activeToolsSubTab: 'ping',
  46. dhcpClients: [],
  47. dhcpSummary: null
  48. };
  49. const API_BASE = '/api';
  50. function escapeHtml(str) {
  51. if (str === null || str === undefined) return '';
  52. return String(str)
  53. .replace(/&/g, '&')
  54. .replace(/</g, '&lt;')
  55. .replace(/>/g, '&gt;')
  56. .replace(/"/g, '&quot;')
  57. .replace(/'/g, '&#039;');
  58. }
  59. // Initialize on page load
  60. document.addEventListener('DOMContentLoaded', () => {
  61. const hash = window.location.hash.replace('#', '') || 'dashboard';
  62. navigate(hash);
  63. fetchData();
  64. // Live polling every 2.5 seconds
  65. setInterval(() => {
  66. if (state.isPolling) {
  67. fetchData(false);
  68. }
  69. }, 2500);
  70. });
  71. // Navigation Handler
  72. function navigate(tabName) {
  73. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  74. navigate('bgp');
  75. return;
  76. }
  77. if (tabName === 'vlans') {
  78. navigate('interfaces');
  79. return;
  80. }
  81. state.activeTab = tabName;
  82. window.location.hash = tabName;
  83. // Update nav links styling
  84. document.querySelectorAll('.nav-link').forEach(link => {
  85. 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';
  86. });
  87. const activeNav = document.getElementById(`nav-${tabName}`);
  88. if (activeNav) {
  89. 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';
  90. }
  91. // Update page headers
  92. const titles = {
  93. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  94. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  95. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  96. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  97. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  98. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  99. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  100. bgp: { title: 'BGP Routing (/routing bgp)', sub: 'FRRouting BGP peering sessions, advertised networks, and BGP routing table (RIB)' },
  101. ospf: { title: 'OSPF Routing (/routing ospf)', sub: 'FRRouting OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  102. 'routing-filters': { title: 'Routing Filters (/routing filter)', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  103. 'dynamic-routing': { title: 'BGP Routing (/routing bgp)', sub: 'FRRouting dynamic routing' },
  104. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  105. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  106. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  107. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  108. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  109. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  110. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  111. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  112. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' }
  113. };
  114. const header = titles[tabName] || titles.dashboard;
  115. const pTitle = document.getElementById('page-title');
  116. if (pTitle) pTitle.innerText = header.title;
  117. const pSub = document.getElementById('page-subtitle');
  118. if (pSub) pSub.innerText = header.sub;
  119. // Toggle sections dynamically for all section elements
  120. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  121. if (el.id === `section-${tabName}`) {
  122. el.classList.remove('hidden');
  123. } else {
  124. el.classList.add('hidden');
  125. }
  126. });
  127. if (tabName === 'bridge') loadBridge();
  128. if (tabName === 'firewall') loadFirewall();
  129. if (tabName === 'routes') loadRoutes();
  130. if (tabName === 'bgp') {
  131. loadDynamicRouting();
  132. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  133. }
  134. if (tabName === 'ospf') {
  135. loadDynamicRouting();
  136. switchOspfSubTab(state.activeOspfSubTab || 'ospf-ifaces');
  137. }
  138. if (tabName === 'routing-filters') loadDynamicRouting();
  139. if (tabName === 'dynamic-routing') loadDynamicRouting();
  140. if (tabName === 'ppp') loadPPP();
  141. if (tabName === 'eoip') loadEoIP();
  142. if (tabName === 'persistence') loadDebianConfig();
  143. if (tabName === 'pppoe') loadPPPoE();
  144. if (tabName === 'wireguard') loadWireGuard();
  145. if (tabName === 'ipsec') loadIPSec();
  146. if (tabName === 'l2tp') loadL2TP();
  147. if (tabName === 'pptp') loadPPTP();
  148. if (tabName === 'tools') loadToolsView();
  149. if (tabName === 'dhcp-client') loadDHCPClients();
  150. }
  151. // Fetch all core system, network and VPN telemetry
  152. async function fetchData(isManual = false) {
  153. const spinner = document.getElementById('refresh-spinner');
  154. if (isManual && spinner) spinner.classList.add('animate-spin');
  155. try {
  156. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes] = await Promise.all([
  157. fetch(`${API_BASE}/system/status`),
  158. fetch(`${API_BASE}/interfaces`),
  159. fetch(`${API_BASE}/vlans`),
  160. fetch(`${API_BASE}/vpn/status`),
  161. fetch(`${API_BASE}/firewall/summary`),
  162. fetch(`${API_BASE}/routing/dynamic/summary`),
  163. fetch(`${API_BASE}/bridge/summary`),
  164. fetch(`${API_BASE}/dhcp/clients/summary`),
  165. fetch(`${API_BASE}/dhcp/clients`)
  166. ]);
  167. if (dhcpSumRes && dhcpSumRes.ok) {
  168. state.dhcpSummary = await dhcpSumRes.json();
  169. const bDhcp = document.getElementById('badge-dhcp-client-count');
  170. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  171. }
  172. if (dhcpClientsRes && dhcpClientsRes.ok) {
  173. state.dhcpClients = await dhcpClientsRes.json();
  174. }
  175. if (brSummaryRes.ok) {
  176. state.bridgeSummary = await brSummaryRes.json();
  177. const bBridge = document.getElementById('badge-bridge-count');
  178. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  179. const sBr = document.getElementById('bridge-stat-bridges');
  180. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  181. const sPorts = document.getElementById('bridge-stat-ports');
  182. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  183. const sHosts = document.getElementById('bridge-stat-hosts');
  184. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  185. }
  186. if (statusRes.ok) state.systemStatus = await statusRes.json();
  187. if (ifacesRes.ok) {
  188. const ifacesData = await ifacesRes.json();
  189. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  190. state.interfaces = rawIfaces.filter(i => {
  191. if (!i.name) return false;
  192. if (i.name.startsWith('ep_')) return false;
  193. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  194. });
  195. try { populateToolsInterfaces(); } catch (e) {}
  196. }
  197. if (vlansRes.ok) {
  198. const vlansData = await vlansRes.json();
  199. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  200. }
  201. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  202. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  203. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  204. updateSystemMetrics();
  205. updateBadges();
  206. if (state.activeTab === 'dashboard') renderDashboard();
  207. if (state.activeTab === 'interfaces') renderInterfacesList();
  208. if (state.activeTab === 'vlans') renderVlansList();
  209. if (state.activeTab === 'firewall') loadFirewall(false);
  210. if (state.activeTab === 'routes') loadRoutes(false);
  211. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  212. if (state.activeTab === 'ppp') loadPPP(false);
  213. if (state.activeTab === 'eoip') loadEoIP(false);
  214. if (state.activeTab === 'pppoe') loadPPPoE(false);
  215. if (state.activeTab === 'wireguard') loadWireGuard(false);
  216. if (state.activeTab === 'ipsec') loadIPSec(false);
  217. if (state.activeTab === 'l2tp') loadL2TP(false);
  218. if (state.activeTab === 'pptp') loadPPTP(false);
  219. if (state.activeTab === 'dhcp-client') loadDHCPClients(false);
  220. } catch (err) {
  221. console.error('Failed to fetch router state:', err);
  222. } finally {
  223. if (isManual && spinner) {
  224. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  225. }
  226. }
  227. }
  228. // Update Top KPI and Sidebar Telemetry
  229. function updateSystemMetrics() {
  230. const s = state.systemStatus;
  231. const v = state.vpnStatus;
  232. if (!s) return;
  233. // Sidebar Host & Uptime
  234. const sideHost = document.getElementById('side-hostname');
  235. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  236. const sideUp = document.getElementById('side-uptime');
  237. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  238. const sideGw = document.getElementById('side-gateway-ip');
  239. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  240. // Compute CPU Metrics
  241. let cpuPct = 0;
  242. if (s.cpu_pct !== undefined) {
  243. cpuPct = s.cpu_pct;
  244. } else if (s.cpu_load && s.cpu_load.length > 0) {
  245. const cores = s.cpu_cores || 1;
  246. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  247. }
  248. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  249. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  250. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  251. // Sidebar CPU
  252. const sideCpuVal = document.getElementById('side-cpu-val');
  253. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  254. const sideCpuBar = document.getElementById('side-cpu-bar');
  255. if (sideCpuBar) {
  256. sideCpuBar.style.width = cpuWidth;
  257. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  258. }
  259. // Dashboard CPU Card
  260. const dashCpuVal = document.getElementById('dash-cpu-val');
  261. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  262. const dashCpuBar = document.getElementById('dash-cpu-bar');
  263. if (dashCpuBar) {
  264. dashCpuBar.style.width = cpuWidth;
  265. if (cpuPct > 85) {
  266. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  267. } else if (cpuPct > 65) {
  268. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  269. } else {
  270. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  271. }
  272. }
  273. const dashCpuCores = document.getElementById('dash-cpu-cores');
  274. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  275. const dashCpuLoad = document.getElementById('dash-cpu-load');
  276. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  277. const dashCpuStatus = document.getElementById('dash-cpu-status');
  278. if (dashCpuStatus) {
  279. if (cpuPct > 85) {
  280. dashCpuStatus.innerText = 'High';
  281. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  282. } else if (cpuPct > 65) {
  283. dashCpuStatus.innerText = 'Heavy';
  284. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  285. } else {
  286. dashCpuStatus.innerText = 'Normal';
  287. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  288. }
  289. }
  290. // Compute RAM Metrics
  291. const memPct = Math.round(s.mem_usage_pct || 0);
  292. const memPctStr = `${memPct}%`;
  293. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  294. const usedMB = s.mem_used_mb || 0;
  295. const totalMB = s.mem_total_mb || 0;
  296. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  297. function fmtMemMB(mb) {
  298. if (mb >= 1024) {
  299. return `${(mb / 1024).toFixed(1)} GB`;
  300. }
  301. return `${mb} MB`;
  302. }
  303. // Sidebar RAM
  304. const sideRamVal = document.getElementById('side-ram-val');
  305. if (sideRamVal) sideRamVal.innerText = memPctStr;
  306. const sideRamBar = document.getElementById('side-ram-bar');
  307. if (sideRamBar) sideRamBar.style.width = memWidth;
  308. // Dashboard RAM Card
  309. const dashRamVal = document.getElementById('dash-ram-val');
  310. if (dashRamVal) dashRamVal.innerText = memPctStr;
  311. const dashRamBar = document.getElementById('dash-ram-bar');
  312. if (dashRamBar) {
  313. dashRamBar.style.width = memWidth;
  314. if (memPct > 85) {
  315. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  316. } else if (memPct > 70) {
  317. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  318. } else {
  319. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  320. }
  321. }
  322. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  323. if (dashRamUsedTotal) {
  324. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  325. }
  326. const dashRamFree = document.getElementById('dash-ram-free');
  327. if (dashRamFree) {
  328. dashRamFree.innerText = fmtMemMB(freeMB);
  329. }
  330. const dashRamStatus = document.getElementById('dash-ram-status');
  331. if (dashRamStatus) {
  332. if (memPct > 85) {
  333. dashRamStatus.innerText = 'High';
  334. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  335. } else {
  336. dashRamStatus.innerText = 'Active';
  337. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  338. }
  339. }
  340. // Legacy Dashboard Stats (Safe checks)
  341. const elIfacesUp = document.getElementById('stat-ifaces-up');
  342. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  343. const elIfacesTot = document.getElementById('stat-ifaces-total');
  344. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  345. const elIfacesDown = document.getElementById('stat-ifaces-down');
  346. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  347. const elVlans = document.getElementById('stat-vlans-count');
  348. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  349. // VPN Status Indicators
  350. if (v) {
  351. const totalActive = v.total_active_tunnels || 0;
  352. const statVpnActive = document.getElementById('stat-vpn-active');
  353. if (statVpnActive) statVpnActive.innerText = totalActive;
  354. const tunnelsDot = document.getElementById('tunnels-dot');
  355. const tunnelsLabel = document.getElementById('tunnels-label');
  356. if (tunnelsDot && tunnelsLabel) {
  357. if (totalActive > 0) {
  358. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  359. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  360. } else {
  361. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  362. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  363. }
  364. }
  365. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  366. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  367. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  368. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  369. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  370. }
  371. // Total Live Bandwidth Rate
  372. let totalRx = 0;
  373. let totalTx = 0;
  374. (state.interfaces || []).forEach(i => {
  375. if (i.rate) {
  376. totalRx += i.rate.rx_bytes_sec || 0;
  377. totalTx += i.rate.tx_bytes_sec || 0;
  378. }
  379. });
  380. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  381. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  382. }
  383. function setDotBadge(id, active) {
  384. const el = document.getElementById(id);
  385. if (!el) return;
  386. if (active) {
  387. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  388. } else {
  389. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  390. }
  391. }
  392. function updateBadges() {
  393. const bIfaces = document.getElementById('badge-ifaces-count');
  394. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  395. const bVlans = document.getElementById('badge-vlans-count');
  396. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  397. if (state.fwSummary) {
  398. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  399. const badgeFw = document.getElementById('badge-firewall-count');
  400. if (badgeFw) badgeFw.innerText = totalFwRules;
  401. }
  402. if (state.vpnStatus) {
  403. const v = state.vpnStatus;
  404. const bEoIP = document.getElementById('badge-eoip-count');
  405. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  406. const bPPPSess = document.getElementById('badge-ppp-sessions');
  407. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  408. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  409. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  410. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  411. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  412. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  413. }
  414. if (state.dynSummary) {
  415. const d = state.dynSummary;
  416. setDotBadge('badge-bgp-dot', d.bgp_running);
  417. setDotBadge('badge-ospf-dot', d.ospf_running);
  418. const bBgp = document.getElementById('badge-bgp-count');
  419. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  420. const bOspf = document.getElementById('badge-ospf-count');
  421. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  422. const bFilters = document.getElementById('badge-filters-count');
  423. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  424. }
  425. }
  426. // Render Dashboard View
  427. function renderDashboard() {
  428. const matrix = document.getElementById('port-matrix');
  429. matrix.innerHTML = '';
  430. (state.interfaces || []).forEach(iface => {
  431. const isUp = iface.state === 'UP';
  432. const isVlan = iface.is_vlan;
  433. const portCard = document.createElement('div');
  434. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  435. isUp
  436. ? (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')
  437. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  438. }`;
  439. portCard.onclick = () => openIfaceModal(iface.name);
  440. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  441. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  442. portCard.innerHTML = `
  443. <div class="flex items-center justify-between mb-2">
  444. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  445. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  446. </div>
  447. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  448. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  449. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  450. <span>${iface.rate?.rx_human || '0 B/s'}</span>
  451. </div>
  452. `;
  453. matrix.appendChild(portCard);
  454. });
  455. const ifaceTbody = document.getElementById('quick-interfaces-table');
  456. if (ifaceTbody) {
  457. ifaceTbody.innerHTML = '';
  458. (state.interfaces || []).forEach(i => {
  459. const isUp = i.state === 'UP';
  460. const tr = document.createElement('tr');
  461. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  462. tr.onclick = () => openIfaceModal(i.name);
  463. const rxStr = i.rate?.rx_human || '0 B/s';
  464. const txStr = i.rate?.tx_human || '0 B/s';
  465. tr.innerHTML = `
  466. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  467. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  468. <span>${i.name}</span>
  469. </td>
  470. <td class="py-2.5 text-slate-300 font-sans">
  471. <span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 font-medium">${i.role || i.type || 'Ethernet'}</span>
  472. </td>
  473. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  474. <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>
  475. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  476. <span class="text-emerald-400">↓ ${rxStr}</span> <span class="text-slate-600">•</span> <span class="text-cyan-400">↑ ${txStr}</span>
  477. </td>
  478. <td class="py-2.5 text-right font-sans font-semibold">
  479. <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>
  480. </td>
  481. `;
  482. ifaceTbody.appendChild(tr);
  483. });
  484. }
  485. const vlanTbody = document.getElementById('quick-vlans-table');
  486. if (vlanTbody) {
  487. vlanTbody.innerHTML = '';
  488. }
  489. }
  490. // Expand / Collapse Handlers
  491. function toggleExpand(parentName) {
  492. if (state.expandedParents.has(parentName)) {
  493. state.expandedParents.delete(parentName);
  494. } else {
  495. state.expandedParents.add(parentName);
  496. }
  497. renderInterfacesList();
  498. }
  499. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  500. function supportsVLAN(iface) {
  501. if (!iface) return false;
  502. if (iface.is_vlan) return false;
  503. const name = (iface.name || '').toLowerCase();
  504. const type = (iface.type || '').toLowerCase();
  505. const role = (iface.role || '').toLowerCase();
  506. // Exclude loopback
  507. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  508. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  509. if (type === 'wireguard' || name.startsWith('wg')) return false;
  510. // Exclude PPP / PPPoE
  511. if (type === 'ppp' || name.startsWith('ppp')) return false;
  512. // Exclude other Layer 3 tunnels and dummy devices
  513. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  514. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  515. return false;
  516. }
  517. // If name already contains a dot, it's already a sub-interface
  518. if (name.includes('.')) return false;
  519. return true;
  520. }
  521. // Expand / Collapse Handlers
  522. function toggleExpand(parentName) {
  523. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  524. if (childVlans.length === 0) {
  525. // Cannot expand an interface with no VLANs
  526. state.expandedParents.delete(parentName);
  527. return;
  528. }
  529. if (state.expandedParents.has(parentName)) {
  530. state.expandedParents.delete(parentName);
  531. } else {
  532. state.expandedParents.add(parentName);
  533. }
  534. renderInterfacesList();
  535. }
  536. function expandAllIfaces(expand) {
  537. if (expand) {
  538. (state.interfaces || []).forEach(i => {
  539. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  540. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  541. });
  542. } else {
  543. state.expandedParents.clear();
  544. }
  545. renderInterfacesList();
  546. }
  547. // Filter and Render Hierarchical Interfaces List
  548. function filterIfaces(filter) {
  549. state.ifaceFilter = filter || 'all';
  550. renderInterfacesList();
  551. }
  552. function renderInterfacesList() {
  553. const tbody = document.getElementById('interfaces-tree-tbody');
  554. const emptyState = document.getElementById('interfaces-empty-state');
  555. const summary = document.getElementById('ifaces-list-summary');
  556. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  557. tbody.innerHTML = '';
  558. const allIfaces = state.interfaces || [];
  559. const allVlans = state.vlans || [];
  560. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  561. const filteredParents = parentIfaces.filter(parent => {
  562. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  563. if (query) {
  564. const matchName = parent.name.toLowerCase().includes(query);
  565. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  566. const matchRole = (parent.role || '').toLowerCase().includes(query);
  567. const matchType = (parent.type || '').toLowerCase().includes(query);
  568. const matchVlan = childVlans.some(v =>
  569. v.name.toLowerCase().includes(query) ||
  570. String(v.vlan_id).includes(query) ||
  571. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  572. (v.description || '').toLowerCase().includes(query)
  573. );
  574. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  575. }
  576. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  577. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  578. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  579. return true;
  580. });
  581. if (summary) {
  582. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  583. }
  584. if (filteredParents.length === 0) {
  585. emptyState?.classList.remove('hidden');
  586. return;
  587. }
  588. emptyState?.classList.add('hidden');
  589. filteredParents.forEach(parent => {
  590. const isUp = parent.state === 'UP';
  591. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  592. const hasVlans = childVlans.length > 0;
  593. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  594. const canHaveVlan = supportsVLAN(parent);
  595. const parentRow = document.createElement('tr');
  596. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  597. parentRow.innerHTML = `
  598. <td class="py-3 px-3 text-center">
  599. ${hasVlans ? `
  600. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  601. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  602. <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">
  603. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  604. </svg>
  605. </button>
  606. ` : `
  607. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  608. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  609. </div>
  610. `}
  611. </td>
  612. <td class="py-3 px-4">
  613. <div class="flex items-center space-x-2.5">
  614. <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">
  615. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  616. </div>
  617. <div>
  618. <div class="flex items-center gap-2">
  619. ${hasVlans ? `
  620. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400" onclick="toggleExpand('${parent.name}')">${parent.name}</span>
  621. <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>
  622. ` : `
  623. <span class="font-bold text-white text-sm">${parent.name}</span>
  624. <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>
  625. `}
  626. </div>
  627. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  628. </div>
  629. </div>
  630. </td>
  631. <td class="py-3 px-4 font-sans">
  632. <div class="flex items-center gap-1.5">
  633. <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>
  634. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  635. </div>
  636. </td>
  637. <td class="py-3 px-4">
  638. ${parent.ipv4 && parent.ipv4.length > 0
  639. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  640. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  641. }
  642. ${(() => {
  643. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  644. if (!c) return '';
  645. 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');
  646. 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>`;
  647. })()}
  648. </td>
  649. <td class="py-3 px-4 text-slate-400 text-[11px]">
  650. <div>${parent.mac || 'N/A'}</div>
  651. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  652. </td>
  653. <td class="py-3 px-4 text-[11px]">
  654. <div class="flex items-center space-x-2">
  655. <span class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  656. <span class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  657. </div>
  658. </td>
  659. <td class="py-3 px-4 font-sans">
  660. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  661. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  662. 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'
  663. }" title="Click to toggle link status">
  664. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  665. <span>${parent.state}</span>
  666. </button>
  667. </td>
  668. <td class="py-3 px-4 text-right space-x-2 font-sans">
  669. ${(() => {
  670. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  671. if (c) {
  672. 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>`;
  673. }
  674. 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>`;
  675. })()}
  676. ${canHaveVlan ? `
  677. <button onclick="openVlanModal('${parent.name}')"
  678. 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">
  679. + Add VLAN
  680. </button>
  681. ` : ''}
  682. <button onclick="openIfaceModal('${parent.name}')"
  683. 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">
  684. Configure
  685. </button>
  686. </td>
  687. `;
  688. tbody.appendChild(parentRow);
  689. if (isExpanded) {
  690. const drawerRow = document.createElement('tr');
  691. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  692. const drawerCell = document.createElement('td');
  693. drawerCell.colSpan = 8;
  694. drawerCell.className = 'p-0';
  695. drawerCell.innerHTML = `
  696. <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">
  697. <div class="flex items-center justify-between mb-3">
  698. <div class="flex items-center space-x-3">
  699. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  700. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  701. </span>
  702. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  703. ${childVlans.length} Attached
  704. </span>
  705. </div>
  706. <button onclick="openVlanModal('${parent.name}')"
  707. 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">
  708. <span>+ Create VLAN on ${parent.name}</span>
  709. </button>
  710. </div>
  711. ${childVlans.length === 0 ? `
  712. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  713. <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>
  714. <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">
  715. <span>+ Create Your First VLAN on ${parent.name}</span>
  716. </button>
  717. </div>
  718. ` : `
  719. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  720. <table class="w-full text-left text-xs font-mono">
  721. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  722. <tr>
  723. <th class="py-2.5 px-4">VLAN ID</th>
  724. <th class="py-2.5 px-4">Interface Device</th>
  725. <th class="py-2.5 px-4">Subnet Gateway</th>
  726. <th class="py-2.5 px-4">Role / Alias</th>
  727. <th class="py-2.5 px-4">MTU</th>
  728. <th class="py-2.5 px-4">Throughput</th>
  729. <th class="py-2.5 px-4">Status</th>
  730. <th class="py-2.5 px-4 text-right">Actions</th>
  731. </tr>
  732. </thead>
  733. <tbody class="divide-y divide-slate-800/70">
  734. ${childVlans.map(v => {
  735. const isVlanUp = v.state === 'UP';
  736. return `
  737. <tr class="hover:bg-slate-800/40 transition">
  738. <td class="py-2.5 px-4">
  739. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  740. VLAN ${v.vlan_id}
  741. </span>
  742. </td>
  743. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  744. <span class="text-cyan-500">└─</span>
  745. <span>${v.name}</span>
  746. </td>
  747. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  748. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  749. ${(() => {
  750. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  751. if (!c) return '';
  752. 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';
  753. 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>`;
  754. })()}
  755. </td>
  756. <td class="py-2.5 px-4 font-sans text-slate-300">
  757. <span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 mr-1.5">${v.role || 'VLAN'}</span>
  758. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  759. </td>
  760. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  761. <td class="py-2.5 px-4 text-[11px]">
  762. <span class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  763. <span class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  764. </td>
  765. <td class="py-2.5 px-4 font-sans">
  766. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  767. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  768. 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'
  769. }">
  770. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  771. <span>${v.state}</span>
  772. </button>
  773. </td>
  774. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  775. ${(() => {
  776. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  777. if (c) {
  778. 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>`;
  779. }
  780. 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>`;
  781. })()}
  782. <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>
  783. <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>
  784. </td>
  785. </tr>
  786. `;
  787. }).join('')}
  788. </tbody>
  789. </table>
  790. </div>
  791. `}
  792. </div>
  793. `;
  794. drawerRow.appendChild(drawerCell);
  795. tbody.appendChild(drawerRow);
  796. }
  797. });
  798. }
  799. // Render VLANs Dedicated View
  800. function renderVlansList() {
  801. const tbody = document.getElementById('vlans-table-body');
  802. if (!tbody) return;
  803. const emptyState = document.getElementById('vlans-empty-state');
  804. const countBadge = document.getElementById('vlans-table-count');
  805. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  806. tbody.innerHTML = '';
  807. const allVlans = state.vlans || [];
  808. if (countBadge) countBadge.innerText = allVlans.length;
  809. const filtered = allVlans.filter(v => {
  810. if (!query) return true;
  811. return v.name.toLowerCase().includes(query) ||
  812. String(v.vlan_id).includes(query) ||
  813. (v.description || '').toLowerCase().includes(query) ||
  814. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  815. });
  816. if (allVlans.length === 0) {
  817. emptyState.classList.remove('hidden');
  818. return;
  819. }
  820. emptyState.classList.add('hidden');
  821. filtered.forEach(v => {
  822. const isUp = v.state === 'UP';
  823. const tr = document.createElement('tr');
  824. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  825. tr.innerHTML = `
  826. <td class="py-3 px-4">
  827. <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">
  828. VLAN ${v.vlan_id}
  829. </span>
  830. </td>
  831. <td class="py-3 px-4 font-bold text-white">${v.name}</td>
  832. <td class="py-3 px-4 text-slate-300">
  833. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  834. </td>
  835. <td class="py-3 px-4 text-emerald-400 font-medium">
  836. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  837. </td>
  838. <td class="py-3 px-4 text-slate-300 font-sans">
  839. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  840. </td>
  841. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  842. <td class="py-3 px-4 font-sans">
  843. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  844. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  845. 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'
  846. }">
  847. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  848. <span>${v.state}</span>
  849. </button>
  850. </td>
  851. <td class="py-3 px-4 text-right space-x-2 font-sans">
  852. <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>
  853. <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>
  854. </td>
  855. `;
  856. tbody.appendChild(tr);
  857. });
  858. }
  859. // Toggle interface UP / DOWN
  860. async function toggleInterfaceState(name, newState) {
  861. try {
  862. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  863. method: 'POST',
  864. headers: { 'Content-Type': 'application/json' },
  865. body: JSON.stringify({ state: newState })
  866. });
  867. const data = await res.json();
  868. if (res.ok) {
  869. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  870. fetchData(false);
  871. } else {
  872. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  873. }
  874. } catch (err) {
  875. showToast('Error', err.message, 'error');
  876. }
  877. }
  878. // ---------------- MikroTik Flag & Utilities ----------------
  879. function renderMikroTikFlag(running, disabled) {
  880. if (running) {
  881. 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>`;
  882. }
  883. if (disabled) {
  884. 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>`;
  885. }
  886. 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>`;
  887. }
  888. function copyToClipboard(text, label = 'Text') {
  889. navigator.clipboard.writeText(text).then(() => {
  890. showToast('Copied', `${label} copied to clipboard`, 'success');
  891. }).catch(() => {
  892. prompt('Copy value:', text);
  893. });
  894. }
  895. // ======================== PPPoE Multi-Instance ========================
  896. async function loadPPPoE(populateInputs = true) {
  897. try {
  898. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  899. const list = await res.json();
  900. state.pppoeList = Array.isArray(list) ? list : [];
  901. const badge = document.getElementById('pppoe-count-badge');
  902. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  903. const tbody = document.getElementById('pppoe-table-body');
  904. const empty = document.getElementById('pppoe-empty');
  905. if (!tbody) return;
  906. tbody.innerHTML = '';
  907. if (state.pppoeList.length === 0) {
  908. if (empty) empty.classList.remove('hidden');
  909. } else {
  910. if (empty) empty.classList.add('hidden');
  911. state.pppoeList.forEach(inst => {
  912. const tr = document.createElement('tr');
  913. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  914. tr.innerHTML = `
  915. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  916. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  917. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.interface}</td>
  918. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  919. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  920. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  921. <td class="py-2.5 px-3 text-center">
  922. <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'}">
  923. ${inst.default_route ? 'Yes' : 'No'}
  924. </span>
  925. </td>
  926. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  927. ${inst.running ? `
  928. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  929. ` : `
  930. <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>
  931. `}
  932. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  933. ${inst.disabled ? 'Enable' : 'Disable'}
  934. </button>
  935. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  936. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  937. </td>
  938. `;
  939. tbody.appendChild(tr);
  940. });
  941. }
  942. } catch (err) {
  943. console.error('Failed to load PPPoE:', err);
  944. }
  945. }
  946. function openAddPPPoEModal() {
  947. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  948. document.getElementById('pppoe-modal-edit-orig').value = '';
  949. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  950. document.getElementById('pppoe-modal-name').readOnly = false;
  951. document.getElementById('pppoe-modal-user').value = '';
  952. document.getElementById('pppoe-modal-pass').value = '';
  953. document.getElementById('pppoe-modal-service').value = '';
  954. document.getElementById('pppoe-modal-mtu').value = '1492';
  955. document.getElementById('pppoe-modal-defroute').checked = true;
  956. document.getElementById('pppoe-modal-reconnect').checked = true;
  957. document.getElementById('pppoe-modal-disabled').checked = false;
  958. // Populate interfaces
  959. const sel = document.getElementById('pppoe-modal-iface');
  960. sel.innerHTML = '';
  961. (state.interfaces || []).forEach(i => {
  962. if (i.name === 'lo') return;
  963. const opt = document.createElement('option');
  964. opt.value = i.name;
  965. opt.innerText = `${i.name} (${i.role || i.type})`;
  966. sel.appendChild(opt);
  967. });
  968. document.getElementById('pppoe-modal').classList.remove('hidden');
  969. }
  970. function openEditPPPoEModal(name) {
  971. const inst = (state.pppoeList || []).find(i => i.name === name);
  972. if (!inst) return;
  973. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  974. document.getElementById('pppoe-modal-edit-orig').value = name;
  975. document.getElementById('pppoe-modal-name').value = inst.name;
  976. document.getElementById('pppoe-modal-name').readOnly = true;
  977. document.getElementById('pppoe-modal-user').value = inst.username || '';
  978. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  979. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  980. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  981. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  982. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  983. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  984. const sel = document.getElementById('pppoe-modal-iface');
  985. sel.innerHTML = '';
  986. (state.interfaces || []).forEach(i => {
  987. if (i.name === 'lo') return;
  988. const opt = document.createElement('option');
  989. opt.value = i.name;
  990. opt.innerText = `${i.name} (${i.role || i.type})`;
  991. if (i.name === inst.interface) opt.selected = true;
  992. sel.appendChild(opt);
  993. });
  994. document.getElementById('pppoe-modal').classList.remove('hidden');
  995. }
  996. function closePPPoEModal() {
  997. document.getElementById('pppoe-modal').classList.add('hidden');
  998. }
  999. async function submitSavePPPoE(e) {
  1000. e.preventDefault();
  1001. const name = document.getElementById('pppoe-modal-name').value.trim();
  1002. const iface = document.getElementById('pppoe-modal-iface').value;
  1003. const user = document.getElementById('pppoe-modal-user').value.trim();
  1004. const pass = document.getElementById('pppoe-modal-pass').value;
  1005. const service = document.getElementById('pppoe-modal-service').value.trim();
  1006. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1007. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1008. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1009. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1010. try {
  1011. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1012. method: 'POST',
  1013. headers: { 'Content-Type': 'application/json' },
  1014. body: JSON.stringify({
  1015. name,
  1016. interface: iface,
  1017. username: user,
  1018. password: pass,
  1019. service_name: service,
  1020. mtu,
  1021. default_route: defRoute,
  1022. auto_reconnect: reconnect,
  1023. disabled
  1024. })
  1025. });
  1026. if (res.ok) {
  1027. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1028. closePPPoEModal();
  1029. loadPPPoE(false);
  1030. fetchData(false);
  1031. } else {
  1032. const err = await res.json();
  1033. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1034. }
  1035. } catch (err) {
  1036. showToast('Error', err.message, 'error');
  1037. }
  1038. }
  1039. async function connectPPPoEInstance(name) {
  1040. try {
  1041. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1042. if (res.ok) {
  1043. showToast('Connecting', `Dialing ${name}...`, 'info');
  1044. setTimeout(() => loadPPPoE(false), 2000);
  1045. }
  1046. } catch (err) {
  1047. showToast('Error', err.message, 'error');
  1048. }
  1049. }
  1050. async function disconnectPPPoEInstance(name) {
  1051. try {
  1052. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1053. if (res.ok) {
  1054. showToast('Disconnected', `${name} session terminated`, 'info');
  1055. setTimeout(() => loadPPPoE(false), 1000);
  1056. }
  1057. } catch (err) {
  1058. showToast('Error', err.message, 'error');
  1059. }
  1060. }
  1061. async function togglePPPoEState(name, enable) {
  1062. try {
  1063. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1064. method: 'POST',
  1065. headers: { 'Content-Type': 'application/json' },
  1066. body: JSON.stringify({ enabled: enable })
  1067. });
  1068. if (res.ok) {
  1069. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1070. loadPPPoE(false);
  1071. }
  1072. } catch (err) {
  1073. showToast('Error', err.message, 'error');
  1074. }
  1075. }
  1076. async function deletePPPoEInstance(name) {
  1077. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1078. try {
  1079. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1080. if (res.ok) {
  1081. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1082. loadPPPoE(false);
  1083. fetchData(false);
  1084. }
  1085. } catch (err) {
  1086. showToast('Error', err.message, 'error');
  1087. }
  1088. }
  1089. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1090. state.wgSubTab = 'ifaces';
  1091. function switchWGSubTab(tab) {
  1092. state.wgSubTab = tab;
  1093. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1094. const peersPanel = document.getElementById('wg-subtab-peers');
  1095. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1096. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1097. if (tab === 'ifaces') {
  1098. ifacesPanel?.classList.remove('hidden');
  1099. peersPanel?.classList.add('hidden');
  1100. 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';
  1101. 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';
  1102. } else {
  1103. ifacesPanel?.classList.add('hidden');
  1104. peersPanel?.classList.remove('hidden');
  1105. 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';
  1106. 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';
  1107. renderWGPeers();
  1108. }
  1109. }
  1110. async function loadWireGuard(populateInputs = true) {
  1111. try {
  1112. const [ifacesRes, peersRes] = await Promise.all([
  1113. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1114. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1115. ]);
  1116. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1117. const peers = peersRes.ok ? await peersRes.json() : [];
  1118. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1119. state.wgPeers = Array.isArray(peers) ? peers : [];
  1120. // Badges
  1121. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1122. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1123. const peersCountBadge = document.getElementById('wg-peers-count');
  1124. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1125. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1126. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1127. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1128. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1129. // Render Interfaces
  1130. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1131. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1132. if (ifacesTbody) {
  1133. ifacesTbody.innerHTML = '';
  1134. if (state.wgInterfaces.length === 0) {
  1135. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1136. } else {
  1137. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1138. state.wgInterfaces.forEach(iface => {
  1139. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1140. const tr = document.createElement('tr');
  1141. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1142. tr.innerHTML = `
  1143. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1144. <td class="py-2.5 px-3">
  1145. <div class="flex items-center gap-1.5">
  1146. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1147. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1148. </div>
  1149. </td>
  1150. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1151. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1152. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1153. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1154. ${(iface.public_key || '').substring(0, 10)}... 📋
  1155. </span>
  1156. </td>
  1157. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1158. <td class="py-2.5 px-3 text-center">
  1159. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1160. </td>
  1161. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1162. ${iface.running ? `
  1163. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1164. ` : `
  1165. <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>
  1166. `}
  1167. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1168. ${iface.disabled ? 'Enable' : 'Disable'}
  1169. </button>
  1170. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1171. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1172. </td>
  1173. `;
  1174. ifacesTbody.appendChild(tr);
  1175. });
  1176. }
  1177. }
  1178. // Populate filter dropdown in peers tab
  1179. const filterSel = document.getElementById('wg-peers-filter-iface');
  1180. if (filterSel) {
  1181. const currentVal = filterSel.value;
  1182. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1183. state.wgInterfaces.forEach(i => {
  1184. const opt = document.createElement('option');
  1185. opt.value = i.name;
  1186. opt.innerText = i.name;
  1187. if (i.name === currentVal) opt.selected = true;
  1188. filterSel.appendChild(opt);
  1189. });
  1190. }
  1191. renderWGPeers();
  1192. } catch (err) {
  1193. console.error('Failed to load WireGuard:', err);
  1194. }
  1195. }
  1196. function renderWGPeers() {
  1197. const filterSel = document.getElementById('wg-peers-filter-iface');
  1198. const selectedIface = filterSel ? filterSel.value : '';
  1199. const tbody = document.getElementById('wg-peers-table-body');
  1200. const empty = document.getElementById('wg-peers-empty');
  1201. if (!tbody) return;
  1202. tbody.innerHTML = '';
  1203. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1204. if (filtered.length === 0) {
  1205. if (empty) empty.classList.remove('hidden');
  1206. } else {
  1207. if (empty) empty.classList.add('hidden');
  1208. filtered.forEach(p => {
  1209. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1210. const tr = document.createElement('tr');
  1211. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1212. tr.innerHTML = `
  1213. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1214. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1215. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1216. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1217. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1218. ${(p.public_key || '').substring(0, 10)}... 📋
  1219. </span>
  1220. </td>
  1221. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1222. <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>
  1223. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1224. <td class="py-2.5 px-3 font-mono text-[11px]">
  1225. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1226. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1227. </td>
  1228. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1229. <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">
  1230. ${p.disabled ? 'Enable' : 'Disable'}
  1231. </button>
  1232. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1233. <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>
  1234. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1235. </td>
  1236. `;
  1237. tbody.appendChild(tr);
  1238. });
  1239. }
  1240. }
  1241. function openAddWGInterfaceModal() {
  1242. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1243. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1244. const nameEl = document.getElementById('wg-iface-modal-name');
  1245. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1246. nameEl.readOnly = false;
  1247. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1248. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1249. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1250. document.getElementById('wg-iface-modal-comment').value = '';
  1251. document.getElementById('wg-iface-modal-pubkey').value = '';
  1252. document.getElementById('wg-iface-modal-privkey').value = '';
  1253. document.getElementById('wg-iface-modal-disabled').checked = false;
  1254. generateWGInterfaceKeys();
  1255. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1256. }
  1257. function openEditWGInterfaceModal(name) {
  1258. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1259. if (!iface) return;
  1260. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1261. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1262. const nameEl = document.getElementById('wg-iface-modal-name');
  1263. nameEl.value = iface.name;
  1264. nameEl.readOnly = false; // ALLOW RENAMING
  1265. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1266. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1267. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1268. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1269. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1270. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1271. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1272. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1273. }
  1274. function closeAddWGInterfaceModal() {
  1275. document.getElementById('wg-iface-modal').classList.add('hidden');
  1276. }
  1277. async function generateWGInterfaceKeys() {
  1278. try {
  1279. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1280. const keys = await res.json();
  1281. if (res.ok) {
  1282. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1283. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1284. }
  1285. } catch (err) {
  1286. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1287. }
  1288. }
  1289. async function onWGInterfacePrivKeyInput() {
  1290. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1291. if (!privKey) return;
  1292. try {
  1293. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1294. method: 'POST',
  1295. headers: { 'Content-Type': 'application/json' },
  1296. body: JSON.stringify({ private_key: privKey })
  1297. });
  1298. if (res.ok) {
  1299. const data = await res.json();
  1300. if (data.public_key) {
  1301. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1302. }
  1303. }
  1304. } catch (err) {
  1305. // Ignore while typing
  1306. }
  1307. }
  1308. function toggleWGPrivKeyVisibility() {
  1309. const el = document.getElementById('wg-iface-modal-privkey');
  1310. const btn = document.getElementById('btn-toggle-wg-privkey');
  1311. if (el.type === 'password') {
  1312. el.type = 'text';
  1313. btn.innerText = '🙈 Hide';
  1314. } else {
  1315. el.type = 'password';
  1316. btn.innerText = '👁️ Show';
  1317. }
  1318. }
  1319. function copyWGInterfacePubKey() {
  1320. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1321. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1322. }
  1323. async function submitSaveWGInterface(e) {
  1324. e.preventDefault();
  1325. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1326. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1327. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1328. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1329. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1330. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1331. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1332. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1333. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1334. try {
  1335. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1336. method: 'POST',
  1337. headers: { 'Content-Type': 'application/json' },
  1338. body: JSON.stringify({
  1339. orig_name: origName,
  1340. name,
  1341. listen_port: port,
  1342. address: addr,
  1343. mtu,
  1344. comment,
  1345. public_key: pub,
  1346. private_key: priv,
  1347. disabled
  1348. })
  1349. });
  1350. const data = await res.json();
  1351. if (res.ok) {
  1352. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1353. closeAddWGInterfaceModal();
  1354. loadWireGuard(false);
  1355. fetchData(false);
  1356. } else {
  1357. showToast('Error', data.error || 'Failed to save interface', 'error');
  1358. }
  1359. } catch (err) {
  1360. showToast('Error', err.message, 'error');
  1361. }
  1362. }
  1363. async function startWGInterface(name) {
  1364. try {
  1365. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1366. if (res.ok) {
  1367. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1368. loadWireGuard(false);
  1369. fetchData(false);
  1370. }
  1371. } catch (err) {
  1372. showToast('Error', err.message, 'error');
  1373. }
  1374. }
  1375. async function stopWGInterface(name) {
  1376. try {
  1377. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1378. if (res.ok) {
  1379. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1380. loadWireGuard(false);
  1381. fetchData(false);
  1382. }
  1383. } catch (err) {
  1384. showToast('Error', err.message, 'error');
  1385. }
  1386. }
  1387. async function toggleWGInterfaceState(name, enable) {
  1388. try {
  1389. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1390. method: 'POST',
  1391. headers: { 'Content-Type': 'application/json' },
  1392. body: JSON.stringify({ enabled: enable })
  1393. });
  1394. if (res.ok) {
  1395. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1396. loadWireGuard(false);
  1397. fetchData(false);
  1398. }
  1399. } catch (err) {
  1400. showToast('Error', err.message, 'error');
  1401. }
  1402. }
  1403. async function deleteWGInterface(name) {
  1404. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1405. try {
  1406. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1407. if (res.ok) {
  1408. showToast('Deleted', `Interface ${name} removed`, 'success');
  1409. loadWireGuard(false);
  1410. fetchData(false);
  1411. }
  1412. } catch (err) {
  1413. showToast('Error', err.message, 'error');
  1414. }
  1415. }
  1416. function populateWGPeerIfaceSelect(selectedIface = '') {
  1417. const sel = document.getElementById('wg-peer-modal-iface');
  1418. if (!sel) return;
  1419. sel.innerHTML = '';
  1420. (state.wgInterfaces || []).forEach(i => {
  1421. const opt = document.createElement('option');
  1422. opt.value = i.name;
  1423. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1424. if (i.name === selectedIface) opt.selected = true;
  1425. sel.appendChild(opt);
  1426. });
  1427. }
  1428. function openAddWGPeerModal() {
  1429. if ((state.wgInterfaces || []).length === 0) {
  1430. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1431. openAddWGInterfaceModal();
  1432. return;
  1433. }
  1434. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  1435. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  1436. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  1437. populateWGPeerIfaceSelect();
  1438. document.getElementById('wg-peer-modal-name').value = '';
  1439. document.getElementById('wg-peer-modal-pubkey').value = '';
  1440. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1441. document.getElementById('wg-peer-modal-endpoint').value = '';
  1442. document.getElementById('wg-peer-modal-port').value = '';
  1443. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1444. document.getElementById('wg-peer-modal-preshared').value = '';
  1445. document.getElementById('wg-peer-modal-disabled').checked = false;
  1446. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1447. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1448. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1449. }
  1450. function openEditWGPeerModal(ifaceName, pubKey) {
  1451. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  1452. if (!peer) {
  1453. showToast('Not Found', 'Peer not found', 'warning');
  1454. return;
  1455. }
  1456. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  1457. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  1458. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  1459. populateWGPeerIfaceSelect(peer.interface);
  1460. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  1461. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  1462. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  1463. document.getElementById('wg-peer-modal-endpoint').value = peer.endpoint_address || '';
  1464. document.getElementById('wg-peer-modal-port').value = peer.endpoint_port || '';
  1465. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  1466. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  1467. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  1468. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1469. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1470. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1471. }
  1472. function closeAddWGPeerModal() {
  1473. document.getElementById('wg-peer-modal').classList.add('hidden');
  1474. }
  1475. async function generatePeerKeypairHelper() {
  1476. try {
  1477. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1478. const keys = await res.json();
  1479. if (res.ok) {
  1480. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  1481. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  1482. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  1483. checkWGPeerKeyValidity();
  1484. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  1485. }
  1486. } catch (err) {
  1487. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1488. }
  1489. }
  1490. function copyGeneratedPeerPrivKey() {
  1491. const priv = document.getElementById('wg-peer-gen-privkey').value;
  1492. if (priv) copyToClipboard(priv, 'Client Private Key');
  1493. }
  1494. async function generatePeerPSK() {
  1495. try {
  1496. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1497. const keys = await res.json();
  1498. if (res.ok && keys.private_key) {
  1499. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  1500. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  1501. }
  1502. } catch (err) {
  1503. showToast('Error', err.message, 'error');
  1504. }
  1505. }
  1506. function checkWGPeerKeyValidity() {
  1507. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  1508. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1509. const warningEl = document.getElementById('wg-peer-key-warning');
  1510. if (!warningEl) return;
  1511. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  1512. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  1513. warningEl.classList.remove('hidden');
  1514. } else {
  1515. warningEl.classList.add('hidden');
  1516. }
  1517. }
  1518. async function submitSaveWGPeer(e) {
  1519. e.preventDefault();
  1520. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  1521. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  1522. const iface = document.getElementById('wg-peer-modal-iface').value;
  1523. const name = document.getElementById('wg-peer-modal-name').value.trim();
  1524. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1525. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  1526. .split(',')
  1527. .map(s => s.trim())
  1528. .filter(s => s.length > 0);
  1529. const epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  1530. const epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  1531. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  1532. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  1533. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  1534. // Validation
  1535. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  1536. if (targetIface && targetIface.public_key === pub) {
  1537. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  1538. return;
  1539. }
  1540. try {
  1541. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  1542. method: 'POST',
  1543. headers: { 'Content-Type': 'application/json' },
  1544. body: JSON.stringify({
  1545. orig_interface: origIface,
  1546. orig_public_key: origPubKey,
  1547. interface: iface,
  1548. name,
  1549. public_key: pub,
  1550. allowed_ips: allowed,
  1551. endpoint_address: epHost,
  1552. endpoint_port: epPort,
  1553. persistent_keepalive: keepalive,
  1554. preshared_key: psk,
  1555. disabled
  1556. })
  1557. });
  1558. const data = await res.json();
  1559. if (res.ok) {
  1560. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  1561. closeAddWGPeerModal();
  1562. loadWireGuard(false);
  1563. } else {
  1564. showToast('Error', data.error || 'Failed to save peer', 'error');
  1565. }
  1566. } catch (err) {
  1567. showToast('Error', err.message, 'error');
  1568. }
  1569. }
  1570. async function toggleWGPeerState(iface, pubkey, enable) {
  1571. try {
  1572. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  1573. method: 'POST',
  1574. headers: { 'Content-Type': 'application/json' },
  1575. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  1576. });
  1577. const data = await res.json();
  1578. if (res.ok) {
  1579. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  1580. loadWireGuard(false);
  1581. } else {
  1582. showToast('Error', data.error || 'Failed to update peer state', 'error');
  1583. }
  1584. } catch (err) {
  1585. showToast('Error', err.message, 'error');
  1586. }
  1587. }
  1588. async function deleteWGPeer(iface, pubkey) {
  1589. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  1590. try {
  1591. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  1592. method: 'POST',
  1593. headers: { 'Content-Type': 'application/json' },
  1594. body: JSON.stringify({ interface: iface, public_key: pubkey })
  1595. });
  1596. const data = await res.json();
  1597. if (res.ok) {
  1598. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  1599. loadWireGuard(false);
  1600. } else {
  1601. showToast('Error', data.error || 'Failed to remove peer', 'error');
  1602. }
  1603. } catch (err) {
  1604. showToast('Error', err.message, 'error');
  1605. }
  1606. }
  1607. // ======================== IPSec Multi-Tunnel ========================
  1608. async function loadIPSec(populateInputs = true) {
  1609. try {
  1610. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1611. const list = await res.json();
  1612. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1613. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1614. const badge = document.getElementById('ipsec-sas-badge');
  1615. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1616. const tbody = document.getElementById('ipsec-table-body');
  1617. const empty = document.getElementById('ipsec-empty');
  1618. if (!tbody) return;
  1619. tbody.innerHTML = '';
  1620. if (state.ipsecTunnels.length === 0) {
  1621. if (empty) empty.classList.remove('hidden');
  1622. } else {
  1623. if (empty) empty.classList.add('hidden');
  1624. state.ipsecTunnels.forEach(c => {
  1625. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1626. const tr = document.createElement('tr');
  1627. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1628. tr.innerHTML = `
  1629. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isEstablished, c.disabled)}</td>
  1630. <td class="py-2.5 px-4 font-bold text-white">${c.name}</td>
  1631. <td class="py-2.5 px-4 text-emerald-400 font-mono">${c.local_subnet || '-'}</td>
  1632. <td class="py-2.5 px-4 text-slate-300 font-mono">${c.remote_addrs || '-'}</td>
  1633. <td class="py-2.5 px-4 text-cyan-400 font-mono">${c.remote_subnet || '-'}</td>
  1634. <td class="py-2.5 px-4 font-sans">
  1635. <span class="px-2 py-0.5 rounded-full text-[10px] font-semibold ${
  1636. isEstablished ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-slate-800 text-slate-400'
  1637. }">${c.status || (isEstablished ? 'ESTABLISHED' : 'DISCONNECTED')}</span>
  1638. </td>
  1639. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  1640. ${isEstablished ? `
  1641. <button onclick="stopIPSecTunnel('${c.name}')" class="text-xs text-rose-400 hover:text-rose-300">Terminate</button>
  1642. ` : `
  1643. <button onclick="startIPSecTunnel('${c.name}')" class="text-xs bg-amber-600/30 hover:bg-amber-600/50 text-amber-300 px-2 py-0.5 rounded border border-amber-500/30">Initiate</button>
  1644. `}
  1645. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1646. ${c.disabled ? 'Enable' : 'Disable'}
  1647. </button>
  1648. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1649. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1650. </td>
  1651. `;
  1652. tbody.appendChild(tr);
  1653. });
  1654. }
  1655. } catch (err) {
  1656. console.error('Failed to load IPSec:', err);
  1657. }
  1658. }
  1659. function openAddIPSecModal() {
  1660. document.getElementById('ipsec-modal-title').innerText = 'Configure IPSec IKEv2 Tunnel';
  1661. document.getElementById('ipsec-modal-name').value = `ipsec-${(state.ipsecTunnels || []).length + 1}`;
  1662. document.getElementById('ipsec-modal-name').readOnly = false;
  1663. document.getElementById('ipsec-modal-localts').value = '192.168.10.0/24';
  1664. document.getElementById('ipsec-modal-remotets').value = '192.168.20.0/24';
  1665. document.getElementById('ipsec-modal-remotegw').value = '';
  1666. document.getElementById('ipsec-modal-psk').value = '';
  1667. document.getElementById('ipsec-modal-ikeprop').value = 'aes256-sha256-modp2048,default';
  1668. document.getElementById('ipsec-modal-espprop').value = 'aes256-sha256-modp2048,default';
  1669. document.getElementById('ipsec-modal-autostart').checked = true;
  1670. document.getElementById('ipsec-modal-disabled').checked = false;
  1671. document.getElementById('ipsec-modal').classList.remove('hidden');
  1672. }
  1673. function openEditIPSecModal(name) {
  1674. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  1675. if (!conn) return;
  1676. document.getElementById('ipsec-modal-title').innerText = `Edit IPSec Tunnel: ${name}`;
  1677. document.getElementById('ipsec-modal-name').value = conn.name;
  1678. document.getElementById('ipsec-modal-name').readOnly = true;
  1679. document.getElementById('ipsec-modal-localts').value = conn.local_subnet || '';
  1680. document.getElementById('ipsec-modal-remotets').value = conn.remote_subnet || '';
  1681. document.getElementById('ipsec-modal-remotegw').value = conn.remote_addrs || '';
  1682. document.getElementById('ipsec-modal-psk').value = conn.preshared_key || '';
  1683. document.getElementById('ipsec-modal-ikeprop').value = conn.ike_proposals || 'aes256-sha256-modp2048,default';
  1684. document.getElementById('ipsec-modal-espprop').value = conn.esp_proposals || 'aes256-sha256-modp2048,default';
  1685. document.getElementById('ipsec-modal-autostart').checked = conn.auto_start ?? true;
  1686. document.getElementById('ipsec-modal-disabled').checked = !!conn.disabled;
  1687. document.getElementById('ipsec-modal').classList.remove('hidden');
  1688. }
  1689. function closeAddIPSecModal() {
  1690. document.getElementById('ipsec-modal').classList.add('hidden');
  1691. }
  1692. async function submitSaveIPSec(e) {
  1693. e.preventDefault();
  1694. const name = document.getElementById('ipsec-modal-name').value.trim();
  1695. const localts = document.getElementById('ipsec-modal-localts').value.trim();
  1696. const remotets = document.getElementById('ipsec-modal-remotets').value.trim();
  1697. const remotegw = document.getElementById('ipsec-modal-remotegw').value.trim();
  1698. const psk = document.getElementById('ipsec-modal-psk').value;
  1699. const ike = document.getElementById('ipsec-modal-ikeprop').value.trim();
  1700. const esp = document.getElementById('ipsec-modal-espprop').value.trim();
  1701. const autostart = document.getElementById('ipsec-modal-autostart').checked;
  1702. const disabled = document.getElementById('ipsec-modal-disabled').checked;
  1703. try {
  1704. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  1705. method: 'POST',
  1706. headers: { 'Content-Type': 'application/json' },
  1707. body: JSON.stringify({
  1708. name,
  1709. local_addrs: '%any',
  1710. remote_addrs: remotegw,
  1711. local_subnet: localts,
  1712. remote_subnet: remotets,
  1713. preshared_key: psk,
  1714. ike_proposals: ike,
  1715. esp_proposals: esp,
  1716. auto_start: autostart,
  1717. disabled
  1718. })
  1719. });
  1720. if (res.ok) {
  1721. showToast('IPSec Saved', `Tunnel ${name} configured`, 'success');
  1722. closeAddIPSecModal();
  1723. loadIPSec(false);
  1724. fetchData(false);
  1725. }
  1726. } catch (err) {
  1727. showToast('Error', err.message, 'error');
  1728. }
  1729. }
  1730. async function startIPSecTunnel(name) {
  1731. try {
  1732. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1733. if (res.ok) {
  1734. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  1735. setTimeout(() => loadIPSec(false), 2000);
  1736. }
  1737. } catch (err) {
  1738. showToast('Error', err.message, 'error');
  1739. }
  1740. }
  1741. async function stopIPSecTunnel(name) {
  1742. try {
  1743. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1744. if (res.ok) {
  1745. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  1746. loadIPSec(false);
  1747. }
  1748. } catch (err) {
  1749. showToast('Error', err.message, 'error');
  1750. }
  1751. }
  1752. async function toggleIPSecState(name, enable) {
  1753. try {
  1754. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  1755. method: 'POST',
  1756. headers: { 'Content-Type': 'application/json' },
  1757. body: JSON.stringify({ enabled: enable })
  1758. });
  1759. if (res.ok) {
  1760. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  1761. loadIPSec(false);
  1762. }
  1763. } catch (err) {
  1764. showToast('Error', err.message, 'error');
  1765. }
  1766. }
  1767. async function deleteIPSecConn(name) {
  1768. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  1769. try {
  1770. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1771. if (res.ok) {
  1772. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  1773. loadIPSec(false);
  1774. fetchData(false);
  1775. }
  1776. } catch (err) {
  1777. showToast('Error', err.message, 'error');
  1778. }
  1779. }
  1780. // ======================== L2TP Multi-Instance ========================
  1781. async function loadL2TP(populateInputs = true) {
  1782. try {
  1783. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  1784. const list = await res.json();
  1785. state.l2tpList = Array.isArray(list) ? list : [];
  1786. const badge = document.getElementById('l2tp-count-badge');
  1787. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  1788. const tbody = document.getElementById('l2tp-table-body');
  1789. const empty = document.getElementById('l2tp-empty');
  1790. if (!tbody) return;
  1791. tbody.innerHTML = '';
  1792. if (state.l2tpList.length === 0) {
  1793. if (empty) empty.classList.remove('hidden');
  1794. } else {
  1795. if (empty) empty.classList.add('hidden');
  1796. state.l2tpList.forEach(inst => {
  1797. const tr = document.createElement('tr');
  1798. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1799. tr.innerHTML = `
  1800. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1801. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1802. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.connect_to}</td>
  1803. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1804. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1805. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1806. <td class="py-2.5 px-3 text-center">
  1807. <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'}">
  1808. ${inst.default_route ? 'Yes' : 'No'}
  1809. </span>
  1810. </td>
  1811. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1812. ${inst.running ? `
  1813. <button onclick="disconnectL2TPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1814. ` : `
  1815. <button onclick="connectL2TPInstance('${inst.name}')" class="text-xs bg-cyan-600/30 hover:bg-cyan-600/50 text-cyan-300 px-2 py-0.5 rounded border border-cyan-500/30">Connect</button>
  1816. `}
  1817. <button onclick="toggleL2TPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1818. ${inst.disabled ? 'Enable' : 'Disable'}
  1819. </button>
  1820. <button onclick="openEditL2TPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1821. <button onclick="deleteL2TPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1822. </td>
  1823. `;
  1824. tbody.appendChild(tr);
  1825. });
  1826. }
  1827. } catch (err) {
  1828. console.error('Failed to load L2TP:', err);
  1829. }
  1830. }
  1831. function openAddL2TPModal() {
  1832. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  1833. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  1834. document.getElementById('l2tp-modal-name').readOnly = false;
  1835. document.getElementById('l2tp-modal-server').value = '';
  1836. document.getElementById('l2tp-modal-user').value = '';
  1837. document.getElementById('l2tp-modal-pass').value = '';
  1838. document.getElementById('l2tp-modal-ipsec').value = '';
  1839. document.getElementById('l2tp-modal-defroute').checked = true;
  1840. document.getElementById('l2tp-modal-disabled').checked = false;
  1841. document.getElementById('l2tp-modal').classList.remove('hidden');
  1842. }
  1843. function openEditL2TPModal(name) {
  1844. const inst = (state.l2tpList || []).find(i => i.name === name);
  1845. if (!inst) return;
  1846. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  1847. document.getElementById('l2tp-modal-name').value = inst.name;
  1848. document.getElementById('l2tp-modal-name').readOnly = true;
  1849. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  1850. document.getElementById('l2tp-modal-user').value = inst.username || '';
  1851. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  1852. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  1853. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  1854. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  1855. document.getElementById('l2tp-modal').classList.remove('hidden');
  1856. }
  1857. function closeL2TPModal() {
  1858. document.getElementById('l2tp-modal').classList.add('hidden');
  1859. }
  1860. async function submitSaveL2TP(e) {
  1861. e.preventDefault();
  1862. const name = document.getElementById('l2tp-modal-name').value.trim();
  1863. const server = document.getElementById('l2tp-modal-server').value.trim();
  1864. const user = document.getElementById('l2tp-modal-user').value.trim();
  1865. const pass = document.getElementById('l2tp-modal-pass').value;
  1866. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  1867. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  1868. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  1869. try {
  1870. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  1871. method: 'POST',
  1872. headers: { 'Content-Type': 'application/json' },
  1873. body: JSON.stringify({
  1874. name,
  1875. connect_to: server,
  1876. username: user,
  1877. password: pass,
  1878. ipsec_secret: ipsec,
  1879. default_route: defRoute,
  1880. disabled
  1881. })
  1882. });
  1883. if (res.ok) {
  1884. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  1885. closeL2TPModal();
  1886. loadL2TP(false);
  1887. fetchData(false);
  1888. }
  1889. } catch (err) {
  1890. showToast('Error', err.message, 'error');
  1891. }
  1892. }
  1893. async function connectL2TPInstance(name) {
  1894. try {
  1895. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1896. if (res.ok) {
  1897. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  1898. setTimeout(() => loadL2TP(false), 2000);
  1899. }
  1900. } catch (err) {
  1901. showToast('Error', err.message, 'error');
  1902. }
  1903. }
  1904. async function disconnectL2TPInstance(name) {
  1905. try {
  1906. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1907. if (res.ok) {
  1908. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  1909. loadL2TP(false);
  1910. }
  1911. } catch (err) {
  1912. showToast('Error', err.message, 'error');
  1913. }
  1914. }
  1915. async function toggleL2TPState(name, enable) {
  1916. try {
  1917. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  1918. method: 'POST',
  1919. headers: { 'Content-Type': 'application/json' },
  1920. body: JSON.stringify({ enabled: enable })
  1921. });
  1922. if (res.ok) {
  1923. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1924. loadL2TP(false);
  1925. }
  1926. } catch (err) {
  1927. showToast('Error', err.message, 'error');
  1928. }
  1929. }
  1930. async function deleteL2TPInstance(name) {
  1931. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  1932. try {
  1933. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1934. if (res.ok) {
  1935. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  1936. loadL2TP(false);
  1937. fetchData(false);
  1938. }
  1939. } catch (err) {
  1940. showToast('Error', err.message, 'error');
  1941. }
  1942. }
  1943. // ======================== PPTP Multi-Instance ========================
  1944. async function loadPPTP(populateInputs = true) {
  1945. try {
  1946. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  1947. const list = await res.json();
  1948. state.pptpList = Array.isArray(list) ? list : [];
  1949. const badge = document.getElementById('pptp-count-badge');
  1950. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  1951. const tbody = document.getElementById('pptp-table-body');
  1952. const empty = document.getElementById('pptp-empty');
  1953. if (!tbody) return;
  1954. tbody.innerHTML = '';
  1955. if (state.pptpList.length === 0) {
  1956. if (empty) empty.classList.remove('hidden');
  1957. } else {
  1958. if (empty) empty.classList.add('hidden');
  1959. state.pptpList.forEach(inst => {
  1960. const tr = document.createElement('tr');
  1961. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1962. tr.innerHTML = `
  1963. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1964. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1965. <td class="py-2.5 px-3 text-purple-400 font-mono">${inst.connect_to}</td>
  1966. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1967. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1968. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1969. <td class="py-2.5 px-3 text-center">
  1970. <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'}">
  1971. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  1972. </span>
  1973. </td>
  1974. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1975. ${inst.running ? `
  1976. <button onclick="disconnectPPTPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1977. ` : `
  1978. <button onclick="connectPPTPInstance('${inst.name}')" class="text-xs bg-purple-600/30 hover:bg-purple-600/50 text-purple-300 px-2 py-0.5 rounded border border-purple-500/30">Connect</button>
  1979. `}
  1980. <button onclick="togglePPTPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1981. ${inst.disabled ? 'Enable' : 'Disable'}
  1982. </button>
  1983. <button onclick="openEditPPTPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1984. <button onclick="deletePPTPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1985. </td>
  1986. `;
  1987. tbody.appendChild(tr);
  1988. });
  1989. }
  1990. } catch (err) {
  1991. console.error('Failed to load PPTP:', err);
  1992. }
  1993. }
  1994. function openAddPPTPModal() {
  1995. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  1996. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  1997. document.getElementById('pptp-modal-name').readOnly = false;
  1998. document.getElementById('pptp-modal-server').value = '';
  1999. document.getElementById('pptp-modal-user').value = '';
  2000. document.getElementById('pptp-modal-pass').value = '';
  2001. document.getElementById('pptp-modal-mppe').checked = true;
  2002. document.getElementById('pptp-modal-defroute').checked = true;
  2003. document.getElementById('pptp-modal-disabled').checked = false;
  2004. document.getElementById('pptp-modal').classList.remove('hidden');
  2005. }
  2006. function openEditPPTPModal(name) {
  2007. const inst = (state.pptpList || []).find(i => i.name === name);
  2008. if (!inst) return;
  2009. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2010. document.getElementById('pptp-modal-name').value = inst.name;
  2011. document.getElementById('pptp-modal-name').readOnly = true;
  2012. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2013. document.getElementById('pptp-modal-user').value = inst.username || '';
  2014. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2015. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2016. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2017. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2018. document.getElementById('pptp-modal').classList.remove('hidden');
  2019. }
  2020. function closePPTPModal() {
  2021. document.getElementById('pptp-modal').classList.add('hidden');
  2022. }
  2023. async function submitSavePPTP(e) {
  2024. e.preventDefault();
  2025. const name = document.getElementById('pptp-modal-name').value.trim();
  2026. const server = document.getElementById('pptp-modal-server').value.trim();
  2027. const user = document.getElementById('pptp-modal-user').value.trim();
  2028. const pass = document.getElementById('pptp-modal-pass').value;
  2029. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2030. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2031. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2032. try {
  2033. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2034. method: 'POST',
  2035. headers: { 'Content-Type': 'application/json' },
  2036. body: JSON.stringify({
  2037. name,
  2038. connect_to: server,
  2039. username: user,
  2040. password: pass,
  2041. require_mppe: mppe,
  2042. default_route: defRoute,
  2043. auto_reconnect: true,
  2044. disabled
  2045. })
  2046. });
  2047. if (res.ok) {
  2048. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2049. closePPTPModal();
  2050. loadPPTP(false);
  2051. fetchData(false);
  2052. }
  2053. } catch (err) {
  2054. showToast('Error', err.message, 'error');
  2055. }
  2056. }
  2057. async function connectPPTPInstance(name) {
  2058. try {
  2059. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2060. if (res.ok) {
  2061. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2062. setTimeout(() => loadPPTP(false), 2000);
  2063. }
  2064. } catch (err) {
  2065. showToast('Error', err.message, 'error');
  2066. }
  2067. }
  2068. async function disconnectPPTPInstance(name) {
  2069. try {
  2070. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2071. if (res.ok) {
  2072. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2073. loadPPTP(false);
  2074. }
  2075. } catch (err) {
  2076. showToast('Error', err.message, 'error');
  2077. }
  2078. }
  2079. async function togglePPTPState(name, enable) {
  2080. try {
  2081. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2082. method: 'POST',
  2083. headers: { 'Content-Type': 'application/json' },
  2084. body: JSON.stringify({ enabled: enable })
  2085. });
  2086. if (res.ok) {
  2087. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2088. loadPPTP(false);
  2089. }
  2090. } catch (err) {
  2091. showToast('Error', err.message, 'error');
  2092. }
  2093. }
  2094. async function deletePPTPInstance(name) {
  2095. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2096. try {
  2097. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2098. if (res.ok) {
  2099. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2100. loadPPTP(false);
  2101. fetchData(false);
  2102. }
  2103. } catch (err) {
  2104. showToast('Error', err.message, 'error');
  2105. }
  2106. }
  2107. // ---------------- Modal & Helper Functions ----------------
  2108. function openVlanModal(defaultParent = '') {
  2109. const select = document.getElementById('vlan-parent');
  2110. select.innerHTML = '';
  2111. const allIfaces = state.interfaces || [];
  2112. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2113. if (eligible.length === 0) {
  2114. const opt = document.createElement('option');
  2115. opt.value = '';
  2116. opt.innerText = 'No VLAN-capable interfaces available';
  2117. select.appendChild(opt);
  2118. } else {
  2119. eligible.forEach(i => {
  2120. const opt = document.createElement('option');
  2121. opt.value = i.name;
  2122. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2123. if (i.name === defaultParent) opt.selected = true;
  2124. select.appendChild(opt);
  2125. });
  2126. }
  2127. document.getElementById('vlan-id').value = '';
  2128. document.getElementById('vlan-name').value = '';
  2129. document.getElementById('vlan-ip').value = '';
  2130. document.getElementById('vlan-desc').value = '';
  2131. autoSuggestVlanName();
  2132. document.getElementById('vlan-modal').classList.remove('hidden');
  2133. }
  2134. function closeVlanModal() {
  2135. document.getElementById('vlan-modal').classList.add('hidden');
  2136. }
  2137. function autoSuggestVlanName() {
  2138. const parent = document.getElementById('vlan-parent').value;
  2139. if (!parent) return;
  2140. const id = document.getElementById('vlan-id').value;
  2141. const nameInput = document.getElementById('vlan-name');
  2142. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  2143. }
  2144. function setSubnetPreset(cidr) {
  2145. const ipInput = document.getElementById('vlan-ip');
  2146. const id = document.getElementById('vlan-id').value || '10';
  2147. ipInput.value = `192.168.${id}.1${cidr}`;
  2148. }
  2149. async function submitCreateVlan(e) {
  2150. e.preventDefault();
  2151. const btn = document.getElementById('vlan-submit-btn');
  2152. btn.disabled = true;
  2153. btn.innerText = 'Creating...';
  2154. const parent = document.getElementById('vlan-parent').value;
  2155. if (!parent) {
  2156. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  2157. btn.disabled = false;
  2158. btn.innerText = 'Create VLAN';
  2159. return;
  2160. }
  2161. const id = parseInt(document.getElementById('vlan-id').value, 10);
  2162. const name = document.getElementById('vlan-name').value.trim();
  2163. const ip = document.getElementById('vlan-ip').value.trim();
  2164. const role = document.getElementById('vlan-role').value;
  2165. const desc = document.getElementById('vlan-desc').value.trim();
  2166. try {
  2167. const res = await fetch(`${API_BASE}/vlans`, {
  2168. method: 'POST',
  2169. headers: { 'Content-Type': 'application/json' },
  2170. body: JSON.stringify({
  2171. parent_name: parent,
  2172. vlan_id: id,
  2173. name: name,
  2174. ip_address: ip,
  2175. role: role,
  2176. description: desc,
  2177. mtu: 1500,
  2178. auto_up: true
  2179. })
  2180. });
  2181. const data = await res.json();
  2182. if (res.ok) {
  2183. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  2184. state.expandedParents.add(parent);
  2185. closeVlanModal();
  2186. await fetchData(true);
  2187. if (state.activeTab !== 'interfaces') navigate('interfaces');
  2188. } else {
  2189. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  2190. }
  2191. } catch (err) {
  2192. showToast('Error', err.message, 'error');
  2193. } finally {
  2194. btn.disabled = false;
  2195. btn.innerText = 'Create VLAN';
  2196. }
  2197. }
  2198. async function confirmDeleteVlan(name) {
  2199. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  2200. try {
  2201. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2202. if (res.ok) {
  2203. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  2204. closeIfaceModal();
  2205. fetchData(true);
  2206. }
  2207. } catch (err) {
  2208. showToast('Error', err.message, 'error');
  2209. }
  2210. }
  2211. function openIfaceModal(name) {
  2212. const iface = (state.interfaces || []).find(i => i.name === name);
  2213. if (!iface) return;
  2214. state.currentModalIface = iface.name;
  2215. document.getElementById('modal-iface-name').innerText = iface.name;
  2216. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  2217. document.getElementById('modal-iface-mtu').value = iface.mtu;
  2218. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  2219. document.getElementById('modal-iface-desc').value = iface.description || '';
  2220. const delBtn = document.getElementById('modal-delete-vlan-btn');
  2221. if (iface.is_vlan) {
  2222. delBtn.classList.remove('hidden');
  2223. } else {
  2224. delBtn.classList.add('hidden');
  2225. }
  2226. renderModalIPs(iface);
  2227. document.getElementById('iface-modal').classList.remove('hidden');
  2228. }
  2229. function renderModalIPs(iface) {
  2230. const container = document.getElementById('modal-ip-list');
  2231. container.innerHTML = '';
  2232. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  2233. if (addrs.length === 0) {
  2234. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  2235. return;
  2236. }
  2237. addrs.forEach(addr => {
  2238. const row = document.createElement('div');
  2239. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  2240. row.innerHTML = `
  2241. <span class="text-white">${addr}</span>
  2242. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  2243. `;
  2244. container.appendChild(row);
  2245. });
  2246. }
  2247. function closeIfaceModal() {
  2248. document.getElementById('iface-modal').classList.add('hidden');
  2249. state.currentModalIface = null;
  2250. }
  2251. async function setIfaceState(name, newState) {
  2252. await toggleInterfaceState(name, newState);
  2253. const updated = (state.interfaces || []).find(i => i.name === name);
  2254. if (updated) openIfaceModal(name);
  2255. }
  2256. async function applyMTU() {
  2257. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  2258. try {
  2259. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  2260. method: 'POST',
  2261. headers: { 'Content-Type': 'application/json' },
  2262. body: JSON.stringify({ mtu })
  2263. });
  2264. if (res.ok) {
  2265. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  2266. fetchData(false);
  2267. }
  2268. } catch (err) {
  2269. showToast('Error', err.message, 'error');
  2270. }
  2271. }
  2272. async function addInterfaceIP() {
  2273. const ip = document.getElementById('modal-new-ip').value.trim();
  2274. if (!ip) return;
  2275. try {
  2276. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2277. method: 'POST',
  2278. headers: { 'Content-Type': 'application/json' },
  2279. body: JSON.stringify({ ip })
  2280. });
  2281. if (res.ok) {
  2282. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  2283. document.getElementById('modal-new-ip').value = '';
  2284. await fetchData(false);
  2285. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2286. if (iface) renderModalIPs(iface);
  2287. } else {
  2288. const err = await res.json();
  2289. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  2290. }
  2291. } catch (err) {
  2292. showToast('Error', err.message, 'error');
  2293. }
  2294. }
  2295. async function removeInterfaceIP(ip) {
  2296. if (!confirm(`Remove IP ${ip}?`)) return;
  2297. try {
  2298. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2299. method: 'DELETE',
  2300. headers: { 'Content-Type': 'application/json' },
  2301. body: JSON.stringify({ ip })
  2302. });
  2303. if (res.ok) {
  2304. showToast('IP Removed', `Removed ${ip}`, 'success');
  2305. await fetchData(false);
  2306. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2307. if (iface) renderModalIPs(iface);
  2308. }
  2309. } catch (err) {
  2310. showToast('Error', err.message, 'error');
  2311. }
  2312. }
  2313. async function saveInterfaceMetadata() {
  2314. const role = document.getElementById('modal-iface-role').value;
  2315. const desc = document.getElementById('modal-iface-desc').value.trim();
  2316. try {
  2317. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/metadata`, {
  2318. method: 'POST',
  2319. headers: { 'Content-Type': 'application/json' },
  2320. body: JSON.stringify({ role, description: desc })
  2321. });
  2322. if (res.ok) {
  2323. showToast('Saved', 'Metadata updated', 'success');
  2324. closeIfaceModal();
  2325. fetchData(false);
  2326. }
  2327. } catch (err) {
  2328. showToast('Error', err.message, 'error');
  2329. }
  2330. }
  2331. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  2332. state.fwSubTab = 'filter';
  2333. state.routesSubTab = 'routes';
  2334. function renderRuleFlag(disabled, hasComment) {
  2335. let flags = '';
  2336. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  2337. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  2338. return flags || '<span class="text-slate-600">-</span>';
  2339. }
  2340. function renderActionBadge(action) {
  2341. const act = (action || '').toLowerCase();
  2342. let color = 'bg-slate-800 text-slate-300';
  2343. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  2344. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  2345. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  2346. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  2347. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  2348. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  2349. }
  2350. function switchFWSubTab(tab) {
  2351. state.fwSubTab = tab;
  2352. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  2353. tabs.forEach(t => {
  2354. const panel = document.getElementById(`fw-subtab-${t}`);
  2355. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  2356. if (panel) {
  2357. if (t === tab) panel.classList.remove('hidden');
  2358. else panel.classList.add('hidden');
  2359. }
  2360. if (btn) {
  2361. if (t === tab) {
  2362. 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';
  2363. } else {
  2364. 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';
  2365. }
  2366. }
  2367. });
  2368. const addBtn = document.getElementById('fw-primary-add-btn');
  2369. if (addBtn) {
  2370. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  2371. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  2372. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  2373. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  2374. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  2375. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  2376. }
  2377. if (tab === 'geo') loadGeoIP();
  2378. if (tab === 'connections') loadConnections();
  2379. }
  2380. function openCurrentFWModal() {
  2381. if (state.fwSubTab === 'filter') openAddFilterModal();
  2382. else if (state.fwSubTab === 'nat') openAddNATModal();
  2383. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  2384. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  2385. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  2386. else if (state.fwSubTab === 'connections') loadConnections();
  2387. }
  2388. async function loadFirewall(populateDropdowns = true) {
  2389. try {
  2390. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  2391. fetch(`${API_BASE}/firewall/summary`),
  2392. fetch(`${API_BASE}/firewall/filter`),
  2393. fetch(`${API_BASE}/firewall/nat`),
  2394. fetch(`${API_BASE}/firewall/mangle`),
  2395. fetch(`${API_BASE}/firewall/address-lists`),
  2396. fetch(`${API_BASE}/firewall/geoip/status`),
  2397. fetch(`${API_BASE}/firewall/geoip/countries`)
  2398. ]);
  2399. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  2400. if (filterRes.ok) state.filterRules = await filterRes.json();
  2401. if (natRes.ok) state.natRules = await natRes.json();
  2402. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  2403. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  2404. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  2405. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  2406. // Badges
  2407. const bFilter = document.getElementById('fw-badge-filter');
  2408. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  2409. const bNat = document.getElementById('fw-badge-nat');
  2410. if (bNat) bNat.innerText = (state.natRules || []).length;
  2411. const bMangle = document.getElementById('fw-badge-mangle');
  2412. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  2413. const bAddr = document.getElementById('fw-badge-addrlist');
  2414. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  2415. const bGeo = document.getElementById('fw-badge-geo');
  2416. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  2417. renderFilterRules();
  2418. renderNATRules();
  2419. renderMangleRules();
  2420. renderAddressLists();
  2421. renderGeoCountries();
  2422. if (state.fwSubTab === 'connections') {
  2423. loadConnections();
  2424. }
  2425. } catch (err) {
  2426. console.error('Failed to load firewall:', err);
  2427. }
  2428. }
  2429. // ----------------- Filter Rules -----------------
  2430. function renderFilterRules() {
  2431. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  2432. const tbody = document.getElementById('filter-table-body');
  2433. const empty = document.getElementById('filter-empty');
  2434. if (!tbody) return;
  2435. tbody.innerHTML = '';
  2436. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2437. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2438. if (rules.length === 0) {
  2439. empty?.classList.remove('hidden');
  2440. return;
  2441. }
  2442. empty?.classList.add('hidden');
  2443. rules.forEach((r, idx) => {
  2444. const tr = document.createElement('tr');
  2445. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2446. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2447. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2448. tr.innerHTML = `
  2449. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2450. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2451. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2452. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2453. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2454. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2455. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2456. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2457. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2458. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2459. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2460. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2461. </td>
  2462. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2463. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2464. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2465. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2466. <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>
  2467. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2468. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2469. </td>
  2470. `;
  2471. tbody.appendChild(tr);
  2472. });
  2473. }
  2474. function formatTarget(addr, list, geo) {
  2475. const parts = [];
  2476. if (addr) parts.push(`<span>${addr}</span>`);
  2477. if (list) {
  2478. const inv = list.startsWith('!') ? '!' : '';
  2479. const clean = list.replace(/^!/, '');
  2480. 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>`);
  2481. }
  2482. if (geo) {
  2483. const inv = geo.startsWith('!') ? '!' : '';
  2484. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  2485. 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>`);
  2486. }
  2487. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  2488. return parts.join(' ');
  2489. }
  2490. function populateInterfaceSelect(selectId, currentVal = '') {
  2491. const sel = document.getElementById(selectId);
  2492. if (!sel) return;
  2493. sel.innerHTML = '<option value="">(Any Interface)</option>';
  2494. (state.interfaces || []).forEach(i => {
  2495. const opt = document.createElement('option');
  2496. opt.value = i.name;
  2497. opt.innerText = `${i.name} (${i.role || i.type})`;
  2498. if (i.name === currentVal) opt.selected = true;
  2499. sel.appendChild(opt);
  2500. });
  2501. }
  2502. function populateAddressListSelect(selectId, currentVal = '') {
  2503. const sel = document.getElementById(selectId);
  2504. if (!sel) return;
  2505. sel.innerHTML = '<option value="">(None)</option>';
  2506. const cleanVal = (currentVal || '').replace(/^!/, '');
  2507. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  2508. customNames.forEach(name => {
  2509. const count = (state.addressLists || []).filter(a => a.name === name).length;
  2510. const opt = document.createElement('option');
  2511. opt.value = name;
  2512. opt.innerText = `${name} (${count} entries)`;
  2513. if (name === cleanVal) opt.selected = true;
  2514. sel.appendChild(opt);
  2515. });
  2516. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  2517. const opt = document.createElement('option');
  2518. opt.value = cleanVal;
  2519. opt.innerText = cleanVal;
  2520. opt.selected = true;
  2521. sel.appendChild(opt);
  2522. }
  2523. }
  2524. function populateGeoIPSelect(selectId, currentVal = '') {
  2525. const sel = document.getElementById(selectId);
  2526. if (!sel) return;
  2527. sel.innerHTML = '<option value="">(None)</option>';
  2528. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  2529. // Presets optgroup
  2530. const grpPresets = document.createElement('optgroup');
  2531. grpPresets.label = '⚡ Regional Presets';
  2532. const presets = [
  2533. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  2534. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  2535. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  2536. ];
  2537. presets.forEach(p => {
  2538. const opt = document.createElement('option');
  2539. opt.value = p.code;
  2540. opt.innerText = p.label;
  2541. if (p.code === cleanVal) opt.selected = true;
  2542. grpPresets.appendChild(opt);
  2543. });
  2544. sel.appendChild(grpPresets);
  2545. // All Countries optgroup
  2546. const grpCountries = document.createElement('optgroup');
  2547. grpCountries.label = '🌍 All Countries';
  2548. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  2549. countries.forEach(c => {
  2550. const opt = document.createElement('option');
  2551. opt.value = c.code;
  2552. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  2553. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  2554. if (c.code === cleanVal) opt.selected = true;
  2555. grpCountries.appendChild(opt);
  2556. });
  2557. sel.appendChild(grpCountries);
  2558. }
  2559. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  2560. function switchFwRuleTab(tab) {
  2561. state.activeFwRuleTab = tab;
  2562. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  2563. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  2564. btn.classList.add('text-slate-400', 'border-transparent');
  2565. });
  2566. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  2567. if (activeBtn) {
  2568. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  2569. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  2570. }
  2571. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  2572. const activePane = document.getElementById(`fw-pane-${tab}`);
  2573. if (activePane) activePane.classList.remove('hidden');
  2574. if (tab === 'statistics') {
  2575. startFwStatPolling();
  2576. } else {
  2577. stopFwStatPolling();
  2578. }
  2579. }
  2580. function toggleFwField(fieldKey, expand) {
  2581. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  2582. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  2583. if (!plusBtn || !fieldBox) return;
  2584. if (expand) {
  2585. plusBtn.classList.add('hidden');
  2586. fieldBox.classList.remove('hidden');
  2587. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2588. if (valInput) valInput.focus();
  2589. } else {
  2590. fieldBox.classList.add('hidden');
  2591. plusBtn.classList.remove('hidden');
  2592. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2593. if (valInput) {
  2594. if (valInput.tagName === 'SELECT') {
  2595. valInput.selectedIndex = 0;
  2596. } else {
  2597. valInput.value = '';
  2598. }
  2599. }
  2600. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  2601. if (invInput) invInput.checked = false;
  2602. if (fieldKey === 'cs') {
  2603. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  2604. const el = document.getElementById(id);
  2605. if (el) el.checked = false;
  2606. });
  2607. }
  2608. if (fieldKey === 'natstate') {
  2609. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  2610. const el = document.getElementById(id);
  2611. if (el) el.checked = false;
  2612. });
  2613. }
  2614. if (fieldKey === 'days') {
  2615. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  2616. const el = document.getElementById(`fw-day-${d}`);
  2617. if (el) el.checked = true;
  2618. });
  2619. }
  2620. }
  2621. }
  2622. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  2623. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  2624. toggleFwField(fieldKey, true);
  2625. let strVal = String(value);
  2626. if (hasInvert) {
  2627. const inv = strVal.startsWith('!');
  2628. if (inv) strVal = strVal.slice(1);
  2629. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  2630. if (invEl) invEl.checked = inv;
  2631. }
  2632. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  2633. if (valEl) valEl.value = strVal;
  2634. } else {
  2635. toggleFwField(fieldKey, false);
  2636. }
  2637. }
  2638. function getFwFieldVal(fieldKey, hasInvert = false) {
  2639. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  2640. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  2641. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  2642. let v = valEl ? valEl.value.trim() : '';
  2643. if (!v) return '';
  2644. if (hasInvert) {
  2645. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  2646. if (invEl && invEl.checked) {
  2647. v = '!' + v.replace(/^!/, '');
  2648. }
  2649. }
  2650. return v;
  2651. }
  2652. function toggleMaximizeFilterModal() {
  2653. const win = document.getElementById('filter-modal-window');
  2654. if (!win) return;
  2655. if (win.classList.contains('max-w-[720px]')) {
  2656. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  2657. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  2658. } else {
  2659. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  2660. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  2661. }
  2662. }
  2663. function openAddFilterModal() {
  2664. switchFwRuleTab('general');
  2665. const badge = document.getElementById('fw-modal-badge');
  2666. if (badge) badge.innerText = 'New...';
  2667. document.getElementById('filter-modal-id').value = '';
  2668. document.getElementById('filter-modal-enabled').checked = true;
  2669. document.getElementById('filter-modal-comment').value = '';
  2670. document.getElementById('filter-modal-chain').value = 'forward';
  2671. document.getElementById('filter-modal-action').value = 'accept';
  2672. document.getElementById('filter-modal-log').checked = false;
  2673. populateInterfaceSelect('fw-val-iniface');
  2674. populateInterfaceSelect('fw-val-outiface');
  2675. populateAddressListSelect('fw-val-srclist');
  2676. populateAddressListSelect('fw-val-dstlist');
  2677. const allFieldKeys = [
  2678. 'src', 'dst', 'srclist', 'dstlist', 'proto', 'sport', 'dport', 'anyport',
  2679. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  2680. 'routingmark', 'conntype', 'cs', 'natstate',
  2681. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  2682. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  2683. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  2684. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  2685. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  2686. ];
  2687. allFieldKeys.forEach(k => toggleFwField(k, false));
  2688. resetCurrentRuleCounters();
  2689. toggleFilterActionFields();
  2690. document.getElementById('filter-modal').classList.remove('hidden');
  2691. }
  2692. function openEditFilterModal(id) {
  2693. const r = (state.filterRules || []).find(rule => rule.id === id);
  2694. if (!r) return;
  2695. switchFwRuleTab('general');
  2696. const badge = document.getElementById('fw-modal-badge');
  2697. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  2698. document.getElementById('filter-modal-id').value = r.id;
  2699. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  2700. document.getElementById('filter-modal-comment').value = r.comment || '';
  2701. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  2702. document.getElementById('filter-modal-action').value = r.action || 'accept';
  2703. document.getElementById('filter-modal-log').checked = !!r.log;
  2704. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  2705. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  2706. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  2707. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  2708. setFwFieldVal('src', r.src_address, true);
  2709. setFwFieldVal('dst', r.dst_address, true);
  2710. setFwFieldVal('srclist', r.src_address_list, true);
  2711. setFwFieldVal('dstlist', r.dst_address_list, true);
  2712. if (r.protocol && r.protocol !== 'all') {
  2713. setFwFieldVal('proto', r.protocol, true);
  2714. } else {
  2715. toggleFwField('proto', false);
  2716. }
  2717. setFwFieldVal('sport', r.src_port, true);
  2718. setFwFieldVal('dport', r.dst_port, true);
  2719. setFwFieldVal('anyport', r.any_port, true);
  2720. setFwFieldVal('iniface', r.in_interface, true);
  2721. setFwFieldVal('outiface', r.out_interface, true);
  2722. setFwFieldVal('inifacelist', r.in_interface_list, true);
  2723. setFwFieldVal('outifacelist', r.out_interface_list, true);
  2724. setFwFieldVal('pktmark', r.packet_mark, true);
  2725. setFwFieldVal('connmark', r.connection_mark, true);
  2726. setFwFieldVal('routingmark', r.routing_mark, true);
  2727. setFwFieldVal('conntype', r.connection_type, false);
  2728. const states = r.connection_state || [];
  2729. if (states.length > 0) {
  2730. toggleFwField('cs', true);
  2731. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  2732. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  2733. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  2734. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  2735. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  2736. } else {
  2737. toggleFwField('cs', false);
  2738. }
  2739. const natStates = r.connection_nat_state || [];
  2740. if (natStates.length > 0) {
  2741. toggleFwField('natstate', true);
  2742. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  2743. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  2744. } else {
  2745. toggleFwField('natstate', false);
  2746. }
  2747. // Advanced tab fields
  2748. setFwFieldVal('layer7', r.layer7_protocol, false);
  2749. setFwFieldVal('content', r.content, false);
  2750. setFwFieldVal('connbytes', r.connection_bytes, false);
  2751. setFwFieldVal('connrate', r.connection_rate, false);
  2752. setFwFieldVal('pcc', r.pcc, false);
  2753. setFwFieldVal('srcmac', r.src_mac_address, true);
  2754. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  2755. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  2756. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  2757. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  2758. setFwFieldVal('ipsec', r.ipsec_policy, false);
  2759. setFwFieldVal('tlshost', r.tls_host, false);
  2760. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  2761. setFwFieldVal('priority', r.priority, false);
  2762. setFwFieldVal('dscp', r.dscp, false);
  2763. setFwFieldVal('tcpmss', r.tcp_mss, false);
  2764. if (r.tos) {
  2765. const tosEl = document.getElementById('fw-val-tos');
  2766. if (tosEl) tosEl.value = r.tos;
  2767. }
  2768. setFwFieldVal('pktsize', r.packet_size, false);
  2769. setFwFieldVal('random', r.random, false);
  2770. setFwFieldVal('tcpflags', r.tcp_flags, false);
  2771. setFwFieldVal('icmpoptions', r.icmp_options, false);
  2772. setFwFieldVal('ipv4options', r.ipv4_options, false);
  2773. setFwFieldVal('ttl', r.ttl, false);
  2774. // Extra tab fields
  2775. setFwFieldVal('time', r.time, false);
  2776. if (r.days) {
  2777. toggleFwField('days', true);
  2778. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  2779. const chk = document.getElementById(`fw-day-${d}`);
  2780. if (chk) chk.checked = r.days.includes(d);
  2781. });
  2782. } else {
  2783. toggleFwField('days', false);
  2784. }
  2785. setFwFieldVal('limit', r.limit, false);
  2786. setFwFieldVal('dstlimit', r.dst_limit, false);
  2787. setFwFieldVal('psd', r.psd, false);
  2788. // Action fields
  2789. if (r.reject_with) {
  2790. const rwEl = document.getElementById('filter-modal-rejectwith');
  2791. if (rwEl) rwEl.value = r.reject_with;
  2792. }
  2793. if (r.jump_target) {
  2794. const jtEl = document.getElementById('filter-modal-jumptarget');
  2795. if (jtEl) jtEl.value = r.jump_target;
  2796. }
  2797. if (r.address_list) {
  2798. const alEl = document.getElementById('filter-modal-action-addrlist');
  2799. if (alEl) alEl.value = r.address_list;
  2800. }
  2801. if (r.address_list_timeout) {
  2802. const toEl = document.getElementById('filter-modal-action-timeout');
  2803. if (toEl) toEl.value = r.address_list_timeout;
  2804. }
  2805. setFwFieldVal('logprefix', r.log_prefix, false);
  2806. // Statistics
  2807. const bEl = document.getElementById('fw-stat-bytes');
  2808. const pEl = document.getElementById('fw-stat-packets');
  2809. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  2810. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  2811. state.fwLastBytes = r.bytes || 0;
  2812. state.fwLastPackets = r.packets || 0;
  2813. state.fwLastTimestamp = Date.now();
  2814. state.fwStatRateHistory = new Array(30).fill(0);
  2815. state.fwStatPktHistory = new Array(30).fill(0);
  2816. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  2817. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  2818. toggleFilterActionFields();
  2819. document.getElementById('filter-modal').classList.remove('hidden');
  2820. }
  2821. function closeFilterModal() {
  2822. stopFwStatPolling();
  2823. document.getElementById('filter-modal').classList.add('hidden');
  2824. }
  2825. function toggleFilterActionFields() {
  2826. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  2827. const rejectBox = document.getElementById('filter-action-reject-box');
  2828. const jumpBox = document.getElementById('filter-action-jump-box');
  2829. const addrBox = document.getElementById('filter-action-addrlist-box');
  2830. if (rejectBox) {
  2831. if (act === 'reject') rejectBox.classList.remove('hidden');
  2832. else rejectBox.classList.add('hidden');
  2833. }
  2834. if (jumpBox) {
  2835. if (act === 'jump') jumpBox.classList.remove('hidden');
  2836. else jumpBox.classList.add('hidden');
  2837. }
  2838. if (addrBox) {
  2839. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list') addrBox.classList.remove('hidden');
  2840. else addrBox.classList.add('hidden');
  2841. }
  2842. }
  2843. function copyFilterRule() {
  2844. document.getElementById('filter-modal-id').value = '';
  2845. const badge = document.getElementById('fw-modal-badge');
  2846. if (badge) badge.innerText = 'New...';
  2847. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  2848. }
  2849. function resetCurrentRuleCounters() {
  2850. state.fwStatRateHistory = new Array(30).fill(0);
  2851. state.fwStatPktHistory = new Array(30).fill(0);
  2852. state.fwLastBytes = 0;
  2853. state.fwLastPackets = 0;
  2854. state.fwLastTimestamp = Date.now();
  2855. const bEl = document.getElementById('fw-stat-bytes');
  2856. const pEl = document.getElementById('fw-stat-packets');
  2857. const rEl = document.getElementById('fw-stat-rate');
  2858. const prEl = document.getElementById('fw-stat-pktrate');
  2859. if (bEl) bEl.value = '0 B';
  2860. if (pEl) pEl.value = '0';
  2861. if (rEl) rEl.value = '0 bps';
  2862. if (prEl) prEl.value = '0 p/s';
  2863. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  2864. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  2865. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  2866. }
  2867. async function resetAllFwCounters() {
  2868. try {
  2869. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  2870. if (res.ok) {
  2871. resetCurrentRuleCounters();
  2872. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  2873. loadFirewall(false);
  2874. }
  2875. } catch (err) {
  2876. showToast('Error', err.message, 'error');
  2877. }
  2878. }
  2879. async function applyFilterRule(closeAfter = false) {
  2880. const id = document.getElementById('filter-modal-id').value;
  2881. const chain = document.getElementById('filter-modal-chain').value;
  2882. const action = document.getElementById('filter-modal-action').value;
  2883. const comment = document.getElementById('filter-modal-comment').value.trim();
  2884. const enabled = document.getElementById('filter-modal-enabled').checked;
  2885. const src = getFwFieldVal('src', true);
  2886. const dst = getFwFieldVal('dst', true);
  2887. const srclist = getFwFieldVal('srclist', true);
  2888. const dstlist = getFwFieldVal('dstlist', true);
  2889. const proto = getFwFieldVal('proto', true);
  2890. const sport = getFwFieldVal('sport', true);
  2891. const dport = getFwFieldVal('dport', true);
  2892. const anyport = getFwFieldVal('anyport', true);
  2893. const iniface = getFwFieldVal('iniface', true);
  2894. const outiface = getFwFieldVal('outiface', true);
  2895. const inifacelist = getFwFieldVal('inifacelist', true);
  2896. const outifacelist = getFwFieldVal('outifacelist', true);
  2897. const pktmark = getFwFieldVal('pktmark', true);
  2898. const connmark = getFwFieldVal('connmark', true);
  2899. const routingmark = getFwFieldVal('routingmark', true);
  2900. const conntype = getFwFieldVal('conntype', false);
  2901. const states = [];
  2902. const csBox = document.getElementById('fw-field-cs');
  2903. if (csBox && !csBox.classList.contains('hidden')) {
  2904. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  2905. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  2906. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  2907. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  2908. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  2909. }
  2910. const natStates = [];
  2911. const natBox = document.getElementById('fw-field-natstate');
  2912. if (natBox && !natBox.classList.contains('hidden')) {
  2913. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  2914. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  2915. }
  2916. const payload = {
  2917. id,
  2918. chain,
  2919. action,
  2920. protocol: proto || 'all',
  2921. src_address: src,
  2922. dst_address: dst,
  2923. src_port: sport,
  2924. dst_port: dport,
  2925. any_port: anyport,
  2926. in_interface: iniface,
  2927. out_interface: outiface,
  2928. in_interface_list: inifacelist,
  2929. out_interface_list: outifacelist,
  2930. packet_mark: pktmark,
  2931. connection_mark: connmark,
  2932. routing_mark: routingmark,
  2933. connection_type: conntype,
  2934. connection_state: states,
  2935. connection_nat_state: natStates,
  2936. src_address_list: srclist,
  2937. dst_address_list: dstlist,
  2938. comment,
  2939. disabled: !enabled,
  2940. // Advanced tab
  2941. layer7_protocol: getFwFieldVal('layer7', false),
  2942. content: getFwFieldVal('content', false),
  2943. connection_bytes: getFwFieldVal('connbytes', false),
  2944. connection_rate: getFwFieldVal('connrate', false),
  2945. pcc: getFwFieldVal('pcc', false),
  2946. src_mac_address: getFwFieldVal('srcmac', true),
  2947. out_bridge_port: getFwFieldVal('outbridgeport', false),
  2948. in_bridge_port: getFwFieldVal('inbridgeport', false),
  2949. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  2950. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  2951. ipsec_policy: getFwFieldVal('ipsec', false),
  2952. tls_host: getFwFieldVal('tlshost', false),
  2953. ingress_priority: getFwFieldVal('ingresspriority', false),
  2954. priority: getFwFieldVal('priority', false),
  2955. dscp: getFwFieldVal('dscp', false),
  2956. tcp_mss: getFwFieldVal('tcpmss', false),
  2957. tos: document.getElementById('fw-val-tos')?.value || '',
  2958. packet_size: getFwFieldVal('pktsize', false),
  2959. random: getFwFieldVal('random', false),
  2960. tcp_flags: getFwFieldVal('tcpflags', false),
  2961. icmp_options: getFwFieldVal('icmpoptions', false),
  2962. ipv4_options: getFwFieldVal('ipv4options', false),
  2963. ttl: getFwFieldVal('ttl', false),
  2964. // Extra tab
  2965. time: getFwFieldVal('time', false),
  2966. limit: getFwFieldVal('limit', false),
  2967. dst_limit: getFwFieldVal('dstlimit', false),
  2968. psd: getFwFieldVal('psd', false),
  2969. // Action tab
  2970. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  2971. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  2972. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  2973. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  2974. log: document.getElementById('filter-modal-log')?.checked || false,
  2975. log_prefix: getFwFieldVal('logprefix', false)
  2976. };
  2977. try {
  2978. const res = await fetch(`${API_BASE}/firewall/filter`, {
  2979. method: 'POST',
  2980. headers: { 'Content-Type': 'application/json' },
  2981. body: JSON.stringify(payload)
  2982. });
  2983. if (res.ok) {
  2984. const data = await res.json();
  2985. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  2986. loadFirewall(false);
  2987. if (closeAfter) {
  2988. closeFilterModal();
  2989. } else {
  2990. if (data.id) {
  2991. document.getElementById('filter-modal-id').value = data.id;
  2992. const badge = document.getElementById('fw-modal-badge');
  2993. if (badge) badge.innerText = `#${data.id}`;
  2994. }
  2995. }
  2996. } else {
  2997. const err = await res.json();
  2998. showToast('Error', err.message || 'Failed to save rule', 'error');
  2999. }
  3000. } catch (err) {
  3001. showToast('Error', err.message, 'error');
  3002. }
  3003. }
  3004. function submitSaveFilterRule(e) {
  3005. if (e && e.preventDefault) e.preventDefault();
  3006. return applyFilterRule(true);
  3007. }
  3008. function startFwStatPolling() {
  3009. stopFwStatPolling();
  3010. pollRuleStats();
  3011. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  3012. }
  3013. function stopFwStatPolling() {
  3014. if (state.fwStatInterval) {
  3015. clearInterval(state.fwStatInterval);
  3016. state.fwStatInterval = null;
  3017. }
  3018. }
  3019. async function pollRuleStats() {
  3020. const id = document.getElementById('filter-modal-id')?.value;
  3021. if (!id) {
  3022. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  3023. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  3024. return;
  3025. }
  3026. try {
  3027. const res = await fetch(`${API_BASE}/firewall/filter`);
  3028. if (!res.ok) return;
  3029. const rules = await res.json();
  3030. const r = rules.find(x => x.id === id);
  3031. if (!r) return;
  3032. const now = Date.now();
  3033. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  3034. state.fwLastTimestamp = now;
  3035. const curBytes = r.bytes || 0;
  3036. const curPackets = r.packets || 0;
  3037. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  3038. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  3039. state.fwLastBytes = curBytes;
  3040. state.fwLastPackets = curPackets;
  3041. const rateBps = Math.round((deltaBytes * 8) / dt);
  3042. const ratePkt = Math.round(deltaPkts / dt);
  3043. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  3044. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  3045. state.fwStatRateHistory.push(rateBps);
  3046. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  3047. state.fwStatPktHistory.push(ratePkt);
  3048. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  3049. const bEl = document.getElementById('fw-stat-bytes');
  3050. const pEl = document.getElementById('fw-stat-packets');
  3051. const rEl = document.getElementById('fw-stat-rate');
  3052. const prEl = document.getElementById('fw-stat-pktrate');
  3053. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  3054. if (pEl) pEl.value = curPackets.toLocaleString();
  3055. if (rEl) rEl.value = formatBps(rateBps);
  3056. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  3057. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3058. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3059. } catch (e) {
  3060. console.error('Error polling rule stats', e);
  3061. }
  3062. }
  3063. function formatBps(bps) {
  3064. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  3065. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  3066. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  3067. return bps + ' bps';
  3068. }
  3069. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  3070. const svg = document.getElementById(svgId);
  3071. if (!svg) return;
  3072. const w = 500;
  3073. const h = 100;
  3074. const paddingRight = 45;
  3075. const graphWidth = w - paddingRight;
  3076. const maxVal = Math.max(5, ...dataArray);
  3077. const currentVal = dataArray[dataArray.length - 1] || 0;
  3078. const leg = document.getElementById(legendId);
  3079. if (leg) {
  3080. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  3081. }
  3082. let gridLines = '';
  3083. for (let i = 0; i <= 5; i++) {
  3084. const y = 8 + (i * (h - 18) / 5);
  3085. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  3086. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  3087. gridLines += `
  3088. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  3089. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  3090. `;
  3091. }
  3092. const step = graphWidth / (dataArray.length - 1);
  3093. const points = dataArray.map((val, idx) => {
  3094. const x = idx * step;
  3095. const y = (h - 10) - (val / maxVal) * (h - 20);
  3096. return `${x.toFixed(1)},${y.toFixed(1)}`;
  3097. });
  3098. const polylineStr = points.join(' ');
  3099. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  3100. svg.innerHTML = `
  3101. ${gridLines}
  3102. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  3103. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  3104. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  3105. `;
  3106. }
  3107. async function moveFilterRule(id, dir) {
  3108. try {
  3109. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  3110. method: 'POST',
  3111. headers: { 'Content-Type': 'application/json' },
  3112. body: JSON.stringify({ direction: dir })
  3113. });
  3114. if (res.ok) loadFirewall(false);
  3115. } catch (err) {
  3116. showToast('Error', err.message, 'error');
  3117. }
  3118. }
  3119. async function toggleFilterRuleState(id, disabled) {
  3120. try {
  3121. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  3122. method: 'POST',
  3123. headers: { 'Content-Type': 'application/json' },
  3124. body: JSON.stringify({ disabled })
  3125. });
  3126. if (res.ok) loadFirewall(false);
  3127. } catch (err) {
  3128. showToast('Error', err.message, 'error');
  3129. }
  3130. }
  3131. async function deleteFilterRule(id) {
  3132. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  3133. try {
  3134. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3135. if (res.ok) {
  3136. showToast('Deleted', 'Filter rule removed', 'success');
  3137. loadFirewall(false);
  3138. }
  3139. } catch (err) {
  3140. showToast('Error', err.message, 'error');
  3141. }
  3142. }
  3143. // ----------------- NAT Rules -----------------
  3144. function renderNATRules() {
  3145. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  3146. const tbody = document.getElementById('nat-table-body');
  3147. const empty = document.getElementById('nat-empty');
  3148. if (!tbody) return;
  3149. tbody.innerHTML = '';
  3150. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3151. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  3152. if (rules.length === 0) {
  3153. empty?.classList.remove('hidden');
  3154. return;
  3155. }
  3156. empty?.classList.add('hidden');
  3157. rules.forEach((r, idx) => {
  3158. const tr = document.createElement('tr');
  3159. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3160. const toTarget = [r.to_addresses, r.to_ports].filter(Boolean).join(':');
  3161. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  3162. tr.innerHTML = `
  3163. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3164. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3165. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  3166. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3167. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3168. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  3169. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3170. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  3171. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${toTarget || '-'}</td>
  3172. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3173. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3174. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3175. </td>
  3176. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3177. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3178. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3179. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3180. <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>
  3181. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3182. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3183. </td>
  3184. `;
  3185. tbody.appendChild(tr);
  3186. });
  3187. }
  3188. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3189. function switchNATRuleTab(tab) {
  3190. state.activeNATRuleTab = tab;
  3191. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  3192. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3193. btn.classList.add('text-slate-400', 'border-transparent');
  3194. });
  3195. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  3196. if (activeBtn) {
  3197. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3198. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3199. }
  3200. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  3201. const activePane = document.getElementById(`nat-pane-${tab}`);
  3202. if (activePane) activePane.classList.remove('hidden');
  3203. if (tab === 'statistics') {
  3204. startNATStatPolling();
  3205. } else {
  3206. stopNATStatPolling();
  3207. }
  3208. }
  3209. function toggleNATField(fieldKey, expand) {
  3210. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  3211. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3212. if (!plusBtn || !fieldBox) return;
  3213. if (expand) {
  3214. plusBtn.classList.add('hidden');
  3215. fieldBox.classList.remove('hidden');
  3216. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3217. if (valInput) valInput.focus();
  3218. } else {
  3219. fieldBox.classList.add('hidden');
  3220. plusBtn.classList.remove('hidden');
  3221. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3222. if (valInput) {
  3223. if (valInput.tagName === 'SELECT') {
  3224. valInput.selectedIndex = 0;
  3225. } else {
  3226. valInput.value = '';
  3227. }
  3228. }
  3229. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  3230. if (invInput) invInput.checked = false;
  3231. if (fieldKey === 'days') {
  3232. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3233. const el = document.getElementById(`nat-day-${d}`);
  3234. if (el) el.checked = true;
  3235. });
  3236. }
  3237. }
  3238. }
  3239. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  3240. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3241. toggleNATField(fieldKey, true);
  3242. let strVal = String(value);
  3243. if (hasInvert) {
  3244. const inv = strVal.startsWith('!');
  3245. if (inv) strVal = strVal.slice(1);
  3246. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3247. if (invEl) invEl.checked = inv;
  3248. }
  3249. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3250. if (valEl) valEl.value = strVal;
  3251. } else {
  3252. toggleNATField(fieldKey, false);
  3253. }
  3254. }
  3255. function getNATFieldVal(fieldKey, hasInvert = false) {
  3256. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3257. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3258. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3259. let v = valEl ? valEl.value.trim() : '';
  3260. if (!v) return '';
  3261. if (hasInvert) {
  3262. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3263. if (invEl && invEl.checked) {
  3264. v = '!' + v.replace(/^!/, '');
  3265. }
  3266. }
  3267. return v;
  3268. }
  3269. function toggleMaximizeNATModal() {
  3270. const win = document.getElementById('nat-modal-window');
  3271. if (!win) return;
  3272. if (win.classList.contains('max-w-[720px]')) {
  3273. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3274. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3275. } else {
  3276. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3277. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3278. }
  3279. }
  3280. function handleNATChainChange() {
  3281. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  3282. const actSel = document.getElementById('nat-modal-action');
  3283. if (actSel) {
  3284. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  3285. actSel.value = 'masquerade';
  3286. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  3287. actSel.value = 'dst-nat';
  3288. }
  3289. }
  3290. toggleNATActionFields();
  3291. }
  3292. function toggleNATActionFields() {
  3293. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  3294. const toBox = document.getElementById('nat-action-to-box');
  3295. const jumpBox = document.getElementById('nat-action-jump-box');
  3296. const addrBox = document.getElementById('nat-action-addrlist-box');
  3297. if (toBox) {
  3298. const needsTo = ['src-nat', 'dst-nat', 'redirect', 'netmap', 'same', 'endpoint-independent-nat'].includes(act);
  3299. if (needsTo) toBox.classList.remove('hidden');
  3300. else toBox.classList.add('hidden');
  3301. }
  3302. if (jumpBox) {
  3303. if (act === 'jump') jumpBox.classList.remove('hidden');
  3304. else jumpBox.classList.add('hidden');
  3305. }
  3306. if (addrBox) {
  3307. if (act.includes('address-list') || act.includes('address list')) addrBox.classList.remove('hidden');
  3308. else addrBox.classList.add('hidden');
  3309. }
  3310. }
  3311. function openAddNATModal() {
  3312. switchNATRuleTab('general');
  3313. const badge = document.getElementById('nat-modal-badge');
  3314. if (badge) badge.innerText = 'New...';
  3315. document.getElementById('nat-modal-id').value = '';
  3316. document.getElementById('nat-modal-enabled').checked = true;
  3317. document.getElementById('nat-modal-comment').value = '';
  3318. document.getElementById('nat-modal-chain').value = 'srcnat';
  3319. document.getElementById('nat-modal-action').value = 'masquerade';
  3320. document.getElementById('nat-modal-toaddr').value = '';
  3321. document.getElementById('nat-modal-toport').value = '';
  3322. document.getElementById('nat-modal-log').checked = false;
  3323. populateInterfaceSelect('nat-val-iniface');
  3324. populateInterfaceSelect('nat-val-outiface');
  3325. populateAddressListSelect('nat-val-srclist');
  3326. populateAddressListSelect('nat-val-dstlist');
  3327. const allFieldKeys = [
  3328. 'src', 'dst', 'srclist', 'dstlist', 'proto', 'sport', 'dport', 'anyport',
  3329. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3330. 'routingmark', 'conntype',
  3331. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3332. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3333. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3334. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  3335. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3336. ];
  3337. allFieldKeys.forEach(k => toggleNATField(k, false));
  3338. resetCurrentNATRuleCounters();
  3339. toggleNATActionFields();
  3340. document.getElementById('nat-modal').classList.remove('hidden');
  3341. }
  3342. function openEditNATModal(id) {
  3343. const r = (state.natRules || []).find(rule => rule.id === id);
  3344. if (!r) return;
  3345. switchNATRuleTab('general');
  3346. const badge = document.getElementById('nat-modal-badge');
  3347. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3348. document.getElementById('nat-modal-id').value = r.id;
  3349. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  3350. document.getElementById('nat-modal-comment').value = r.comment || '';
  3351. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  3352. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  3353. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  3354. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  3355. document.getElementById('nat-modal-log').checked = !!r.log;
  3356. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3357. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3358. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3359. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3360. setNATFieldVal('src', r.src_address, true);
  3361. setNATFieldVal('dst', r.dst_address, true);
  3362. setNATFieldVal('srclist', r.src_address_list, true);
  3363. setNATFieldVal('dstlist', r.dst_address_list, true);
  3364. if (r.protocol && r.protocol !== 'all') {
  3365. setNATFieldVal('proto', r.protocol, true);
  3366. } else {
  3367. toggleNATField('proto', false);
  3368. }
  3369. setNATFieldVal('sport', r.src_port, true);
  3370. setNATFieldVal('dport', r.dst_port, true);
  3371. setNATFieldVal('anyport', r.any_port, true);
  3372. setNATFieldVal('iniface', r.in_interface, true);
  3373. setNATFieldVal('outiface', r.out_interface, true);
  3374. setNATFieldVal('inifacelist', r.in_interface_list, true);
  3375. setNATFieldVal('outifacelist', r.out_interface_list, true);
  3376. setNATFieldVal('pktmark', r.packet_mark, true);
  3377. setNATFieldVal('connmark', r.connection_mark, true);
  3378. setNATFieldVal('routingmark', r.routing_mark, true);
  3379. setNATFieldVal('conntype', r.connection_type, false);
  3380. // Advanced tab fields
  3381. setNATFieldVal('layer7', r.layer7_protocol, false);
  3382. setNATFieldVal('content', r.content, false);
  3383. setNATFieldVal('connbytes', r.connection_bytes, false);
  3384. setNATFieldVal('connrate', r.connection_rate, false);
  3385. setNATFieldVal('pcc', r.pcc, false);
  3386. setNATFieldVal('srcmac', r.src_mac_address, true);
  3387. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  3388. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  3389. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3390. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3391. setNATFieldVal('ipsec', r.ipsec_policy, false);
  3392. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  3393. setNATFieldVal('priority', r.priority, false);
  3394. setNATFieldVal('dscp', r.dscp, false);
  3395. setNATFieldVal('tcpmss', r.tcp_mss, false);
  3396. if (r.tos) {
  3397. const tosEl = document.getElementById('nat-val-tos');
  3398. if (tosEl) tosEl.value = r.tos;
  3399. }
  3400. setNATFieldVal('pktsize', r.packet_size, false);
  3401. setNATFieldVal('random', r.random, false);
  3402. setNATFieldVal('icmpoptions', r.icmp_options, false);
  3403. setNATFieldVal('ipv4options', r.ipv4_options, false);
  3404. setNATFieldVal('ttl', r.ttl, false);
  3405. // Extra tab fields
  3406. setNATFieldVal('time', r.time, false);
  3407. if (r.days) {
  3408. toggleNATField('days', true);
  3409. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3410. const chk = document.getElementById(`nat-day-${d}`);
  3411. if (chk) chk.checked = r.days.includes(d);
  3412. });
  3413. } else {
  3414. toggleNATField('days', false);
  3415. }
  3416. setNATFieldVal('limit', r.limit, false);
  3417. setNATFieldVal('dstlimit', r.dst_limit, false);
  3418. setNATFieldVal('psd', r.psd, false);
  3419. // Action fields
  3420. if (r.jump_target) {
  3421. const jtEl = document.getElementById('nat-modal-jumptarget');
  3422. if (jtEl) jtEl.value = r.jump_target;
  3423. }
  3424. if (r.address_list) {
  3425. const alEl = document.getElementById('nat-modal-action-addrlist');
  3426. if (alEl) alEl.value = r.address_list;
  3427. }
  3428. if (r.address_list_timeout) {
  3429. const toEl = document.getElementById('nat-modal-action-timeout');
  3430. if (toEl) toEl.value = r.address_list_timeout;
  3431. }
  3432. setNATFieldVal('logprefix', r.log_prefix, false);
  3433. // Statistics
  3434. const bEl = document.getElementById('nat-stat-bytes');
  3435. const pEl = document.getElementById('nat-stat-packets');
  3436. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3437. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3438. state.natLastBytes = r.bytes || 0;
  3439. state.natLastPackets = r.packets || 0;
  3440. state.natLastTimestamp = Date.now();
  3441. state.natStatRateHistory = new Array(30).fill(0);
  3442. state.natStatPktHistory = new Array(30).fill(0);
  3443. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3444. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3445. toggleNATActionFields();
  3446. document.getElementById('nat-modal').classList.remove('hidden');
  3447. }
  3448. function closeNATModal() {
  3449. stopNATStatPolling();
  3450. document.getElementById('nat-modal').classList.add('hidden');
  3451. }
  3452. function copyNATRule() {
  3453. document.getElementById('nat-modal-id').value = '';
  3454. const badge = document.getElementById('nat-modal-badge');
  3455. if (badge) badge.innerText = 'New...';
  3456. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  3457. }
  3458. function resetCurrentNATRuleCounters() {
  3459. state.natStatRateHistory = new Array(30).fill(0);
  3460. state.natStatPktHistory = new Array(30).fill(0);
  3461. state.natLastBytes = 0;
  3462. state.natLastPackets = 0;
  3463. state.natLastTimestamp = Date.now();
  3464. const bEl = document.getElementById('nat-stat-bytes');
  3465. const pEl = document.getElementById('nat-stat-packets');
  3466. const rEl = document.getElementById('nat-stat-rate');
  3467. const prEl = document.getElementById('nat-stat-pktrate');
  3468. if (bEl) bEl.value = '0 B';
  3469. if (pEl) pEl.value = '0';
  3470. if (rEl) rEl.value = '0 bps';
  3471. if (prEl) prEl.value = '0 p/s';
  3472. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3473. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3474. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  3475. }
  3476. async function applyNATRule(closeAfter = false) {
  3477. const id = document.getElementById('nat-modal-id').value;
  3478. const chain = document.getElementById('nat-modal-chain').value;
  3479. const action = document.getElementById('nat-modal-action').value;
  3480. const comment = document.getElementById('nat-modal-comment').value.trim();
  3481. const enabled = document.getElementById('nat-modal-enabled').checked;
  3482. const src = getNATFieldVal('src', true);
  3483. const dst = getNATFieldVal('dst', true);
  3484. const srclist = getNATFieldVal('srclist', true);
  3485. const dstlist = getNATFieldVal('dstlist', true);
  3486. const proto = getNATFieldVal('proto', true);
  3487. const sport = getNATFieldVal('sport', true);
  3488. const dport = getNATFieldVal('dport', true);
  3489. const anyport = getNATFieldVal('anyport', true);
  3490. const iniface = getNATFieldVal('iniface', true);
  3491. const outiface = getNATFieldVal('outiface', true);
  3492. const inifacelist = getNATFieldVal('inifacelist', true);
  3493. const outifacelist = getNATFieldVal('outifacelist', true);
  3494. const pktmark = getNATFieldVal('pktmark', true);
  3495. const connmark = getNATFieldVal('connmark', true);
  3496. const routingmark = getNATFieldVal('routingmark', true);
  3497. const conntype = getNATFieldVal('conntype', false);
  3498. const payload = {
  3499. id,
  3500. chain,
  3501. action,
  3502. to_addresses: document.getElementById('nat-modal-toaddr')?.value.trim() || '',
  3503. to_ports: document.getElementById('nat-modal-toport')?.value.trim() || '',
  3504. protocol: proto || 'all',
  3505. src_address: src,
  3506. dst_address: dst,
  3507. src_port: sport,
  3508. dst_port: dport,
  3509. any_port: anyport,
  3510. in_interface: iniface,
  3511. out_interface: outiface,
  3512. in_interface_list: inifacelist,
  3513. out_interface_list: outifacelist,
  3514. packet_mark: pktmark,
  3515. connection_mark: connmark,
  3516. routing_mark: routingmark,
  3517. connection_type: conntype,
  3518. src_address_list: srclist,
  3519. dst_address_list: dstlist,
  3520. comment,
  3521. disabled: !enabled,
  3522. // Advanced tab
  3523. layer7_protocol: getNATFieldVal('layer7', false),
  3524. content: getNATFieldVal('content', false),
  3525. connection_bytes: getNATFieldVal('connbytes', false),
  3526. connection_rate: getNATFieldVal('connrate', false),
  3527. pcc: getNATFieldVal('pcc', false),
  3528. src_mac_address: getNATFieldVal('srcmac', true),
  3529. out_bridge_port: getNATFieldVal('outbridgeport', false),
  3530. in_bridge_port: getNATFieldVal('inbridgeport', false),
  3531. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  3532. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  3533. ipsec_policy: getNATFieldVal('ipsec', false),
  3534. ingress_priority: getNATFieldVal('ingresspriority', false),
  3535. priority: getNATFieldVal('priority', false),
  3536. dscp: getNATFieldVal('dscp', false),
  3537. tcp_mss: getNATFieldVal('tcpmss', false),
  3538. tos: document.getElementById('nat-val-tos')?.value || '',
  3539. packet_size: getNATFieldVal('pktsize', false),
  3540. random: getNATFieldVal('random', false),
  3541. icmp_options: getNATFieldVal('icmpoptions', false),
  3542. ipv4_options: getNATFieldVal('ipv4options', false),
  3543. ttl: getNATFieldVal('ttl', false),
  3544. // Extra tab
  3545. time: getNATFieldVal('time', false),
  3546. limit: getNATFieldVal('limit', false),
  3547. dst_limit: getNATFieldVal('dstlimit', false),
  3548. psd: getNATFieldVal('psd', false),
  3549. // Action tab
  3550. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  3551. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  3552. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  3553. log: document.getElementById('nat-modal-log')?.checked || false,
  3554. log_prefix: getNATFieldVal('logprefix', false)
  3555. };
  3556. try {
  3557. const res = await fetch(`${API_BASE}/firewall/nat`, {
  3558. method: 'POST',
  3559. headers: { 'Content-Type': 'application/json' },
  3560. body: JSON.stringify(payload)
  3561. });
  3562. if (res.ok) {
  3563. const data = await res.json();
  3564. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  3565. loadFirewall(false);
  3566. if (closeAfter) {
  3567. closeNATModal();
  3568. } else {
  3569. if (data.id) {
  3570. document.getElementById('nat-modal-id').value = data.id;
  3571. const badge = document.getElementById('nat-modal-badge');
  3572. if (badge) badge.innerText = `#${data.id}`;
  3573. }
  3574. }
  3575. } else {
  3576. const err = await res.json();
  3577. showToast('Error', err.message || 'Failed to save rule', 'error');
  3578. }
  3579. } catch (err) {
  3580. showToast('Error', err.message, 'error');
  3581. }
  3582. }
  3583. function submitSaveNATRule(e) {
  3584. if (e && e.preventDefault) e.preventDefault();
  3585. return applyNATRule(true);
  3586. }
  3587. function startNATStatPolling() {
  3588. stopNATStatPolling();
  3589. pollNATRuleStats();
  3590. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  3591. }
  3592. function stopNATStatPolling() {
  3593. if (state.natStatInterval) {
  3594. clearInterval(state.natStatInterval);
  3595. state.natStatInterval = null;
  3596. }
  3597. }
  3598. async function pollNATRuleStats() {
  3599. const id = document.getElementById('nat-modal-id')?.value;
  3600. if (!id) {
  3601. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  3602. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  3603. return;
  3604. }
  3605. try {
  3606. const res = await fetch(`${API_BASE}/firewall/nat`);
  3607. if (!res.ok) return;
  3608. const rules = await res.json();
  3609. const r = rules.find(x => x.id === id);
  3610. if (!r) return;
  3611. const now = Date.now();
  3612. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  3613. state.natLastTimestamp = now;
  3614. const curBytes = r.bytes || 0;
  3615. const curPackets = r.packets || 0;
  3616. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  3617. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  3618. state.natLastBytes = curBytes;
  3619. state.natLastPackets = curPackets;
  3620. const rateBps = Math.round((deltaBytes * 8) / dt);
  3621. const ratePkt = Math.round(deltaPkts / dt);
  3622. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  3623. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  3624. state.natStatRateHistory.push(rateBps);
  3625. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  3626. state.natStatPktHistory.push(ratePkt);
  3627. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  3628. const bEl = document.getElementById('nat-stat-bytes');
  3629. const pEl = document.getElementById('nat-stat-packets');
  3630. const rEl = document.getElementById('nat-stat-rate');
  3631. const prEl = document.getElementById('nat-stat-pktrate');
  3632. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  3633. if (pEl) pEl.value = curPackets.toLocaleString();
  3634. if (rEl) rEl.value = formatBps(rateBps);
  3635. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  3636. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3637. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3638. } catch (e) {
  3639. console.error('Error polling NAT rule stats', e);
  3640. }
  3641. }
  3642. async function moveNATRule(id, dir) {
  3643. try {
  3644. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  3645. method: 'POST',
  3646. headers: { 'Content-Type': 'application/json' },
  3647. body: JSON.stringify({ direction: dir })
  3648. });
  3649. if (res.ok) loadFirewall(false);
  3650. } catch (err) {
  3651. showToast('Error', err.message, 'error');
  3652. }
  3653. }
  3654. async function toggleNATRuleState(id, disabled) {
  3655. try {
  3656. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  3657. method: 'POST',
  3658. headers: { 'Content-Type': 'application/json' },
  3659. body: JSON.stringify({ disabled })
  3660. });
  3661. if (res.ok) loadFirewall(false);
  3662. } catch (err) {
  3663. showToast('Error', err.message, 'error');
  3664. }
  3665. }
  3666. async function deleteNATRule(id) {
  3667. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  3668. try {
  3669. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3670. if (res.ok) {
  3671. showToast('Deleted', 'NAT rule removed', 'success');
  3672. loadFirewall(false);
  3673. }
  3674. } catch (err) {
  3675. showToast('Error', err.message, 'error');
  3676. }
  3677. }
  3678. // ----------------- Mangle Rules -----------------
  3679. function renderMangleRules() {
  3680. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  3681. const tbody = document.getElementById('mangle-table-body');
  3682. const empty = document.getElementById('mangle-empty');
  3683. if (!tbody) return;
  3684. tbody.innerHTML = '';
  3685. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3686. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  3687. if (rules.length === 0) {
  3688. empty?.classList.remove('hidden');
  3689. return;
  3690. }
  3691. empty?.classList.add('hidden');
  3692. rules.forEach((r, idx) => {
  3693. const tr = document.createElement('tr');
  3694. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3695. const markVal = r.new_connection_mark || r.new_routing_mark || r.new_packet_mark || r.new_mss || (r.new_dscp ? 'DSCP:' + r.new_dscp : '');
  3696. tr.innerHTML = `
  3697. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3698. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3699. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  3700. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3701. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3702. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  3703. <td class="py-2.5 px-3 font-mono font-bold text-cyan-300">${markVal || '-'}</td>
  3704. <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>
  3705. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3706. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3707. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3708. </td>
  3709. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3710. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3711. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3712. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3713. <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>
  3714. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3715. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3716. </td>
  3717. `;
  3718. tbody.appendChild(tr);
  3719. });
  3720. }
  3721. function openAddMangleModal() {
  3722. document.getElementById('mangle-modal-title').innerText = 'Add Mangle Rule';
  3723. document.getElementById('mangle-modal-id').value = '';
  3724. document.getElementById('mangle-modal-chain').value = 'prerouting';
  3725. document.getElementById('mangle-modal-action').value = 'mark-connection';
  3726. document.getElementById('mangle-modal-newmark').value = '';
  3727. document.getElementById('mangle-modal-passthrough').checked = true;
  3728. document.getElementById('mangle-modal-src').value = '';
  3729. document.getElementById('mangle-modal-dst').value = '';
  3730. document.getElementById('mangle-modal-connmark').value = '';
  3731. document.getElementById('mangle-modal-comment').value = '';
  3732. document.getElementById('mangle-modal-disabled').checked = false;
  3733. populateInterfaceSelect('mangle-modal-iniface');
  3734. populateAddressListSelect('mangle-modal-srclist');
  3735. populateAddressListSelect('mangle-modal-dstlist');
  3736. const srcInvEl = document.getElementById('mangle-modal-srclist-inv');
  3737. if (srcInvEl) srcInvEl.checked = false;
  3738. const dstInvEl = document.getElementById('mangle-modal-dstlist-inv');
  3739. if (dstInvEl) dstInvEl.checked = false;
  3740. populateGeoIPSelect('mangle-modal-srcgeoip');
  3741. populateGeoIPSelect('mangle-modal-dstgeoip');
  3742. const srcGeoInvEl = document.getElementById('mangle-modal-srcgeoip-inv');
  3743. if (srcGeoInvEl) srcGeoInvEl.checked = false;
  3744. const dstGeoInvEl = document.getElementById('mangle-modal-dstgeoip-inv');
  3745. if (dstGeoInvEl) dstGeoInvEl.checked = false;
  3746. document.getElementById('mangle-modal').classList.remove('hidden');
  3747. }
  3748. function openEditMangleModal(id) {
  3749. const r = (state.mangleRules || []).find(rule => rule.id === id);
  3750. if (!r) return;
  3751. document.getElementById('mangle-modal-title').innerText = `Edit Mangle Rule (#${r.order})`;
  3752. document.getElementById('mangle-modal-id').value = r.id;
  3753. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  3754. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  3755. document.getElementById('mangle-modal-newmark').value = r.new_connection_mark || r.new_routing_mark || r.new_packet_mark || r.new_mss || '';
  3756. document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  3757. document.getElementById('mangle-modal-src').value = r.src_address || '';
  3758. document.getElementById('mangle-modal-dst').value = r.dst_address || '';
  3759. document.getElementById('mangle-modal-connmark').value = r.connection_mark || '';
  3760. document.getElementById('mangle-modal-comment').value = r.comment || '';
  3761. document.getElementById('mangle-modal-disabled').checked = !!r.disabled;
  3762. populateInterfaceSelect('mangle-modal-iniface', r.in_interface);
  3763. const srcInv = (r.src_address_list || '').startsWith('!');
  3764. const dstInv = (r.dst_address_list || '').startsWith('!');
  3765. const srcInvEl = document.getElementById('mangle-modal-srclist-inv');
  3766. if (srcInvEl) srcInvEl.checked = srcInv;
  3767. const dstInvEl = document.getElementById('mangle-modal-dstlist-inv');
  3768. if (dstInvEl) dstInvEl.checked = dstInv;
  3769. populateAddressListSelect('mangle-modal-srclist', r.src_address_list || '');
  3770. populateAddressListSelect('mangle-modal-dstlist', r.dst_address_list || '');
  3771. const srcGeoInv = (r.src_geoip || '').startsWith('!');
  3772. const dstGeoInv = (r.dst_geoip || '').startsWith('!');
  3773. const srcGeoInvEl = document.getElementById('mangle-modal-srcgeoip-inv');
  3774. if (srcGeoInvEl) srcGeoInvEl.checked = srcGeoInv;
  3775. const dstGeoInvEl = document.getElementById('mangle-modal-dstgeoip-inv');
  3776. if (dstGeoInvEl) dstGeoInvEl.checked = dstGeoInv;
  3777. populateGeoIPSelect('mangle-modal-srcgeoip', r.src_geoip || '');
  3778. populateGeoIPSelect('mangle-modal-dstgeoip', r.dst_geoip || '');
  3779. document.getElementById('mangle-modal').classList.remove('hidden');
  3780. }
  3781. function closeMangleModal() {
  3782. document.getElementById('mangle-modal').classList.add('hidden');
  3783. }
  3784. function toggleMangleActionFields() {
  3785. // Handled smoothly by single dynamic input
  3786. }
  3787. async function submitSaveMangleRule(e) {
  3788. e.preventDefault();
  3789. const id = document.getElementById('mangle-modal-id').value;
  3790. const chain = document.getElementById('mangle-modal-chain').value;
  3791. const action = document.getElementById('mangle-modal-action').value;
  3792. const newmark = document.getElementById('mangle-modal-newmark').value.trim();
  3793. const passthrough = document.getElementById('mangle-modal-passthrough').checked;
  3794. const src = document.getElementById('mangle-modal-src').value.trim();
  3795. const dst = document.getElementById('mangle-modal-dst').value.trim();
  3796. const inIface = document.getElementById('mangle-modal-iniface').value;
  3797. let srclist = document.getElementById('mangle-modal-srclist')?.value || '';
  3798. if (srclist && document.getElementById('mangle-modal-srclist-inv')?.checked) {
  3799. srclist = '!' + srclist.replace(/^!/, '');
  3800. }
  3801. let dstlist = document.getElementById('mangle-modal-dstlist')?.value || '';
  3802. if (dstlist && document.getElementById('mangle-modal-dstlist-inv')?.checked) {
  3803. dstlist = '!' + dstlist.replace(/^!/, '');
  3804. }
  3805. let srcgeoip = document.getElementById('mangle-modal-srcgeoip')?.value || '';
  3806. if (srcgeoip && document.getElementById('mangle-modal-srcgeoip-inv')?.checked) {
  3807. srcgeoip = '!' + srcgeoip.replace(/^!/, '');
  3808. }
  3809. let dstgeoip = document.getElementById('mangle-modal-dstgeoip')?.value || '';
  3810. if (dstgeoip && document.getElementById('mangle-modal-dstgeoip-inv')?.checked) {
  3811. dstgeoip = '!' + dstgeoip.replace(/^!/, '');
  3812. }
  3813. const connmark = document.getElementById('mangle-modal-connmark').value.trim();
  3814. const comment = document.getElementById('mangle-modal-comment').value.trim();
  3815. const disabled = document.getElementById('mangle-modal-disabled').checked;
  3816. const payload = {
  3817. id,
  3818. chain,
  3819. action,
  3820. passthrough,
  3821. src_address: src,
  3822. dst_address: dst,
  3823. in_interface: inIface,
  3824. src_address_list: srclist,
  3825. dst_address_list: dstlist,
  3826. src_geoip: srcgeoip,
  3827. dst_geoip: dstgeoip,
  3828. connection_mark: connmark,
  3829. comment,
  3830. disabled
  3831. };
  3832. if (action === 'mark-connection') payload.new_connection_mark = newmark;
  3833. else if (action === 'mark-routing') payload.new_routing_mark = newmark;
  3834. else if (action === 'mark-packet') payload.new_packet_mark = newmark;
  3835. else if (action === 'change-mss') payload.new_mss = newmark || 'clamp-to-pmtu';
  3836. try {
  3837. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  3838. method: 'POST',
  3839. headers: { 'Content-Type': 'application/json' },
  3840. body: JSON.stringify(payload)
  3841. });
  3842. if (res.ok) {
  3843. showToast('Mangle Rule Saved', 'Marking rule applied', 'success');
  3844. closeMangleModal();
  3845. loadFirewall(false);
  3846. }
  3847. } catch (err) {
  3848. showToast('Error', err.message, 'error');
  3849. }
  3850. }
  3851. async function moveMangleRule(id, dir) {
  3852. try {
  3853. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  3854. method: 'POST',
  3855. headers: { 'Content-Type': 'application/json' },
  3856. body: JSON.stringify({ direction: dir })
  3857. });
  3858. if (res.ok) loadFirewall(false);
  3859. } catch (err) {
  3860. showToast('Error', err.message, 'error');
  3861. }
  3862. }
  3863. async function toggleMangleRuleState(id, disabled) {
  3864. try {
  3865. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  3866. method: 'POST',
  3867. headers: { 'Content-Type': 'application/json' },
  3868. body: JSON.stringify({ disabled })
  3869. });
  3870. if (res.ok) loadFirewall(false);
  3871. } catch (err) {
  3872. showToast('Error', err.message, 'error');
  3873. }
  3874. }
  3875. async function deleteMangleRule(id) {
  3876. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  3877. try {
  3878. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3879. if (res.ok) {
  3880. showToast('Deleted', 'Mangle rule removed', 'success');
  3881. loadFirewall(false);
  3882. }
  3883. } catch (err) {
  3884. showToast('Error', err.message, 'error');
  3885. }
  3886. }
  3887. // ----------------- Address Lists -----------------
  3888. function renderAddressLists() {
  3889. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  3890. const tbody = document.getElementById('addrlist-table-body');
  3891. const empty = document.getElementById('addrlist-empty');
  3892. if (!tbody) return;
  3893. tbody.innerHTML = '';
  3894. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  3895. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  3896. // Update filter select
  3897. const sel = document.getElementById('addrlist-filter-name');
  3898. if (sel) {
  3899. const cur = sel.value;
  3900. sel.innerHTML = '<option value="">All Lists</option>';
  3901. const set = new Set((state.addressLists || []).map(a => a.name));
  3902. set.forEach(n => {
  3903. const opt = document.createElement('option');
  3904. opt.value = n;
  3905. opt.innerText = n;
  3906. if (n === cur) opt.selected = true;
  3907. sel.appendChild(opt);
  3908. });
  3909. }
  3910. if (entries.length === 0) {
  3911. empty?.classList.remove('hidden');
  3912. return;
  3913. }
  3914. empty?.classList.add('hidden');
  3915. entries.forEach((e, idx) => {
  3916. const tr = document.createElement('tr');
  3917. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  3918. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  3919. tr.innerHTML = `
  3920. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  3921. <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>
  3922. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  3923. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  3924. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  3925. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  3926. <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>
  3927. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  3928. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3929. </td>
  3930. `;
  3931. tbody.appendChild(tr);
  3932. });
  3933. }
  3934. function openAddAddrListModal() {
  3935. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  3936. document.getElementById('addrlist-modal-id').value = '';
  3937. document.getElementById('addrlist-modal-name').value = '';
  3938. document.getElementById('addrlist-modal-addr').value = '';
  3939. document.getElementById('addrlist-modal-comment').value = '';
  3940. document.getElementById('addrlist-modal-disabled').checked = false;
  3941. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  3942. if (submitBtn) submitBtn.innerText = 'Add to List';
  3943. document.getElementById('addrlist-modal').classList.remove('hidden');
  3944. }
  3945. function openEditAddrListModal(id) {
  3946. const e = (state.addressLists || []).find(item => item.id === id);
  3947. if (!e) return;
  3948. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  3949. document.getElementById('addrlist-modal-id').value = e.id;
  3950. document.getElementById('addrlist-modal-name').value = e.name;
  3951. document.getElementById('addrlist-modal-addr').value = e.address;
  3952. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  3953. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  3954. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  3955. if (submitBtn) submitBtn.innerText = 'Save Changes';
  3956. document.getElementById('addrlist-modal').classList.remove('hidden');
  3957. }
  3958. function closeAddrListModal() {
  3959. document.getElementById('addrlist-modal').classList.add('hidden');
  3960. }
  3961. async function submitSaveAddrList(e) {
  3962. e.preventDefault();
  3963. const id = document.getElementById('addrlist-modal-id').value;
  3964. const name = document.getElementById('addrlist-modal-name').value.trim();
  3965. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  3966. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  3967. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  3968. try {
  3969. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  3970. method: 'POST',
  3971. headers: { 'Content-Type': 'application/json' },
  3972. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  3973. });
  3974. if (res.ok) {
  3975. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  3976. closeAddrListModal();
  3977. loadFirewall(false);
  3978. } else {
  3979. const err = await res.json();
  3980. showToast('Error', err.message || 'Failed to save address list', 'error');
  3981. }
  3982. } catch (err) {
  3983. showToast('Error', err.message, 'error');
  3984. }
  3985. }
  3986. async function toggleAddrListState(id, disabled) {
  3987. try {
  3988. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  3989. method: 'POST',
  3990. headers: { 'Content-Type': 'application/json' },
  3991. body: JSON.stringify({ disabled })
  3992. });
  3993. if (res.ok) {
  3994. loadFirewall(false);
  3995. }
  3996. } catch (err) {
  3997. showToast('Error', err.message, 'error');
  3998. }
  3999. }
  4000. async function deleteAddrList(id) {
  4001. if (!confirm('Are you sure you want to delete this address list item?')) return;
  4002. try {
  4003. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4004. if (res.ok) {
  4005. showToast('Deleted', 'Address list item removed', 'info');
  4006. loadFirewall(false);
  4007. }
  4008. } catch (err) {
  4009. showToast('Error', err.message, 'error');
  4010. }
  4011. }
  4012. // ----------------- Geo-Location IP Management -----------------
  4013. async function loadGeoIP() {
  4014. try {
  4015. const [statusRes, countriesRes] = await Promise.all([
  4016. fetch(`${API_BASE}/firewall/geoip/status`),
  4017. fetch(`${API_BASE}/firewall/geoip/countries`)
  4018. ]);
  4019. if (statusRes.ok) state.geoStatus = await statusRes.json();
  4020. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  4021. updateGeoHeader();
  4022. renderGeoCountries();
  4023. } catch (err) {
  4024. console.error('Failed to load GeoIP:', err);
  4025. }
  4026. }
  4027. function getGeoUsageMap() {
  4028. const usage = {};
  4029. const checkRule = (r, type) => {
  4030. ['src_geoip', 'dst_geoip'].forEach(field => {
  4031. let val = (r && r[field]) || '';
  4032. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  4033. if (code) {
  4034. if (!usage[code]) usage[code] = [];
  4035. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  4036. if (!usage[code].includes(label)) usage[code].push(label);
  4037. }
  4038. });
  4039. };
  4040. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  4041. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  4042. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  4043. return usage;
  4044. }
  4045. function updateGeoHeader() {
  4046. const s = state.geoStatus || {};
  4047. const statusBadge = document.getElementById('geo-status-badge');
  4048. if (statusBadge) {
  4049. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  4050. statusBadge.className = s.auto_update
  4051. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  4052. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  4053. }
  4054. const intervalLabel = document.getElementById('geo-interval-label');
  4055. if (intervalLabel) {
  4056. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  4057. }
  4058. const usageMap = getGeoUsageMap();
  4059. const inUseCount = Object.keys(usageMap).length;
  4060. const activeCountEl = document.getElementById('geo-stat-active-countries');
  4061. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  4062. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  4063. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  4064. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  4065. if (lastSyncEl) {
  4066. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  4067. const d = new Date(s.last_updated);
  4068. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4069. } else {
  4070. lastSyncEl.innerText = 'Never (Sync Pending)';
  4071. }
  4072. }
  4073. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  4074. if (nextSyncEl) {
  4075. if (s.next_update && !s.next_update.startsWith('0001')) {
  4076. const d = new Date(s.next_update);
  4077. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4078. } else {
  4079. nextSyncEl.innerText = '-';
  4080. }
  4081. }
  4082. const badge = document.getElementById('fw-badge-geo');
  4083. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  4084. }
  4085. function renderGeoCountries() {
  4086. const tbody = document.getElementById('geo-table-body');
  4087. const empty = document.getElementById('geo-empty');
  4088. if (!tbody) return;
  4089. tbody.innerHTML = '';
  4090. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  4091. const continent = document.getElementById('geo-continent-filter')?.value || '';
  4092. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  4093. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  4094. const usageMap = getGeoUsageMap();
  4095. const countries = (state.geoCountries || []).filter(c => {
  4096. const isUsed = !!usageMap[c.code];
  4097. if (inUseOnly && !isUsed) return false;
  4098. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  4099. if (continent && c.continent !== continent) return false;
  4100. if (q) {
  4101. const matchCode = c.code.toLowerCase().includes(q);
  4102. const matchName = c.name.toLowerCase().includes(q);
  4103. if (!matchCode && !matchName) return false;
  4104. }
  4105. return true;
  4106. });
  4107. if (countries.length === 0) {
  4108. empty?.classList.remove('hidden');
  4109. return;
  4110. }
  4111. empty?.classList.add('hidden');
  4112. countries.forEach(c => {
  4113. const tr = document.createElement('tr');
  4114. const isUsed = !!usageMap[c.code];
  4115. const rulesUsing = usageMap[c.code] || [];
  4116. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  4117. let statusHtml = '';
  4118. if (isUsed) {
  4119. 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>`;
  4120. } else if (c.subnet_count > 0) {
  4121. 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>';
  4122. } else {
  4123. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  4124. }
  4125. tr.innerHTML = `
  4126. <td class="py-2.5 px-3 text-center">
  4127. <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'}">
  4128. ${c.code}
  4129. </span>
  4130. </td>
  4131. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  4132. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  4133. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  4134. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  4135. </td>
  4136. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  4137. <td class="py-2.5 px-3">
  4138. ${statusHtml}
  4139. </td>
  4140. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4141. <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>
  4142. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  4143. </td>
  4144. `;
  4145. tbody.appendChild(tr);
  4146. });
  4147. }
  4148. function quickFilterGeo(preset) {
  4149. const searchInput = document.getElementById('geo-search-input');
  4150. const continentSel = document.getElementById('geo-continent-filter');
  4151. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  4152. const cachedCheck = document.getElementById('geo-filter-cached-only');
  4153. if (searchInput) searchInput.value = '';
  4154. if (continentSel) continentSel.value = '';
  4155. if (inUseCheck) inUseCheck.checked = false;
  4156. if (cachedCheck) cachedCheck.checked = false;
  4157. if (preset === 'GR') {
  4158. if (searchInput) searchInput.value = 'Greece';
  4159. } else if (preset === 'Europe') {
  4160. if (continentSel) continentSel.value = 'Europe';
  4161. } else if (preset === 'HIGHRISK') {
  4162. if (searchInput) searchInput.value = 'China';
  4163. }
  4164. renderGeoCountries();
  4165. }
  4166. async function toggleGeoCountry(code, enabled) {
  4167. try {
  4168. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  4169. method: 'POST',
  4170. headers: { 'Content-Type': 'application/json' },
  4171. body: JSON.stringify({ enabled })
  4172. });
  4173. if (res.ok) {
  4174. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  4175. loadGeoIP();
  4176. } else {
  4177. const err = await res.json();
  4178. showToast('Error', err.message || 'Failed to toggle country', 'error');
  4179. }
  4180. } catch (err) {
  4181. showToast('Error', err.message, 'error');
  4182. }
  4183. }
  4184. async function updateGeoCountry(code) {
  4185. try {
  4186. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  4187. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  4188. if (res.ok) {
  4189. const data = await res.json();
  4190. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  4191. loadGeoIP();
  4192. } else {
  4193. const err = await res.json();
  4194. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  4195. }
  4196. } catch (err) {
  4197. showToast('Error', err.message, 'error');
  4198. }
  4199. }
  4200. async function triggerGeoUpdateNow() {
  4201. const spinner = document.getElementById('geo-update-spinner');
  4202. if (spinner) spinner.classList.remove('hidden');
  4203. try {
  4204. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  4205. if (res.ok) {
  4206. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  4207. setTimeout(() => {
  4208. loadGeoIP();
  4209. if (spinner) spinner.classList.add('hidden');
  4210. }, 2500);
  4211. } else {
  4212. const err = await res.json();
  4213. showToast('Notice', err.message || 'Update in progress', 'info');
  4214. if (spinner) spinner.classList.add('hidden');
  4215. }
  4216. } catch (err) {
  4217. showToast('Error', err.message, 'error');
  4218. if (spinner) spinner.classList.add('hidden');
  4219. }
  4220. }
  4221. async function applyGeoPreset(preset) {
  4222. try {
  4223. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  4224. method: 'POST',
  4225. headers: { 'Content-Type': 'application/json' },
  4226. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  4227. });
  4228. if (res.ok) {
  4229. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  4230. loadGeoIP();
  4231. }
  4232. } catch (err) {
  4233. showToast('Error', err.message, 'error');
  4234. }
  4235. }
  4236. function openGeoIntervalModal() {
  4237. const s = state.geoStatus || {};
  4238. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  4239. const sel = document.getElementById('geo-cfg-interval');
  4240. const customBox = document.getElementById('geo-cfg-custom-box');
  4241. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  4242. const curHours = s.interval_hours || 24;
  4243. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  4244. if (matchOption) {
  4245. sel.value = String(curHours);
  4246. customBox.classList.add('hidden');
  4247. } else {
  4248. sel.value = 'custom';
  4249. customHoursInput.value = curHours;
  4250. customBox.classList.remove('hidden');
  4251. }
  4252. document.getElementById('geo-interval-modal').classList.remove('hidden');
  4253. }
  4254. function closeGeoIntervalModal() {
  4255. document.getElementById('geo-interval-modal').classList.add('hidden');
  4256. }
  4257. function toggleCustomGeoInterval() {
  4258. const val = document.getElementById('geo-cfg-interval').value;
  4259. const customBox = document.getElementById('geo-cfg-custom-box');
  4260. if (val === 'custom') {
  4261. customBox.classList.remove('hidden');
  4262. } else {
  4263. customBox.classList.add('hidden');
  4264. }
  4265. }
  4266. async function submitGeoIntervalSettings(e) {
  4267. e.preventDefault();
  4268. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  4269. const intervalVal = document.getElementById('geo-cfg-interval').value;
  4270. let hours = 24;
  4271. if (intervalVal === 'custom') {
  4272. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  4273. } else {
  4274. hours = parseInt(intervalVal, 10) || 24;
  4275. }
  4276. try {
  4277. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  4278. method: 'POST',
  4279. headers: { 'Content-Type': 'application/json' },
  4280. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  4281. });
  4282. if (res.ok) {
  4283. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  4284. closeGeoIntervalModal();
  4285. loadGeoIP();
  4286. } else {
  4287. const err = await res.json();
  4288. showToast('Error', err.message || 'Failed to save schedule', 'error');
  4289. }
  4290. } catch (err) {
  4291. showToast('Error', err.message, 'error');
  4292. }
  4293. }
  4294. async function viewGeoSubnets(code, name) {
  4295. if (!name) {
  4296. const found = (state.geoCountries || []).find(x => x.code === code);
  4297. name = found ? found.name : code;
  4298. }
  4299. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  4300. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  4301. const listEl = document.getElementById('geo-subnets-list');
  4302. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  4303. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  4304. try {
  4305. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  4306. if (res.ok) {
  4307. const data = await res.json();
  4308. const subnets = data.subnets || [];
  4309. if (subnets.length === 0) {
  4310. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  4311. } else {
  4312. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  4313. }
  4314. } else {
  4315. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  4316. }
  4317. } catch (err) {
  4318. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  4319. }
  4320. }
  4321. function closeGeoSubnetsModal() {
  4322. document.getElementById('geo-subnets-modal').classList.add('hidden');
  4323. }
  4324. // ----------------- Active Connections Tracking -----------------
  4325. async function loadConnections() {
  4326. try {
  4327. const res = await fetch(`${API_BASE}/firewall/connections`);
  4328. const data = await res.json();
  4329. state.connections = Array.isArray(data) ? data : [];
  4330. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  4331. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  4332. renderConnections();
  4333. } catch (err) {
  4334. console.error('Failed to load connections:', err);
  4335. }
  4336. }
  4337. function renderConnections() {
  4338. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  4339. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  4340. const tbody = document.getElementById('conns-table-body');
  4341. const empty = document.getElementById('conns-empty');
  4342. if (!tbody) return;
  4343. tbody.innerHTML = '';
  4344. const conns = (state.connections || []).filter(c => {
  4345. if (protoFilter && c.protocol !== protoFilter) return false;
  4346. if (search) {
  4347. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  4348. if (!line.includes(search)) return false;
  4349. }
  4350. return true;
  4351. });
  4352. if (conns.length === 0) {
  4353. empty?.classList.remove('hidden');
  4354. return;
  4355. }
  4356. empty?.classList.add('hidden');
  4357. conns.slice(0, 150).forEach(c => {
  4358. const tr = document.createElement('tr');
  4359. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  4360. let stateColor = 'text-slate-400';
  4361. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  4362. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  4363. tr.innerHTML = `
  4364. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  4365. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  4366. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  4367. <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>
  4368. <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>
  4369. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  4370. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  4371. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  4372. <td class="py-2.5 px-3 text-right font-sans">
  4373. <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>
  4374. </td>
  4375. `;
  4376. tbody.appendChild(tr);
  4377. });
  4378. }
  4379. async function killConnection(protocol, src, sport, dst, dport) {
  4380. try {
  4381. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  4382. method: 'POST',
  4383. headers: { 'Content-Type': 'application/json' },
  4384. body: JSON.stringify({ protocol, src, sport, dst, dport })
  4385. });
  4386. if (res.ok) {
  4387. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  4388. loadConnections();
  4389. }
  4390. } catch (err) {
  4391. showToast('Error', err.message, 'error');
  4392. }
  4393. }
  4394. async function resetFirewallCounters() {
  4395. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  4396. try {
  4397. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  4398. if (res.ok) {
  4399. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  4400. loadFirewall(false);
  4401. }
  4402. } catch (err) {
  4403. showToast('Error', err.message, 'error');
  4404. }
  4405. }
  4406. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  4407. function switchRoutesSubTab(tab) {
  4408. state.routesSubTab = tab;
  4409. const tabs = ['routes', 'rules', 'tables'];
  4410. tabs.forEach(t => {
  4411. const panel = document.getElementById(`routes-subtab-${t}`);
  4412. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  4413. if (panel) {
  4414. if (t === tab) panel.classList.remove('hidden');
  4415. else panel.classList.add('hidden');
  4416. }
  4417. if (btn) {
  4418. if (t === tab) {
  4419. 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';
  4420. } else {
  4421. 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';
  4422. }
  4423. }
  4424. });
  4425. }
  4426. async function loadRoutes() {
  4427. try {
  4428. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  4429. fetch(`${API_BASE}/routes`),
  4430. fetch(`${API_BASE}/routing/rules`),
  4431. fetch(`${API_BASE}/routing/tables`)
  4432. ]);
  4433. if (routesRes.ok) state.routes = await routesRes.json();
  4434. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  4435. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  4436. const bRoutes = document.getElementById('routes-badge-routes');
  4437. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  4438. const bRules = document.getElementById('routes-badge-rules');
  4439. if (bRules) bRules.innerText = (state.policyRules || []).length;
  4440. const bTables = document.getElementById('routes-badge-tables');
  4441. if (bTables) bTables.innerText = (state.routingTables || []).length;
  4442. const bRoutesCount = document.getElementById('badge-routes-count');
  4443. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  4444. renderRoutesList();
  4445. renderPolicyRules();
  4446. renderRoutingTables();
  4447. } catch (err) {
  4448. console.error('Failed to load routing:', err);
  4449. }
  4450. }
  4451. function renderRoutesList() {
  4452. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  4453. const tbody = document.getElementById('routes-table-body');
  4454. const empty = document.getElementById('routes-empty');
  4455. if (!tbody) return;
  4456. tbody.innerHTML = '';
  4457. // Update table filter select
  4458. const sel = document.getElementById('routes-filter-table');
  4459. if (sel) {
  4460. const cur = sel.value;
  4461. sel.innerHTML = '<option value="">All Tables</option>';
  4462. (state.routingTables || []).forEach(t => {
  4463. const opt = document.createElement('option');
  4464. opt.value = t.name;
  4465. opt.innerText = t.name;
  4466. if (t.name === cur) opt.selected = true;
  4467. sel.appendChild(opt);
  4468. });
  4469. }
  4470. const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
  4471. document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
  4472. if (routes.length === 0) {
  4473. empty?.classList.remove('hidden');
  4474. return;
  4475. }
  4476. empty?.classList.add('hidden');
  4477. routes.forEach(r => {
  4478. const tr = document.createElement('tr');
  4479. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  4480. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  4481. // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
  4482. let flags = '';
  4483. if (r.dynamic) flags += 'D';
  4484. if (r.active) flags += 'A';
  4485. if (r.connect) flags += 'C';
  4486. if (r.static) flags += 'S';
  4487. if (r.disabled) flags += 'X';
  4488. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  4489. tr.innerHTML = `
  4490. <td class="py-2.5 px-3 text-center">
  4491. <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'}">
  4492. ${flags || '-'}
  4493. </span>
  4494. </td>
  4495. <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
  4496. <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>
  4497. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  4498. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  4499. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  4500. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  4501. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4502. ${r.static ? `
  4503. <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>
  4504. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  4505. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4506. ` : `
  4507. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  4508. `}
  4509. </td>
  4510. `;
  4511. tbody.appendChild(tr);
  4512. });
  4513. }
  4514. function openAddRouteModal() {
  4515. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  4516. document.getElementById('route-modal-id').value = '';
  4517. document.getElementById('route-modal-old-dst').value = '';
  4518. document.getElementById('route-modal-old-gw').value = '';
  4519. document.getElementById('route-modal-old-distance').value = '';
  4520. document.getElementById('route-modal-old-table').value = '';
  4521. document.getElementById('route-modal-old-iface').value = '';
  4522. const dstInput = document.getElementById('route-modal-dst');
  4523. const gwInput = document.getElementById('route-modal-gw');
  4524. const distInput = document.getElementById('route-modal-distance');
  4525. const ifaceSelect = document.getElementById('route-modal-iface');
  4526. const tableSelect = document.getElementById('route-modal-table');
  4527. const commentInput = document.getElementById('route-modal-comment');
  4528. const disCheck = document.getElementById('route-modal-disabled');
  4529. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  4530. dstInput.disabled = false;
  4531. dstInput.value = '0.0.0.0/0';
  4532. gwInput.disabled = false;
  4533. gwInput.value = '';
  4534. distInput.disabled = false;
  4535. distInput.value = '1';
  4536. ifaceSelect.disabled = false;
  4537. tableSelect.disabled = false;
  4538. commentInput.disabled = false;
  4539. commentInput.value = '';
  4540. disCheck.disabled = false;
  4541. disCheck.checked = false;
  4542. if (saveBtn) saveBtn.classList.remove('hidden');
  4543. populateInterfaceSelect('route-modal-iface');
  4544. // Populate tables
  4545. tableSelect.innerHTML = '';
  4546. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  4547. const opt = document.createElement('option');
  4548. opt.value = t.name;
  4549. opt.innerText = t.name;
  4550. if (t.name === 'main') opt.selected = true;
  4551. tableSelect.appendChild(opt);
  4552. });
  4553. document.getElementById('route-modal').classList.remove('hidden');
  4554. }
  4555. function openEditRouteModal(id) {
  4556. const r = (state.routes || []).find(route => route.id === id);
  4557. if (!r) return;
  4558. const isStatic = !!r.static;
  4559. document.getElementById('route-modal-title').innerText = isStatic
  4560. ? `Edit Route: ${r.dst_address}`
  4561. : `Route Properties (Read Only): ${r.dst_address}`;
  4562. document.getElementById('route-modal-id').value = r.id;
  4563. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  4564. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  4565. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  4566. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  4567. document.getElementById('route-modal-old-iface').value = r.interface || '';
  4568. const dstInput = document.getElementById('route-modal-dst');
  4569. const gwInput = document.getElementById('route-modal-gw');
  4570. const distInput = document.getElementById('route-modal-distance');
  4571. const ifaceSelect = document.getElementById('route-modal-iface');
  4572. const tableSelect = document.getElementById('route-modal-table');
  4573. const commentInput = document.getElementById('route-modal-comment');
  4574. const disCheck = document.getElementById('route-modal-disabled');
  4575. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  4576. dstInput.value = r.dst_address;
  4577. gwInput.value = r.gateway || '';
  4578. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  4579. commentInput.value = r.comment || '';
  4580. disCheck.checked = !!r.disabled;
  4581. dstInput.disabled = !isStatic;
  4582. gwInput.disabled = !isStatic;
  4583. distInput.disabled = !isStatic;
  4584. ifaceSelect.disabled = !isStatic;
  4585. tableSelect.disabled = !isStatic;
  4586. commentInput.disabled = !isStatic;
  4587. disCheck.disabled = !isStatic;
  4588. if (saveBtn) {
  4589. if (isStatic) {
  4590. saveBtn.classList.remove('hidden');
  4591. } else {
  4592. saveBtn.classList.add('hidden');
  4593. }
  4594. }
  4595. populateInterfaceSelect('route-modal-iface', r.interface);
  4596. tableSelect.innerHTML = '';
  4597. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  4598. const opt = document.createElement('option');
  4599. opt.value = t.name;
  4600. opt.innerText = t.name;
  4601. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  4602. tableSelect.appendChild(opt);
  4603. });
  4604. document.getElementById('route-modal').classList.remove('hidden');
  4605. }
  4606. function closeRouteModal() {
  4607. document.getElementById('route-modal').classList.add('hidden');
  4608. }
  4609. async function submitSaveRoute(e) {
  4610. e.preventDefault();
  4611. const id = document.getElementById('route-modal-id').value;
  4612. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  4613. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  4614. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  4615. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  4616. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  4617. const dst = document.getElementById('route-modal-dst').value.trim();
  4618. const gw = document.getElementById('route-modal-gw').value.trim();
  4619. const table = document.getElementById('route-modal-table').value;
  4620. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  4621. const iface = document.getElementById('route-modal-iface').value;
  4622. const comment = document.getElementById('route-modal-comment').value.trim();
  4623. const disabled = document.getElementById('route-modal-disabled').checked;
  4624. if (!dst) {
  4625. showToast('Error', 'Destination address is required', 'error');
  4626. return;
  4627. }
  4628. if (!gw && !iface) {
  4629. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  4630. return;
  4631. }
  4632. const payload = {
  4633. id,
  4634. old_dst_address: oldDst,
  4635. old_gateway: oldGw,
  4636. old_routing_table: oldTable,
  4637. old_interface: oldIface,
  4638. dst_address: dst,
  4639. gateway: gw || iface,
  4640. routing_table: table,
  4641. distance,
  4642. interface: iface,
  4643. comment,
  4644. disabled
  4645. };
  4646. if (oldDistStr !== undefined && oldDistStr !== '') {
  4647. payload.old_distance = parseInt(oldDistStr, 10);
  4648. }
  4649. try {
  4650. const res = await fetch(`${API_BASE}/routes`, {
  4651. method: 'POST',
  4652. headers: { 'Content-Type': 'application/json' },
  4653. body: JSON.stringify(payload)
  4654. });
  4655. if (res.ok) {
  4656. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  4657. closeRouteModal();
  4658. loadRoutes();
  4659. } else {
  4660. const err = await res.json();
  4661. showToast('Error', err.message || 'Failed to save route', 'error');
  4662. }
  4663. } catch (err) {
  4664. showToast('Error', err.message, 'error');
  4665. }
  4666. }
  4667. async function toggleRouteState(id, disabled) {
  4668. try {
  4669. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  4670. method: 'POST',
  4671. headers: { 'Content-Type': 'application/json' },
  4672. body: JSON.stringify({ disabled })
  4673. });
  4674. if (res.ok) loadRoutes();
  4675. } catch (err) {
  4676. showToast('Error', err.message, 'error');
  4677. }
  4678. }
  4679. async function deleteRoute(id) {
  4680. if (!confirm('Are you sure you want to delete this route?')) return;
  4681. try {
  4682. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4683. if (res.ok) {
  4684. showToast('Deleted', 'Route removed', 'success');
  4685. loadRoutes();
  4686. }
  4687. } catch (err) {
  4688. showToast('Error', err.message, 'error');
  4689. }
  4690. }
  4691. // ----------------- Policy Rules (/ip route rule) -----------------
  4692. function renderPolicyRules() {
  4693. const tbody = document.getElementById('rules-table-body');
  4694. const empty = document.getElementById('rules-empty');
  4695. if (!tbody) return;
  4696. tbody.innerHTML = '';
  4697. const rules = state.policyRules || [];
  4698. document.getElementById('rules-count-badge').innerText = `${rules.length} Rules`;
  4699. if (rules.length === 0) {
  4700. empty?.classList.remove('hidden');
  4701. return;
  4702. }
  4703. empty?.classList.add('hidden');
  4704. rules.forEach(pr => {
  4705. const tr = document.createElement('tr');
  4706. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  4707. tr.innerHTML = `
  4708. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  4709. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  4710. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  4711. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  4712. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  4713. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  4714. <td class="py-2.5 px-3 text-right font-sans">
  4715. ${pr.priority < 32766 && pr.priority > 0 ? `
  4716. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4717. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  4718. </td>
  4719. `;
  4720. tbody.appendChild(tr);
  4721. });
  4722. }
  4723. function openAddPolicyRuleModal() {
  4724. document.getElementById('prule-modal-pref').value = (state.policyRules || []).length * 10 + 1000;
  4725. document.getElementById('prule-modal-mark').value = '';
  4726. document.getElementById('prule-modal-src').value = '';
  4727. document.getElementById('prule-modal-dst').value = '';
  4728. const sel = document.getElementById('prule-modal-table');
  4729. sel.innerHTML = '';
  4730. (state.routingTables || []).forEach(t => {
  4731. const opt = document.createElement('option');
  4732. opt.value = t.name;
  4733. opt.innerText = t.name;
  4734. sel.appendChild(opt);
  4735. });
  4736. document.getElementById('prule-modal').classList.remove('hidden');
  4737. }
  4738. function closePolicyRuleModal() {
  4739. document.getElementById('prule-modal').classList.add('hidden');
  4740. }
  4741. async function submitSavePolicyRule(e) {
  4742. e.preventDefault();
  4743. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  4744. const mark = document.getElementById('prule-modal-mark').value.trim();
  4745. const src = document.getElementById('prule-modal-src').value.trim();
  4746. const dst = document.getElementById('prule-modal-dst').value.trim();
  4747. const table = document.getElementById('prule-modal-table').value;
  4748. const action = document.getElementById('prule-modal-action').value;
  4749. try {
  4750. const res = await fetch(`${API_BASE}/routing/rules`, {
  4751. method: 'POST',
  4752. headers: { 'Content-Type': 'application/json' },
  4753. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  4754. });
  4755. if (res.ok) {
  4756. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  4757. closePolicyRuleModal();
  4758. loadRoutes();
  4759. } else {
  4760. const err = await res.json();
  4761. showToast('Error', err.message, 'error');
  4762. }
  4763. } catch (err) {
  4764. showToast('Error', err.message, 'error');
  4765. }
  4766. }
  4767. async function deletePolicyRule(id) {
  4768. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  4769. try {
  4770. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4771. if (res.ok) {
  4772. showToast('Rule Removed', 'Policy rule deleted', 'success');
  4773. loadRoutes();
  4774. }
  4775. } catch (err) {
  4776. showToast('Error', err.message, 'error');
  4777. }
  4778. }
  4779. // ----------------- Routing Tables -----------------
  4780. function renderRoutingTables() {
  4781. const tbody = document.getElementById('tables-table-body');
  4782. if (!tbody) return;
  4783. tbody.innerHTML = '';
  4784. (state.routingTables || []).forEach(t => {
  4785. const tr = document.createElement('tr');
  4786. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  4787. tr.innerHTML = `
  4788. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  4789. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  4790. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  4791. `;
  4792. tbody.appendChild(tr);
  4793. });
  4794. }
  4795. function openAddTableModal() {
  4796. document.getElementById('table-modal-name').value = '';
  4797. document.getElementById('table-modal-id').value = '';
  4798. document.getElementById('table-modal-comment').value = '';
  4799. document.getElementById('table-modal').classList.remove('hidden');
  4800. }
  4801. function closeTableModal() {
  4802. document.getElementById('table-modal').classList.add('hidden');
  4803. }
  4804. async function submitSaveTable(e) {
  4805. e.preventDefault();
  4806. const name = document.getElementById('table-modal-name').value.trim();
  4807. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  4808. const comment = document.getElementById('table-modal-comment').value.trim();
  4809. try {
  4810. const res = await fetch(`${API_BASE}/routing/tables`, {
  4811. method: 'POST',
  4812. headers: { 'Content-Type': 'application/json' },
  4813. body: JSON.stringify({ name, table_id: id, comment })
  4814. });
  4815. if (res.ok) {
  4816. showToast('Table Created', `Routing table ${name} registered`, 'success');
  4817. closeTableModal();
  4818. loadRoutes();
  4819. } else {
  4820. const err = await res.json();
  4821. showToast('Error', err.message, 'error');
  4822. }
  4823. } catch (err) {
  4824. showToast('Error', err.message, 'error');
  4825. }
  4826. }
  4827. async function loadDebianConfig() {
  4828. const view = document.getElementById('debian-config-view');
  4829. view.innerText = 'Generating live configuration...';
  4830. try {
  4831. const res = await fetch(`${API_BASE}/debian/config`);
  4832. const data = await res.json();
  4833. view.innerText = data.content || '# Empty config';
  4834. } catch (err) {
  4835. view.innerText = 'Failed to generate Debian network config.';
  4836. }
  4837. }
  4838. async function saveDebianConfig() {
  4839. try {
  4840. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  4841. const data = await res.json();
  4842. if (res.ok) {
  4843. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  4844. loadDebianConfig();
  4845. }
  4846. } catch (err) {
  4847. showToast('Error', err.message, 'error');
  4848. }
  4849. }
  4850. function showToast(title, message, type = 'info') {
  4851. const container = document.getElementById('toast-container');
  4852. const toast = document.createElement('div');
  4853. const borderColors = {
  4854. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  4855. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  4856. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  4857. };
  4858. 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}`;
  4859. toast.innerHTML = `
  4860. <div class="flex-1">
  4861. <div class="font-bold text-xs text-white">${title}</div>
  4862. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  4863. </div>
  4864. `;
  4865. container.appendChild(toast);
  4866. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  4867. setTimeout(() => {
  4868. toast.classList.add('opacity-0', 'translate-y-2');
  4869. setTimeout(() => toast.remove(), 300);
  4870. }, 4000);
  4871. }
  4872. function formatTraffic(bytesPerSec) {
  4873. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  4874. const kb = bytesPerSec / 1024;
  4875. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  4876. const mb = kb / 1024;
  4877. return `${mb.toFixed(2)} MB/s`;
  4878. }
  4879. function toggleSidebar() {
  4880. const sb = document.getElementById('sidebar');
  4881. sb.classList.toggle('-translate-x-full');
  4882. }
  4883. // ======================== EoIP (Ethernet over IP) ========================
  4884. async function loadEoIP(populate = true) {
  4885. try {
  4886. const res = await fetch(`${API_BASE}/vpn/eoip`);
  4887. const data = await res.json();
  4888. state.eoipTunnels = Array.isArray(data) ? data : [];
  4889. const badge = document.getElementById('eoip-count-badge');
  4890. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  4891. const sideBadge = document.getElementById('badge-eoip-count');
  4892. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  4893. renderEoIPTunnels();
  4894. } catch (err) {
  4895. console.error('Failed to load EoIP:', err);
  4896. }
  4897. }
  4898. function renderEoIPTunnels() {
  4899. const tbody = document.getElementById('eoip-table-body');
  4900. const empty = document.getElementById('eoip-empty');
  4901. if (!tbody) return;
  4902. tbody.innerHTML = '';
  4903. const tunnels = state.eoipTunnels || [];
  4904. if (tunnels.length === 0) {
  4905. empty?.classList.remove('hidden');
  4906. return;
  4907. }
  4908. empty?.classList.add('hidden');
  4909. tunnels.forEach(t => {
  4910. const tr = document.createElement('tr');
  4911. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  4912. tr.innerHTML = `
  4913. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  4914. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  4915. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  4916. <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>
  4917. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  4918. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  4919. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  4920. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  4921. <td class="py-2.5 px-3 font-mono text-[11px]">
  4922. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  4923. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  4924. </td>
  4925. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  4926. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4927. <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>
  4928. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4929. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  4930. </td>
  4931. `;
  4932. tbody.appendChild(tr);
  4933. });
  4934. }
  4935. function openAddEoIPModal() {
  4936. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  4937. document.getElementById('eoip-modal-id').value = '';
  4938. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  4939. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  4940. document.getElementById('eoip-modal-remote').value = '';
  4941. document.getElementById('eoip-modal-ip').value = '';
  4942. document.getElementById('eoip-modal-local').value = '';
  4943. document.getElementById('eoip-modal-mac').value = '';
  4944. document.getElementById('eoip-modal-mtu').value = '1500';
  4945. document.getElementById('eoip-modal-comment').value = '';
  4946. document.getElementById('eoip-modal-clampmss').checked = true;
  4947. document.getElementById('eoip-modal-disabled').checked = false;
  4948. document.getElementById('eoip-modal').classList.remove('hidden');
  4949. }
  4950. function openEditEoIPModal(id) {
  4951. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  4952. if (!t) return;
  4953. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  4954. document.getElementById('eoip-modal-id').value = t.id;
  4955. document.getElementById('eoip-modal-name').value = t.name;
  4956. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  4957. document.getElementById('eoip-modal-remote').value = t.remote_address;
  4958. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  4959. document.getElementById('eoip-modal-local').value = t.local_address || '';
  4960. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  4961. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  4962. document.getElementById('eoip-modal-comment').value = t.comment || '';
  4963. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  4964. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  4965. document.getElementById('eoip-modal').classList.remove('hidden');
  4966. }
  4967. function closeEoIPModal() {
  4968. document.getElementById('eoip-modal').classList.add('hidden');
  4969. }
  4970. async function submitSaveEoIP(e) {
  4971. e.preventDefault();
  4972. const id = document.getElementById('eoip-modal-id').value;
  4973. const name = document.getElementById('eoip-modal-name').value.trim();
  4974. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  4975. const remote = document.getElementById('eoip-modal-remote').value.trim();
  4976. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  4977. const local = document.getElementById('eoip-modal-local').value.trim();
  4978. const mac = document.getElementById('eoip-modal-mac').value.trim();
  4979. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  4980. const comment = document.getElementById('eoip-modal-comment').value.trim();
  4981. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  4982. const disabled = document.getElementById('eoip-modal-disabled').checked;
  4983. try {
  4984. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  4985. method: 'POST',
  4986. headers: { 'Content-Type': 'application/json' },
  4987. body: JSON.stringify({
  4988. id,
  4989. name,
  4990. tunnel_id: tunnelId,
  4991. remote_address: remote,
  4992. ip_address: ipAddress,
  4993. local_address: local,
  4994. mac_address: mac,
  4995. mtu,
  4996. clamp_mss: clampMss,
  4997. comment,
  4998. disabled
  4999. })
  5000. });
  5001. if (res.ok) {
  5002. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  5003. closeEoIPModal();
  5004. loadEoIP(false);
  5005. fetchData(false);
  5006. } else {
  5007. const err = await res.json();
  5008. showToast('Error', err.message, 'error');
  5009. }
  5010. } catch (err) {
  5011. showToast('Error', err.message, 'error');
  5012. }
  5013. }
  5014. async function toggleEoIPState(id, disabled) {
  5015. try {
  5016. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  5017. method: 'POST',
  5018. headers: { 'Content-Type': 'application/json' },
  5019. body: JSON.stringify({ disabled })
  5020. });
  5021. if (res.ok) {
  5022. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  5023. loadEoIP(false);
  5024. fetchData(false);
  5025. }
  5026. } catch (err) {
  5027. showToast('Error', err.message, 'error');
  5028. }
  5029. }
  5030. async function deleteEoIP(id) {
  5031. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  5032. try {
  5033. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5034. if (res.ok) {
  5035. showToast('Deleted', 'EoIP tunnel removed', 'success');
  5036. loadEoIP(false);
  5037. fetchData(false);
  5038. }
  5039. } catch (err) {
  5040. showToast('Error', err.message, 'error');
  5041. }
  5042. }
  5043. // ======================== PPP Central Hub & Servers ========================
  5044. function switchPPPSubTab(tab) {
  5045. state.pppSubTab = tab;
  5046. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  5047. tabs.forEach(t => {
  5048. const panel = document.getElementById(`ppp-subtab-${t}`);
  5049. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  5050. if (panel) {
  5051. if (t === tab) panel.classList.remove('hidden');
  5052. else panel.classList.add('hidden');
  5053. }
  5054. if (btn) {
  5055. if (t === tab) {
  5056. 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';
  5057. } else {
  5058. 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';
  5059. }
  5060. }
  5061. });
  5062. const addBtn = document.getElementById('ppp-primary-add-btn');
  5063. if (addBtn) {
  5064. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  5065. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  5066. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  5067. else addBtn.innerHTML = '<span>Save Config</span>';
  5068. }
  5069. if (tab === 'active') loadPPPSessions();
  5070. }
  5071. function openCurrentPPPModal() {
  5072. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  5073. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  5074. else if (state.pppSubTab === 'active') loadPPPSessions();
  5075. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  5076. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  5077. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  5078. }
  5079. async function loadPPP(populateDropdowns = true) {
  5080. await Promise.all([
  5081. loadPPPSecrets(),
  5082. loadPPPProfiles(),
  5083. loadPPPServers(),
  5084. loadPPPSessions()
  5085. ]);
  5086. }
  5087. async function loadPPPSecrets() {
  5088. try {
  5089. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  5090. const data = await res.json();
  5091. state.pppSecrets = Array.isArray(data) ? data : [];
  5092. const b = document.getElementById('ppp-badge-secrets');
  5093. if (b) b.innerText = state.pppSecrets.length;
  5094. const b2 = document.getElementById('secrets-count-badge');
  5095. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  5096. renderPPPSecrets();
  5097. } catch (err) {
  5098. console.error('Failed to load PPP secrets:', err);
  5099. }
  5100. }
  5101. function renderPPPSecrets() {
  5102. const tbody = document.getElementById('secrets-table-body');
  5103. const empty = document.getElementById('secrets-empty');
  5104. if (!tbody) return;
  5105. tbody.innerHTML = '';
  5106. const secrets = state.pppSecrets || [];
  5107. if (secrets.length === 0) {
  5108. empty?.classList.remove('hidden');
  5109. return;
  5110. }
  5111. empty?.classList.add('hidden');
  5112. secrets.forEach(s => {
  5113. const tr = document.createElement('tr');
  5114. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  5115. tr.innerHTML = `
  5116. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  5117. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  5118. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  5119. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  5120. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  5121. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  5122. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  5123. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5124. <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>
  5125. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5126. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  5127. </td>
  5128. `;
  5129. tbody.appendChild(tr);
  5130. });
  5131. }
  5132. async function loadPPPProfiles() {
  5133. try {
  5134. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  5135. const data = await res.json();
  5136. state.pppProfiles = Array.isArray(data) ? data : [];
  5137. const b = document.getElementById('ppp-badge-profiles');
  5138. if (b) b.innerText = state.pppProfiles.length;
  5139. const b2 = document.getElementById('profiles-count-badge');
  5140. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  5141. // Populate profile selects across modals
  5142. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  5143. selects.forEach(sid => {
  5144. const el = document.getElementById(sid);
  5145. if (!el) return;
  5146. const cur = el.value;
  5147. el.innerHTML = '';
  5148. state.pppProfiles.forEach(p => {
  5149. const opt = document.createElement('option');
  5150. opt.value = p.name;
  5151. opt.innerText = `${p.name} (${p.remote_address})`;
  5152. if (p.name === cur) opt.selected = true;
  5153. el.appendChild(opt);
  5154. });
  5155. });
  5156. renderPPPProfiles();
  5157. } catch (err) {
  5158. console.error('Failed to load PPP profiles:', err);
  5159. }
  5160. }
  5161. function renderPPPProfiles() {
  5162. const tbody = document.getElementById('profiles-table-body');
  5163. if (!tbody) return;
  5164. tbody.innerHTML = '';
  5165. (state.pppProfiles || []).forEach(p => {
  5166. const isDefault = p.name.startsWith('default');
  5167. const tr = document.createElement('tr');
  5168. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5169. tr.innerHTML = `
  5170. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  5171. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  5172. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  5173. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  5174. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  5175. <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>
  5176. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  5177. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  5178. ${!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>`}
  5179. </td>
  5180. `;
  5181. tbody.appendChild(tr);
  5182. });
  5183. }
  5184. async function loadPPPServers() {
  5185. try {
  5186. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  5187. fetch(`${API_BASE}/vpn/servers/pppoe`),
  5188. fetch(`${API_BASE}/vpn/servers/pptp`),
  5189. fetch(`${API_BASE}/vpn/servers/l2tp`),
  5190. fetch(`${API_BASE}/vpn/servers/ipsec`)
  5191. ]);
  5192. if (pppoeRes.ok) {
  5193. state.pppoeServer = await pppoeRes.json();
  5194. const s = state.pppoeServer;
  5195. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  5196. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  5197. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  5198. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  5199. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  5200. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  5201. const pill = document.getElementById('pppoe-server-status-pill');
  5202. if (pill) {
  5203. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  5204. 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';
  5205. }
  5206. setDotBadge('ppp-badge-pppoe-state', s.running);
  5207. }
  5208. if (pptpRes.ok) {
  5209. state.pptpServer = await pptpRes.json();
  5210. const s = state.pptpServer;
  5211. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  5212. document.getElementById('pptp-server-port').value = s.port || 1723;
  5213. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  5214. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  5215. const pill = document.getElementById('pptp-server-status-pill');
  5216. if (pill) {
  5217. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  5218. 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';
  5219. }
  5220. setDotBadge('ppp-badge-pptp-state', s.running);
  5221. }
  5222. if (l2tpRes.ok) {
  5223. state.l2tpServer = await l2tpRes.json();
  5224. const s = state.l2tpServer;
  5225. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  5226. document.getElementById('l2tp-server-port').value = s.port || 1701;
  5227. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  5228. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  5229. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  5230. const pill = document.getElementById('l2tp-server-status-pill');
  5231. if (pill) {
  5232. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  5233. 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';
  5234. }
  5235. setDotBadge('ppp-badge-l2tp-state', s.running);
  5236. }
  5237. if (ipsecRes.ok) {
  5238. state.ipsecServer = await ipsecRes.json();
  5239. const s = state.ipsecServer;
  5240. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  5241. if (modalEn) modalEn.checked = !!s.enabled;
  5242. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  5243. if (modalPsk) modalPsk.value = s.preshared_key || '';
  5244. const modalPool = document.getElementById('modal-ipsec-server-pool');
  5245. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  5246. const modalDns = document.getElementById('modal-ipsec-server-dns');
  5247. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  5248. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  5249. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  5250. const pill = document.getElementById('modal-ipsec-server-status');
  5251. if (pill) {
  5252. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  5253. 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';
  5254. }
  5255. }
  5256. } catch (err) {
  5257. console.error('Failed to load VPN servers:', err);
  5258. }
  5259. }
  5260. async function loadPPPSessions() {
  5261. try {
  5262. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  5263. const data = await res.json();
  5264. state.pppActiveSessions = Array.isArray(data) ? data : [];
  5265. const b = document.getElementById('ppp-badge-active');
  5266. if (b) b.innerText = state.pppActiveSessions.length;
  5267. const sideB = document.getElementById('badge-ppp-sessions');
  5268. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  5269. renderPPPSessions();
  5270. } catch (err) {
  5271. console.error('Failed to load active PPP sessions:', err);
  5272. }
  5273. }
  5274. function renderPPPSessions() {
  5275. const tbody = document.getElementById('active-ppp-table-body');
  5276. const empty = document.getElementById('active-ppp-empty');
  5277. if (!tbody) return;
  5278. tbody.innerHTML = '';
  5279. const list = state.pppActiveSessions || [];
  5280. if (list.length === 0) {
  5281. empty?.classList.remove('hidden');
  5282. return;
  5283. }
  5284. empty?.classList.add('hidden');
  5285. list.forEach(s => {
  5286. const tr = document.createElement('tr');
  5287. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5288. tr.innerHTML = `
  5289. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  5290. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  5291. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  5292. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  5293. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  5294. <td class="py-2.5 px-3 text-[11px]">
  5295. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  5296. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  5297. </td>
  5298. <td class="py-2.5 px-3 text-right font-sans">
  5299. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  5300. </td>
  5301. `;
  5302. tbody.appendChild(tr);
  5303. });
  5304. }
  5305. async function disconnectPPPSession(iface) {
  5306. if (!confirm(`Disconnect session ${iface}?`)) return;
  5307. try {
  5308. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  5309. if (res.ok) {
  5310. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  5311. loadPPPSessions();
  5312. }
  5313. } catch (err) {
  5314. showToast('Error', err.message, 'error');
  5315. }
  5316. }
  5317. // PPP Secret Modal handlers
  5318. function openAddPPPSecretModal() {
  5319. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  5320. document.getElementById('secret-modal-id').value = '';
  5321. document.getElementById('secret-modal-name').value = '';
  5322. document.getElementById('secret-modal-password').value = '';
  5323. document.getElementById('secret-modal-service').value = 'any';
  5324. document.getElementById('secret-modal-profile').value = 'default';
  5325. document.getElementById('secret-modal-local').value = '';
  5326. document.getElementById('secret-modal-remote').value = '';
  5327. document.getElementById('secret-modal-comment').value = '';
  5328. document.getElementById('secret-modal-disabled').checked = false;
  5329. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  5330. }
  5331. function openEditPPPSecretModal(id) {
  5332. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  5333. if (!s) return;
  5334. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  5335. document.getElementById('secret-modal-id').value = s.id;
  5336. document.getElementById('secret-modal-name').value = s.name;
  5337. document.getElementById('secret-modal-password').value = s.password;
  5338. document.getElementById('secret-modal-service').value = s.service || 'any';
  5339. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  5340. document.getElementById('secret-modal-local').value = s.local_address || '';
  5341. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  5342. document.getElementById('secret-modal-comment').value = s.comment || '';
  5343. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  5344. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  5345. }
  5346. function closePPPSecretModal() {
  5347. document.getElementById('ppp-secret-modal').classList.add('hidden');
  5348. }
  5349. async function submitSavePPPSecret(e) {
  5350. e.preventDefault();
  5351. const id = document.getElementById('secret-modal-id').value;
  5352. const name = document.getElementById('secret-modal-name').value.trim();
  5353. const password = document.getElementById('secret-modal-password').value.trim();
  5354. const service = document.getElementById('secret-modal-service').value;
  5355. const profile = document.getElementById('secret-modal-profile').value;
  5356. const local = document.getElementById('secret-modal-local').value.trim();
  5357. const remote = document.getElementById('secret-modal-remote').value.trim();
  5358. const comment = document.getElementById('secret-modal-comment').value.trim();
  5359. const disabled = document.getElementById('secret-modal-disabled').checked;
  5360. try {
  5361. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  5362. method: 'POST',
  5363. headers: { 'Content-Type': 'application/json' },
  5364. body: JSON.stringify({
  5365. id,
  5366. name,
  5367. password,
  5368. service,
  5369. profile,
  5370. local_address: local,
  5371. remote_address: remote,
  5372. comment,
  5373. disabled
  5374. })
  5375. });
  5376. if (res.ok) {
  5377. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  5378. closePPPSecretModal();
  5379. loadPPPSecrets();
  5380. } else {
  5381. const err = await res.json();
  5382. showToast('Error', err.message, 'error');
  5383. }
  5384. } catch (err) {
  5385. showToast('Error', err.message, 'error');
  5386. }
  5387. }
  5388. async function togglePPPSecretState(id, disabled) {
  5389. try {
  5390. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  5391. method: 'POST',
  5392. headers: { 'Content-Type': 'application/json' },
  5393. body: JSON.stringify({ disabled })
  5394. });
  5395. if (res.ok) {
  5396. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  5397. loadPPPSecrets();
  5398. }
  5399. } catch (err) {
  5400. showToast('Error', err.message, 'error');
  5401. }
  5402. }
  5403. async function deletePPPSecret(id) {
  5404. if (!confirm('Are you sure you want to delete this secret account?')) return;
  5405. try {
  5406. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5407. if (res.ok) {
  5408. showToast('Deleted', 'Secret account removed', 'success');
  5409. loadPPPSecrets();
  5410. }
  5411. } catch (err) {
  5412. showToast('Error', err.message, 'error');
  5413. }
  5414. }
  5415. // PPP Profile Modal handlers
  5416. function openAddPPPProfileModal() {
  5417. document.getElementById('profile-modal-name').value = '';
  5418. document.getElementById('profile-modal-local').value = '10.10.10.1';
  5419. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  5420. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  5421. document.getElementById('profile-modal-encryption').value = 'required';
  5422. document.getElementById('profile-modal-onlyone').checked = true;
  5423. document.getElementById('profile-modal-comment').value = '';
  5424. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  5425. }
  5426. function closePPPProfileModal() {
  5427. document.getElementById('ppp-profile-modal').classList.add('hidden');
  5428. }
  5429. async function submitSavePPPProfile(e) {
  5430. e.preventDefault();
  5431. const name = document.getElementById('profile-modal-name').value.trim();
  5432. const local = document.getElementById('profile-modal-local').value.trim();
  5433. const remote = document.getElementById('profile-modal-remote').value.trim();
  5434. const dns = document.getElementById('profile-modal-dns').value.trim();
  5435. const enc = document.getElementById('profile-modal-encryption').value;
  5436. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  5437. const comment = document.getElementById('profile-modal-comment').value.trim();
  5438. try {
  5439. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  5440. method: 'POST',
  5441. headers: { 'Content-Type': 'application/json' },
  5442. body: JSON.stringify({
  5443. id: name,
  5444. name,
  5445. local_address: local,
  5446. remote_address: remote,
  5447. dns_servers: dns,
  5448. use_encryption: enc,
  5449. only_one: onlyone,
  5450. comment
  5451. })
  5452. });
  5453. if (res.ok) {
  5454. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  5455. closePPPProfileModal();
  5456. loadPPPProfiles();
  5457. } else {
  5458. const err = await res.json();
  5459. showToast('Error', err.message, 'error');
  5460. }
  5461. } catch (err) {
  5462. showToast('Error', err.message, 'error');
  5463. }
  5464. }
  5465. async function deletePPPProfile(name) {
  5466. if (!confirm(`Delete PPP profile ${name}?`)) return;
  5467. try {
  5468. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  5469. if (res.ok) {
  5470. showToast('Deleted', 'Profile removed', 'success');
  5471. loadPPPProfiles();
  5472. } else {
  5473. const err = await res.json();
  5474. showToast('Error', err.message, 'error');
  5475. }
  5476. } catch (err) {
  5477. showToast('Error', err.message, 'error');
  5478. }
  5479. }
  5480. // Server Config submissions
  5481. async function savePPPoEServerConfig(e) {
  5482. e.preventDefault();
  5483. const enabled = document.getElementById('pppoe-server-enabled').checked;
  5484. const name = document.getElementById('pppoe-server-name').value.trim();
  5485. const iface = document.getElementById('pppoe-server-iface').value;
  5486. const profile = document.getElementById('pppoe-server-profile').value;
  5487. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  5488. const onesession = document.getElementById('pppoe-server-onesession').checked;
  5489. try {
  5490. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  5491. method: 'POST',
  5492. headers: { 'Content-Type': 'application/json' },
  5493. body: JSON.stringify({
  5494. enabled,
  5495. service_name: name,
  5496. interface: iface,
  5497. default_profile: profile,
  5498. max_mtu: mtu,
  5499. max_mru: mtu,
  5500. one_session_per_host: onesession
  5501. })
  5502. });
  5503. if (res.ok) {
  5504. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  5505. loadPPPServers();
  5506. fetchData(false);
  5507. } else {
  5508. const err = await res.json();
  5509. showToast('Error', err.message, 'error');
  5510. }
  5511. } catch (err) {
  5512. showToast('Error', err.message, 'error');
  5513. }
  5514. }
  5515. async function savePPTPServerConfig(e) {
  5516. e.preventDefault();
  5517. const enabled = document.getElementById('pptp-server-enabled').checked;
  5518. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  5519. const profile = document.getElementById('pptp-server-profile').value;
  5520. const mppe = document.getElementById('pptp-server-mppe').checked;
  5521. try {
  5522. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  5523. method: 'POST',
  5524. headers: { 'Content-Type': 'application/json' },
  5525. body: JSON.stringify({
  5526. enabled,
  5527. port,
  5528. default_profile: profile,
  5529. require_mppe: mppe
  5530. })
  5531. });
  5532. if (res.ok) {
  5533. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  5534. loadPPPServers();
  5535. fetchData(false);
  5536. } else {
  5537. const err = await res.json();
  5538. showToast('Error', err.message, 'error');
  5539. }
  5540. } catch (err) {
  5541. showToast('Error', err.message, 'error');
  5542. }
  5543. }
  5544. async function saveL2TPServerConfig(e) {
  5545. e.preventDefault();
  5546. const enabled = document.getElementById('l2tp-server-enabled').checked;
  5547. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  5548. const profile = document.getElementById('l2tp-server-profile').value;
  5549. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  5550. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  5551. try {
  5552. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  5553. method: 'POST',
  5554. headers: { 'Content-Type': 'application/json' },
  5555. body: JSON.stringify({
  5556. enabled,
  5557. port,
  5558. default_profile: profile,
  5559. use_ipsec: useipsec,
  5560. ipsec_secret: psk
  5561. })
  5562. });
  5563. if (res.ok) {
  5564. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  5565. loadPPPServers();
  5566. fetchData(false);
  5567. } else {
  5568. const err = await res.json();
  5569. showToast('Error', err.message, 'error');
  5570. }
  5571. } catch (err) {
  5572. showToast('Error', err.message, 'error');
  5573. }
  5574. }
  5575. // IPSec Server Modal
  5576. function openIPSecServerModal() {
  5577. loadPPPServers();
  5578. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  5579. }
  5580. function closeIPSecServerModal() {
  5581. document.getElementById('ipsec-server-modal').classList.add('hidden');
  5582. }
  5583. async function submitSaveIPSecServer(e) {
  5584. e.preventDefault();
  5585. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  5586. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  5587. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  5588. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  5589. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  5590. try {
  5591. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  5592. method: 'POST',
  5593. headers: { 'Content-Type': 'application/json' },
  5594. body: JSON.stringify({
  5595. enabled,
  5596. preshared_key: psk,
  5597. pool_address: pool,
  5598. dns_servers: dns,
  5599. local_subnet: subnet
  5600. })
  5601. });
  5602. if (res.ok) {
  5603. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  5604. closeIPSecServerModal();
  5605. loadPPPServers();
  5606. fetchData(false);
  5607. } else {
  5608. const err = await res.json();
  5609. showToast('Error', err.message, 'error');
  5610. }
  5611. } catch (err) {
  5612. showToast('Error', err.message, 'error');
  5613. }
  5614. }
  5615. // WireGuard Client Config Viewer
  5616. let currentWGClientConf = '';
  5617. async function openWGClientConfModal(iface, clientIP) {
  5618. try {
  5619. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  5620. method: 'POST',
  5621. headers: { 'Content-Type': 'application/json' },
  5622. body: JSON.stringify({
  5623. interface: iface,
  5624. address: clientIP || '10.10.0.2/32',
  5625. dns: '1.1.1.1, 8.8.8.8'
  5626. })
  5627. });
  5628. if (res.ok) {
  5629. const data = await res.json();
  5630. currentWGClientConf = data.config;
  5631. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  5632. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  5633. } else {
  5634. const err = await res.json();
  5635. showToast('Error', err.message, 'error');
  5636. }
  5637. } catch (err) {
  5638. showToast('Error', err.message, 'error');
  5639. }
  5640. }
  5641. function closeWGClientConfModal() {
  5642. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  5643. }
  5644. function copyWGClientConf() {
  5645. if (!currentWGClientConf) return;
  5646. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  5647. }
  5648. function downloadWGClientConf() {
  5649. if (!currentWGClientConf) return;
  5650. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  5651. const a = document.createElement('a');
  5652. a.href = URL.createObjectURL(blob);
  5653. a.download = 'wireguard-client.conf';
  5654. document.body.appendChild(a);
  5655. a.click();
  5656. document.body.removeChild(a);
  5657. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  5658. }
  5659. // =========================================================================
  5660. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  5661. // =========================================================================
  5662. state.activeDynSubTab = 'bgp-peers';
  5663. state.activeBgpSubTab = 'bgp-peers';
  5664. state.activeOspfSubTab = 'ospf-ifaces';
  5665. state.bgpInstance = null;
  5666. state.bgpPeers = [];
  5667. state.bgpNets = [];
  5668. state.bgpRoutes = [];
  5669. state.ospfInstance = null;
  5670. state.ospfInterfaces = [];
  5671. state.ospfAreas = [];
  5672. state.ospfNeighbors = [];
  5673. state.ospfRoutes = [];
  5674. function switchBgpSubTab(subTab) {
  5675. state.activeBgpSubTab = subTab;
  5676. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  5677. tabs.forEach(t => {
  5678. const el = document.getElementById(`dyn-subtab-${t}`);
  5679. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  5680. if (el) el.classList.toggle('hidden', t !== subTab);
  5681. if (btn) {
  5682. if (t === subTab) {
  5683. 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';
  5684. } else {
  5685. 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';
  5686. }
  5687. }
  5688. });
  5689. }
  5690. function switchOspfSubTab(subTab) {
  5691. state.activeOspfSubTab = subTab;
  5692. const tabs = ['ospf-ifaces', 'ospf-areas', 'ospf-nbrs', 'ospf-routes'];
  5693. tabs.forEach(t => {
  5694. const el = document.getElementById(`dyn-subtab-${t}`);
  5695. const btn = document.getElementById(`ospf-subtab-btn-${t}`);
  5696. if (el) el.classList.toggle('hidden', t !== subTab);
  5697. if (btn) {
  5698. if (t === subTab) {
  5699. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-indigo-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  5700. } else {
  5701. 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';
  5702. }
  5703. }
  5704. });
  5705. }
  5706. function switchDynSubTab(subTab) {
  5707. if (subTab.startsWith('bgp')) {
  5708. if (state.activeTab !== 'bgp') navigate('bgp');
  5709. switchBgpSubTab(subTab);
  5710. } else if (subTab.startsWith('ospf')) {
  5711. if (state.activeTab !== 'ospf') navigate('ospf');
  5712. switchOspfSubTab(subTab);
  5713. }
  5714. }
  5715. async function loadDynamicRouting(showToastMsg = false) {
  5716. try {
  5717. const fetchSafeJson = async (url) => {
  5718. try {
  5719. const r = await fetch(url);
  5720. return r.ok ? await r.json() : null;
  5721. } catch (e) {
  5722. return null;
  5723. }
  5724. };
  5725. const [sum, bgpInst, bgpPeers, bgpNets, bgpRoutes, ospfInst, ospfIfaces, ospfAreas, ospfNbrs, ospfRoutes, filters] = await Promise.all([
  5726. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  5727. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  5728. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  5729. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  5730. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  5731. fetchSafeJson(`${API_BASE}/routing/ospf/instance`),
  5732. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces`),
  5733. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  5734. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  5735. fetchSafeJson(`${API_BASE}/routing/ospf/routes`),
  5736. fetchSafeJson(`${API_BASE}/routing/filters`)
  5737. ]);
  5738. if (sum) state.dynSummary = sum;
  5739. if (bgpInst) state.bgpInstance = bgpInst;
  5740. if (bgpPeers) state.bgpPeers = bgpPeers;
  5741. if (bgpNets) state.bgpNets = bgpNets;
  5742. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  5743. if (ospfInst) state.ospfInstance = ospfInst;
  5744. if (ospfIfaces) state.ospfInterfaces = ospfIfaces;
  5745. if (ospfAreas) state.ospfAreas = ospfAreas;
  5746. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  5747. if (ospfRoutes) state.ospfRoutes = ospfRoutes;
  5748. if (filters) state.routingFilters = filters;
  5749. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  5750. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  5751. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  5752. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  5753. try { renderOspfStatusPill(); } catch(e) { console.error('renderOspfStatusPill error:', e); }
  5754. try { renderOspfInterfaces(); } catch(e) { console.error('renderOspfInterfaces error:', e); }
  5755. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  5756. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  5757. try { renderOspfRoutes(); } catch(e) { console.error('renderOspfRoutes error:', e); }
  5758. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  5759. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  5760. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  5761. } catch (err) {
  5762. console.error('Failed to load dynamic routing:', err);
  5763. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  5764. }
  5765. }
  5766. function renderBgpStatusPill() {
  5767. const pill = document.getElementById('bgp-live-status-pill');
  5768. if (!pill) return;
  5769. const inst = state.bgpInstance;
  5770. if (!inst || !inst.enabled) {
  5771. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  5772. pill.innerText = 'BGP DISABLED';
  5773. } else if (inst.running) {
  5774. 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';
  5775. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  5776. } else {
  5777. 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';
  5778. pill.innerText = 'BGP STARTING...';
  5779. }
  5780. }
  5781. function renderBgpPeers() {
  5782. const tbody = document.getElementById('bgp-peers-table-body');
  5783. if (!tbody) return;
  5784. const empty = document.getElementById('bgp-peers-empty');
  5785. const countBadge = document.getElementById('bgp-peers-count-badge');
  5786. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  5787. const peers = state.bgpPeers || [];
  5788. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  5789. if (navBadge) navBadge.innerText = peers.length;
  5790. if (peers.length === 0) {
  5791. tbody.innerHTML = '';
  5792. if (empty) empty.classList.remove('hidden');
  5793. return;
  5794. }
  5795. if (empty) empty.classList.add('hidden');
  5796. tbody.innerHTML = peers.map(p => {
  5797. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  5798. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  5799. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  5800. let stateBadge = '';
  5801. if (p.disabled) {
  5802. 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>';
  5803. } else if (p.state === 'Established') {
  5804. 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>';
  5805. } else if (p.state === 'Connect' || p.state === 'Active') {
  5806. 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>`;
  5807. } else {
  5808. 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>`;
  5809. }
  5810. return `
  5811. <tr class="hover:bg-slate-800/40 transition">
  5812. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  5813. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  5814. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  5815. <td class="py-2.5 px-3 font-bold text-slate-200">AS ${p.remote_as}</td>
  5816. <td class="py-2.5 px-3">${stateBadge}</td>
  5817. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  5818. <td class="py-2.5 px-3 text-slate-300">
  5819. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  5820. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  5821. </td>
  5822. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  5823. ${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> ` : ''}
  5824. ${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>` : ''}
  5825. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  5826. </td>
  5827. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  5828. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  5829. <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'}">
  5830. ${p.disabled ? 'Enable' : 'Disable'}
  5831. </button>
  5832. <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">
  5833. Edit
  5834. </button>
  5835. <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">
  5836. Delete
  5837. </button>
  5838. </td>
  5839. </tr>
  5840. `;
  5841. }).join('');
  5842. }
  5843. function renderBgpNetworks() {
  5844. const tbody = document.getElementById('bgp-nets-table-body');
  5845. if (!tbody) return;
  5846. const empty = document.getElementById('bgp-nets-empty');
  5847. const countBadge = document.getElementById('bgp-nets-count-badge');
  5848. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  5849. const nets = state.bgpNets || [];
  5850. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  5851. if (navBadge) navBadge.innerText = nets.length;
  5852. if (nets.length === 0) {
  5853. tbody.innerHTML = '';
  5854. if (empty) empty.classList.remove('hidden');
  5855. return;
  5856. }
  5857. if (empty) empty.classList.add('hidden');
  5858. tbody.innerHTML = nets.map(n => `
  5859. <tr class="hover:bg-slate-800/40 transition">
  5860. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  5861. <td class="py-2.5 px-3">
  5862. ${n.disabled
  5863. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  5864. : '<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>'}
  5865. </td>
  5866. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  5867. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  5868. <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">
  5869. Delete
  5870. </button>
  5871. </td>
  5872. </tr>
  5873. `).join('');
  5874. }
  5875. function renderBgpRoutes() {
  5876. const tbody = document.getElementById('bgp-routes-table-body');
  5877. if (!tbody) return;
  5878. const empty = document.getElementById('bgp-routes-empty');
  5879. const countBadge = document.getElementById('bgp-routes-count-badge');
  5880. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  5881. const routes = state.bgpRoutes || [];
  5882. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  5883. if (navBadge) navBadge.innerText = routes.length;
  5884. if (routes.length === 0) {
  5885. tbody.innerHTML = '';
  5886. if (empty) empty.classList.remove('hidden');
  5887. return;
  5888. }
  5889. if (empty) empty.classList.add('hidden');
  5890. tbody.innerHTML = routes.map(r => `
  5891. <tr class="hover:bg-slate-800/40 transition">
  5892. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  5893. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  5894. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  5895. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  5896. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  5897. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  5898. </tr>
  5899. `).join('');
  5900. }
  5901. function renderOspfStatusPill() {
  5902. const pill = document.getElementById('ospf-live-status-pill');
  5903. if (!pill) return;
  5904. const inst = state.ospfInstance;
  5905. if (!inst || !inst.enabled) {
  5906. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  5907. pill.innerText = 'OSPF DISABLED';
  5908. } else if (inst.running) {
  5909. 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';
  5910. pill.innerText = `OSPF ACTIVE (ID: ${inst.router_id || 'Auto'})`;
  5911. } else {
  5912. 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';
  5913. pill.innerText = 'OSPF STARTING...';
  5914. }
  5915. }
  5916. function renderOspfInterfaces() {
  5917. const tbody = document.getElementById('ospf-ifaces-table-body');
  5918. if (!tbody) return;
  5919. const empty = document.getElementById('ospf-ifaces-empty');
  5920. const countBadge = document.getElementById('ospf-ifaces-count-badge');
  5921. const navBadge = document.getElementById('dyn-badge-ospf-ifaces');
  5922. const ifaces = state.ospfInterfaces || [];
  5923. if (countBadge) countBadge.innerText = `${ifaces.length} Interfaces`;
  5924. if (navBadge) navBadge.innerText = ifaces.length;
  5925. if (ifaces.length === 0) {
  5926. tbody.innerHTML = '';
  5927. if (empty) empty.classList.remove('hidden');
  5928. return;
  5929. }
  5930. if (empty) empty.classList.add('hidden');
  5931. tbody.innerHTML = ifaces.map(i => {
  5932. let flagA = !i.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  5933. let flagP = i.passive ? '<span class="text-amber-400 font-bold ml-1" title="Passive">P</span>' : '';
  5934. let flagX = i.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  5935. return `
  5936. <tr class="hover:bg-slate-800/40 transition">
  5937. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagP}${flagX}</td>
  5938. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(i.network)}</td>
  5939. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(i.area)}</td>
  5940. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(i.interface || 'Any')}</td>
  5941. <td class="py-2.5 px-3 text-slate-300">${i.cost}</td>
  5942. <td class="py-2.5 px-3 text-slate-300">${i.priority}</td>
  5943. <td class="py-2.5 px-3 text-slate-400">${i.hello_interval}s / ${i.dead_interval}s</td>
  5944. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(i.auth_type || 'none')}</td>
  5945. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(i.comment || '')}</td>
  5946. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  5947. <button onclick="toggleOspfInterfaceState('${i.id}', ${!i.disabled})" class="px-2 py-1 rounded text-[11px] ${i.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  5948. ${i.disabled ? 'Enable' : 'Disable'}
  5949. </button>
  5950. <button onclick="openEditOspfInterfaceModal('${i.id}')" class="px-2 py-1 rounded text-[11px] bg-slate-800 hover:bg-slate-700 text-indigo-300 border border-slate-700">
  5951. Edit
  5952. </button>
  5953. <button onclick="deleteOspfInterface('${i.id}')" class="px-2 py-1 rounded text-[11px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  5954. Delete
  5955. </button>
  5956. </td>
  5957. </tr>
  5958. `;
  5959. }).join('');
  5960. }
  5961. function renderOspfAreas() {
  5962. const tbody = document.getElementById('ospf-areas-table-body');
  5963. if (!tbody) return;
  5964. const countBadge = document.getElementById('ospf-areas-count-badge');
  5965. const navBadge = document.getElementById('dyn-badge-ospf-areas');
  5966. const areas = state.ospfAreas || [];
  5967. if (countBadge) countBadge.innerText = `${areas.length} Areas`;
  5968. if (navBadge) navBadge.innerText = areas.length;
  5969. tbody.innerHTML = areas.map(a => `
  5970. <tr class="hover:bg-slate-800/40 transition">
  5971. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(a.name)}</td>
  5972. <td class="py-2.5 px-3 font-bold text-indigo-300">${escapeHtml(a.area_id)}</td>
  5973. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(a.area_type || 'default')}</td>
  5974. <td class="py-2.5 px-3 text-slate-400 font-sans">${escapeHtml(a.comment || '')}</td>
  5975. <td class="py-2.5 px-3 text-right font-sans">
  5976. <button onclick="deleteOspfArea('${a.id}')" class="px-2 py-1 rounded text-[11px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  5977. Delete
  5978. </button>
  5979. </td>
  5980. </tr>
  5981. `).join('');
  5982. }
  5983. function renderOspfNeighbors() {
  5984. const tbody = document.getElementById('ospf-nbrs-table-body');
  5985. if (!tbody) return;
  5986. const empty = document.getElementById('ospf-nbrs-empty');
  5987. const countBadge = document.getElementById('ospf-nbrs-count-badge');
  5988. const navBadge = document.getElementById('dyn-badge-ospf-nbrs');
  5989. const nbrs = state.ospfNeighbors || [];
  5990. if (countBadge) countBadge.innerText = `${nbrs.length} Neighbors`;
  5991. if (navBadge) navBadge.innerText = nbrs.length;
  5992. if (nbrs.length === 0) {
  5993. tbody.innerHTML = '';
  5994. if (empty) empty.classList.remove('hidden');
  5995. return;
  5996. }
  5997. if (empty) empty.classList.add('hidden');
  5998. tbody.innerHTML = nbrs.map(n => {
  5999. let stateBadge = '';
  6000. if (n.state && (n.state.startsWith('Full') || n.state.includes('DR') || n.state.includes('Backup'))) {
  6001. stateBadge = `<span class="px-2 py-0.5 rounded-full text-[10px] font-sans font-medium bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">${escapeHtml(n.state)}</span>`;
  6002. } else {
  6003. stateBadge = `<span class="px-2 py-0.5 rounded-full text-[10px] font-sans font-medium bg-amber-500/10 text-amber-400 border border-amber-500/20">${escapeHtml(n.state || 'Unknown')}</span>`;
  6004. }
  6005. return `
  6006. <tr class="hover:bg-slate-800/40 transition">
  6007. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(n.neighbor_id)}</td>
  6008. <td class="py-2.5 px-3 text-indigo-300 font-bold">${escapeHtml(n.address)}</td>
  6009. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(n.interface)}</td>
  6010. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.area || '0.0.0.0')}</td>
  6011. <td class="py-2.5 px-3">${stateBadge}</td>
  6012. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.dead_timer || '-')}</td>
  6013. </tr>
  6014. `;
  6015. }).join('');
  6016. }
  6017. function renderOspfRoutes() {
  6018. const tbody = document.getElementById('ospf-routes-table-body');
  6019. if (!tbody) return;
  6020. const empty = document.getElementById('ospf-routes-empty');
  6021. const countBadge = document.getElementById('ospf-routes-count-badge');
  6022. const navBadge = document.getElementById('dyn-badge-ospf-routes');
  6023. const routes = state.ospfRoutes || [];
  6024. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  6025. if (navBadge) navBadge.innerText = routes.length;
  6026. if (routes.length === 0) {
  6027. tbody.innerHTML = '';
  6028. if (empty) empty.classList.remove('hidden');
  6029. return;
  6030. }
  6031. if (empty) empty.classList.add('hidden');
  6032. tbody.innerHTML = routes.map(r => `
  6033. <tr class="hover:bg-slate-800/40 transition">
  6034. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(r.prefix)}</td>
  6035. <td class="py-2.5 px-3 text-slate-300">${escapeHtml(r.route_type || 'Network')}</td>
  6036. <td class="py-2.5 px-3 text-slate-300">${r.cost}</td>
  6037. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(r.area || '0.0.0.0')}</td>
  6038. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(r.next_hop || r.interface || '-')}</td>
  6039. </tr>
  6040. `).join('');
  6041. }
  6042. // BGP Modals & Actions
  6043. function openBgpInstanceModal() {
  6044. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  6045. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  6046. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  6047. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  6048. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  6049. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  6050. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  6051. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  6052. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  6053. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  6054. }
  6055. function closeBgpInstanceModal() {
  6056. document.getElementById('bgp-instance-modal').classList.add('hidden');
  6057. }
  6058. async function submitBgpInstance(e) {
  6059. e.preventDefault();
  6060. const payload = {
  6061. enabled: document.getElementById('modal-bgp-enabled').checked,
  6062. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  6063. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  6064. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  6065. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  6066. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  6067. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  6068. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  6069. };
  6070. try {
  6071. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  6072. method: 'POST',
  6073. headers: { 'Content-Type': 'application/json' },
  6074. body: JSON.stringify(payload)
  6075. });
  6076. if (res.ok) {
  6077. closeBgpInstanceModal();
  6078. showToast('Success', 'BGP instance configuration updated', 'success');
  6079. loadDynamicRouting();
  6080. } else {
  6081. const err = await res.json();
  6082. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  6083. }
  6084. } catch (err) {
  6085. showToast('Error', err.message, 'error');
  6086. }
  6087. }
  6088. function openAddBgpPeerModal() {
  6089. document.getElementById('bgp-peer-form').reset();
  6090. document.getElementById('modal-bgp-peer-id').value = '';
  6091. document.getElementById('bgp-peer-modal-title').innerText = 'Add BGP Peer Connection';
  6092. document.getElementById('modal-bgp-peer-nexthop-self').checked = true;
  6093. const inFilterEl = document.getElementById('modal-bgp-peer-in-filter');
  6094. if (inFilterEl) inFilterEl.value = '';
  6095. const outFilterEl = document.getElementById('modal-bgp-peer-out-filter');
  6096. if (outFilterEl) outFilterEl.value = '';
  6097. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  6098. }
  6099. function openEditBgpPeerModal(id) {
  6100. const p = (state.bgpPeers || []).find(item => item.id === id);
  6101. if (!p) return;
  6102. document.getElementById('modal-bgp-peer-id').value = p.id;
  6103. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  6104. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  6105. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  6106. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  6107. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  6108. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  6109. document.getElementById('modal-bgp-peer-nexthop-self').checked = !!p.nexthop_self;
  6110. document.getElementById('modal-bgp-peer-passive').checked = !!p.passive;
  6111. document.getElementById('modal-bgp-peer-disabled').checked = !!p.disabled;
  6112. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  6113. const inFilterEl = document.getElementById('modal-bgp-peer-in-filter');
  6114. if (inFilterEl) inFilterEl.value = p.in_filter || '';
  6115. const outFilterEl = document.getElementById('modal-bgp-peer-out-filter');
  6116. if (outFilterEl) outFilterEl.value = p.out_filter || '';
  6117. document.getElementById('bgp-peer-modal-title').innerText = 'Edit BGP Peer Connection';
  6118. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  6119. }
  6120. function closeBgpPeerModal() {
  6121. document.getElementById('bgp-peer-modal').classList.add('hidden');
  6122. }
  6123. async function submitBgpPeer(e) {
  6124. e.preventDefault();
  6125. const payload = {
  6126. id: document.getElementById('modal-bgp-peer-id').value,
  6127. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  6128. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  6129. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10),
  6130. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  6131. password: document.getElementById('modal-bgp-peer-password').value,
  6132. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  6133. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-self').checked,
  6134. passive: document.getElementById('modal-bgp-peer-passive').checked,
  6135. disabled: document.getElementById('modal-bgp-peer-disabled').checked,
  6136. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  6137. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  6138. comment: document.getElementById('modal-bgp-peer-comment').value.trim()
  6139. };
  6140. try {
  6141. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  6142. method: 'POST',
  6143. headers: { 'Content-Type': 'application/json' },
  6144. body: JSON.stringify(payload)
  6145. });
  6146. if (res.ok) {
  6147. closeBgpPeerModal();
  6148. showToast('Success', 'BGP Peer saved', 'success');
  6149. loadDynamicRouting();
  6150. } else {
  6151. const err = await res.json();
  6152. showToast('Error', err.error || 'Failed to save peer', 'error');
  6153. }
  6154. } catch (err) {
  6155. showToast('Error', err.message, 'error');
  6156. }
  6157. }
  6158. async function deleteBgpPeer(id) {
  6159. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  6160. try {
  6161. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6162. if (res.ok) {
  6163. showToast('Deleted', 'BGP peer removed', 'success');
  6164. loadDynamicRouting();
  6165. }
  6166. } catch (err) {
  6167. showToast('Error', err.message, 'error');
  6168. }
  6169. }
  6170. async function toggleBgpPeerState(id, disabled) {
  6171. try {
  6172. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  6173. method: 'POST',
  6174. headers: { 'Content-Type': 'application/json' },
  6175. body: JSON.stringify({ disabled })
  6176. });
  6177. if (res.ok) {
  6178. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  6179. loadDynamicRouting();
  6180. }
  6181. } catch (err) {
  6182. showToast('Error', err.message, 'error');
  6183. }
  6184. }
  6185. function openAddBgpNetworkModal() {
  6186. document.getElementById('bgp-network-form').reset();
  6187. document.getElementById('modal-bgp-net-id').value = '';
  6188. document.getElementById('bgp-network-modal').classList.remove('hidden');
  6189. }
  6190. function closeBgpNetworkModal() {
  6191. document.getElementById('bgp-network-modal').classList.add('hidden');
  6192. }
  6193. async function submitBgpNetwork(e) {
  6194. e.preventDefault();
  6195. const payload = {
  6196. id: document.getElementById('modal-bgp-net-id').value,
  6197. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  6198. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  6199. disabled: document.getElementById('modal-bgp-net-disabled').checked
  6200. };
  6201. try {
  6202. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  6203. method: 'POST',
  6204. headers: { 'Content-Type': 'application/json' },
  6205. body: JSON.stringify(payload)
  6206. });
  6207. if (res.ok) {
  6208. closeBgpNetworkModal();
  6209. showToast('Success', 'BGP network advertisement saved', 'success');
  6210. loadDynamicRouting();
  6211. } else {
  6212. const err = await res.json();
  6213. showToast('Error', err.error || 'Failed to save network', 'error');
  6214. }
  6215. } catch (err) {
  6216. showToast('Error', err.message, 'error');
  6217. }
  6218. }
  6219. async function deleteBgpNetwork(id) {
  6220. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  6221. try {
  6222. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6223. if (res.ok) {
  6224. showToast('Deleted', 'Network advertisement removed', 'success');
  6225. loadDynamicRouting();
  6226. }
  6227. } catch (err) {
  6228. showToast('Error', err.message, 'error');
  6229. }
  6230. }
  6231. // OSPF Modals & Actions
  6232. function openOspfInstanceModal() {
  6233. const inst = state.ospfInstance || { enabled: false, router_id: '192.168.131.56', default_metric: 10 };
  6234. document.getElementById('modal-ospf-enabled').checked = !!inst.enabled;
  6235. document.getElementById('modal-ospf-router-id').value = inst.router_id || '';
  6236. document.getElementById('modal-ospf-metric').value = inst.default_metric || 10;
  6237. document.getElementById('modal-ospf-redist-conn').checked = !!inst.redistribute_connected;
  6238. document.getElementById('modal-ospf-redist-static').checked = !!inst.redistribute_static;
  6239. document.getElementById('modal-ospf-redist-bgp').checked = !!inst.redistribute_bgp;
  6240. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  6241. }
  6242. function closeOspfInstanceModal() {
  6243. document.getElementById('ospf-instance-modal').classList.add('hidden');
  6244. }
  6245. async function submitOspfInstance(e) {
  6246. e.preventDefault();
  6247. const payload = {
  6248. enabled: document.getElementById('modal-ospf-enabled').checked,
  6249. router_id: document.getElementById('modal-ospf-router-id').value.trim(),
  6250. default_metric: parseInt(document.getElementById('modal-ospf-metric').value, 10),
  6251. redistribute_connected: document.getElementById('modal-ospf-redist-conn').checked,
  6252. redistribute_static: document.getElementById('modal-ospf-redist-static').checked,
  6253. redistribute_bgp: document.getElementById('modal-ospf-redist-bgp').checked
  6254. };
  6255. try {
  6256. const res = await fetch(`${API_BASE}/routing/ospf/instance`, {
  6257. method: 'POST',
  6258. headers: { 'Content-Type': 'application/json' },
  6259. body: JSON.stringify(payload)
  6260. });
  6261. if (res.ok) {
  6262. closeOspfInstanceModal();
  6263. showToast('Success', 'OSPF instance configuration updated', 'success');
  6264. loadDynamicRouting();
  6265. } else {
  6266. const err = await res.json();
  6267. showToast('Error', err.error || 'Failed to update OSPF instance', 'error');
  6268. }
  6269. } catch (err) {
  6270. showToast('Error', err.message, 'error');
  6271. }
  6272. }
  6273. function openAddOspfAreaModal() {
  6274. document.getElementById('ospf-area-form').reset();
  6275. document.getElementById('modal-ospf-area-id').value = '';
  6276. document.getElementById('modal-ospf-area-areaid').value = '0.0.0.0';
  6277. document.getElementById('ospf-area-modal').classList.remove('hidden');
  6278. }
  6279. function closeOspfAreaModal() {
  6280. document.getElementById('ospf-area-modal').classList.add('hidden');
  6281. }
  6282. async function submitOspfArea(e) {
  6283. e.preventDefault();
  6284. const payload = {
  6285. id: document.getElementById('modal-ospf-area-id').value,
  6286. name: document.getElementById('modal-ospf-area-name').value.trim(),
  6287. area_id: document.getElementById('modal-ospf-area-areaid').value.trim(),
  6288. area_type: document.getElementById('modal-ospf-area-type').value,
  6289. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  6290. };
  6291. try {
  6292. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  6293. method: 'POST',
  6294. headers: { 'Content-Type': 'application/json' },
  6295. body: JSON.stringify(payload)
  6296. });
  6297. if (res.ok) {
  6298. closeOspfAreaModal();
  6299. showToast('Success', 'OSPF area saved', 'success');
  6300. loadDynamicRouting();
  6301. } else {
  6302. const err = await res.json();
  6303. showToast('Error', err.error || 'Failed to save area', 'error');
  6304. }
  6305. } catch (err) {
  6306. showToast('Error', err.message, 'error');
  6307. }
  6308. }
  6309. async function deleteOspfArea(id) {
  6310. if (!confirm('Are you sure you want to delete this OSPF area?')) return;
  6311. try {
  6312. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6313. if (res.ok) {
  6314. showToast('Deleted', 'OSPF area removed', 'success');
  6315. loadDynamicRouting();
  6316. }
  6317. } catch (err) {
  6318. showToast('Error', err.message, 'error');
  6319. }
  6320. }
  6321. function populateOspfInterfaceDevices() {
  6322. const select = document.getElementById('modal-ospf-iface-device');
  6323. if (!select) return;
  6324. const current = select.value;
  6325. select.innerHTML = '<option value="">Any matching interface</option>';
  6326. (state.interfaces || []).forEach(iface => {
  6327. select.innerHTML += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)} (${iface.type})</option>`;
  6328. });
  6329. if (current) select.value = current;
  6330. }
  6331. function openAddOspfInterfaceModal() {
  6332. document.getElementById('ospf-interface-form').reset();
  6333. document.getElementById('modal-ospf-iface-id').value = '';
  6334. document.getElementById('modal-ospf-iface-area').value = '0.0.0.0';
  6335. document.getElementById('modal-ospf-iface-cost').value = '10';
  6336. document.getElementById('modal-ospf-iface-priority').value = '1';
  6337. document.getElementById('modal-ospf-iface-hello').value = '10';
  6338. document.getElementById('modal-ospf-iface-dead').value = '40';
  6339. document.getElementById('ospf-interface-modal-title').innerText = 'Add OSPF Interface';
  6340. populateOspfInterfaceDevices();
  6341. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  6342. }
  6343. function openEditOspfInterfaceModal(id) {
  6344. const item = (state.ospfInterfaces || []).find(i => i.id === id);
  6345. if (!item) return;
  6346. populateOspfInterfaceDevices();
  6347. document.getElementById('modal-ospf-iface-id').value = item.id;
  6348. document.getElementById('modal-ospf-iface-net').value = item.network || '';
  6349. document.getElementById('modal-ospf-iface-area').value = item.area || '0.0.0.0';
  6350. document.getElementById('modal-ospf-iface-device').value = item.interface || '';
  6351. document.getElementById('modal-ospf-iface-cost').value = item.cost || 10;
  6352. document.getElementById('modal-ospf-iface-priority').value = item.priority || 1;
  6353. document.getElementById('modal-ospf-iface-hello').value = item.hello_interval || 10;
  6354. document.getElementById('modal-ospf-iface-dead').value = item.dead_interval || 40;
  6355. document.getElementById('modal-ospf-iface-auth-type').value = item.auth_type || 'none';
  6356. document.getElementById('modal-ospf-iface-auth-key').value = item.auth_key || '';
  6357. document.getElementById('modal-ospf-iface-passive').checked = !!item.passive;
  6358. document.getElementById('modal-ospf-iface-disabled').checked = !!item.disabled;
  6359. document.getElementById('modal-ospf-iface-comment').value = item.comment || '';
  6360. document.getElementById('ospf-interface-modal-title').innerText = 'Edit OSPF Interface';
  6361. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  6362. }
  6363. function closeOspfInterfaceModal() {
  6364. document.getElementById('ospf-interface-modal').classList.add('hidden');
  6365. }
  6366. async function submitOspfInterface(e) {
  6367. e.preventDefault();
  6368. const payload = {
  6369. id: document.getElementById('modal-ospf-iface-id').value,
  6370. network: document.getElementById('modal-ospf-iface-net').value.trim(),
  6371. area: document.getElementById('modal-ospf-iface-area').value.trim(),
  6372. interface: document.getElementById('modal-ospf-iface-device').value,
  6373. cost: parseInt(document.getElementById('modal-ospf-iface-cost').value, 10),
  6374. priority: parseInt(document.getElementById('modal-ospf-iface-priority').value, 10),
  6375. hello_interval: parseInt(document.getElementById('modal-ospf-iface-hello').value, 10),
  6376. dead_interval: parseInt(document.getElementById('modal-ospf-iface-dead').value, 10),
  6377. auth_type: document.getElementById('modal-ospf-iface-auth-type').value,
  6378. auth_key: document.getElementById('modal-ospf-iface-auth-key').value,
  6379. passive: document.getElementById('modal-ospf-iface-passive').checked,
  6380. disabled: document.getElementById('modal-ospf-iface-disabled').checked,
  6381. comment: document.getElementById('modal-ospf-iface-comment').value.trim()
  6382. };
  6383. try {
  6384. const res = await fetch(`${API_BASE}/routing/ospf/interfaces`, {
  6385. method: 'POST',
  6386. headers: { 'Content-Type': 'application/json' },
  6387. body: JSON.stringify(payload)
  6388. });
  6389. if (res.ok) {
  6390. closeOspfInterfaceModal();
  6391. showToast('Success', 'OSPF interface template saved', 'success');
  6392. loadDynamicRouting();
  6393. } else {
  6394. const err = await res.json();
  6395. showToast('Error', err.error || 'Failed to save interface', 'error');
  6396. }
  6397. } catch (err) {
  6398. showToast('Error', err.message, 'error');
  6399. }
  6400. }
  6401. async function deleteOspfInterface(id) {
  6402. if (!confirm('Are you sure you want to delete this OSPF interface?')) return;
  6403. try {
  6404. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6405. if (res.ok) {
  6406. showToast('Deleted', 'OSPF interface removed', 'success');
  6407. loadDynamicRouting();
  6408. }
  6409. } catch (err) {
  6410. showToast('Error', err.message, 'error');
  6411. }
  6412. }
  6413. async function toggleOspfInterfaceState(id, disabled) {
  6414. try {
  6415. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}/state`, {
  6416. method: 'POST',
  6417. headers: { 'Content-Type': 'application/json' },
  6418. body: JSON.stringify({ disabled })
  6419. });
  6420. if (res.ok) {
  6421. showToast('Updated', `Interface ${disabled ? 'disabled' : 'enabled'}`, 'success');
  6422. loadDynamicRouting();
  6423. }
  6424. } catch (err) {
  6425. showToast('Error', err.message, 'error');
  6426. }
  6427. }
  6428. // ============================================================================
  6429. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  6430. // ============================================================================
  6431. function switchBridgeSubTab(tab) {
  6432. state.bridgeSubTab = tab;
  6433. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  6434. tabs.forEach(t => {
  6435. const panel = document.getElementById(`bridge-subtab-${t}`);
  6436. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  6437. if (panel) {
  6438. if (t === tab) panel.classList.remove('hidden');
  6439. else panel.classList.add('hidden');
  6440. }
  6441. if (btn) {
  6442. if (t === tab) {
  6443. 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';
  6444. } else {
  6445. 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';
  6446. }
  6447. }
  6448. });
  6449. const addBtn = document.getElementById('bridge-top-action-btn');
  6450. if (addBtn) {
  6451. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  6452. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  6453. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  6454. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  6455. }
  6456. if (tab === 'hosts') loadBridgeHosts();
  6457. }
  6458. function openCurrentBridgeModal() {
  6459. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  6460. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  6461. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  6462. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  6463. }
  6464. async function loadBridge() {
  6465. try {
  6466. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  6467. fetch(`${API_BASE}/bridge/bridges`),
  6468. fetch(`${API_BASE}/bridge/ports`),
  6469. fetch(`${API_BASE}/bridge/vlans`),
  6470. fetch(`${API_BASE}/bridge/summary`),
  6471. fetch(`${API_BASE}/vpn/eoip`),
  6472. fetch(`${API_BASE}/vlans`)
  6473. ]);
  6474. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  6475. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  6476. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  6477. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  6478. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  6479. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  6480. // Badges & Stats
  6481. const bBridges = document.getElementById('bridge-badge-bridges');
  6482. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  6483. const bPorts = document.getElementById('bridge-badge-ports');
  6484. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  6485. const bVlans = document.getElementById('bridge-badge-vlans');
  6486. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  6487. const bHosts = document.getElementById('bridge-badge-hosts');
  6488. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  6489. const sBr = document.getElementById('bridge-stat-bridges');
  6490. if (sBr) sBr.innerText = (state.bridges || []).length;
  6491. const sPorts = document.getElementById('bridge-stat-ports');
  6492. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  6493. const sHosts = document.getElementById('bridge-stat-hosts');
  6494. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  6495. renderBridges();
  6496. renderBridgePorts();
  6497. renderBridgeVLANs();
  6498. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  6499. } catch (err) {
  6500. console.error('Failed to load bridge subsystem:', err);
  6501. }
  6502. }
  6503. // ----------------- Bridges -----------------
  6504. function renderBridges() {
  6505. const tbody = document.getElementById('bridge-table-body');
  6506. const empty = document.getElementById('bridge-empty-bridges');
  6507. const countBadge = document.getElementById('bridge-count-badge');
  6508. if (!tbody) return;
  6509. tbody.innerHTML = '';
  6510. const bridges = state.bridges || [];
  6511. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  6512. if (bridges.length === 0) {
  6513. empty?.classList.remove('hidden');
  6514. return;
  6515. }
  6516. empty?.classList.add('hidden');
  6517. bridges.forEach((b, idx) => {
  6518. const tr = document.createElement('tr');
  6519. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  6520. // Format IP addresses pill list
  6521. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  6522. if (b.ip_addresses && b.ip_addresses.length > 0) {
  6523. ipsHtml = b.ip_addresses.map(ip => `
  6524. <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">
  6525. <span>${ip}</span>
  6526. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  6527. </span>
  6528. `).join(' ');
  6529. }
  6530. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  6531. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  6532. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  6533. tr.innerHTML = `
  6534. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  6535. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  6536. <td class="py-2.5 px-3 font-bold text-white text-sm">
  6537. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  6538. </td>
  6539. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  6540. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  6541. <td class="py-2.5 px-3">
  6542. <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>
  6543. </td>
  6544. <td class="py-2.5 px-3 text-center">
  6545. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  6546. </td>
  6547. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  6548. <td class="py-2.5 px-3">
  6549. <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>
  6550. </td>
  6551. <td class="py-2.5 px-3">
  6552. <div class="flex items-center gap-1.5 flex-wrap">
  6553. ${ipsHtml}
  6554. <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>
  6555. </div>
  6556. </td>
  6557. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  6558. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  6559. </td>
  6560. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  6561. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6562. <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>
  6563. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6564. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6565. </td>
  6566. `;
  6567. tbody.appendChild(tr);
  6568. });
  6569. }
  6570. function openAddBridgeModal() {
  6571. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  6572. document.getElementById('bridge-modal-id').value = '';
  6573. document.getElementById('bridge-modal-name').value = 'bridge1';
  6574. document.getElementById('bridge-modal-name').disabled = false;
  6575. document.getElementById('bridge-modal-mtu').value = '1500';
  6576. document.getElementById('bridge-modal-mac').value = '';
  6577. document.getElementById('bridge-modal-stp').value = 'rstp';
  6578. document.getElementById('bridge-modal-priority').value = '32768';
  6579. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  6580. document.getElementById('bridge-modal-pvid').value = '1';
  6581. document.getElementById('bridge-modal-fastforward').checked = true;
  6582. document.getElementById('bridge-modal-comment').value = '';
  6583. document.getElementById('bridge-modal-disabled').checked = false;
  6584. toggleBridgeModalVlanFiltering();
  6585. document.getElementById('bridge-modal').classList.remove('hidden');
  6586. }
  6587. function openEditBridgeModal(id) {
  6588. const b = (state.bridges || []).find(x => x.id === id);
  6589. if (!b) return;
  6590. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  6591. document.getElementById('bridge-modal-id').value = b.id;
  6592. document.getElementById('bridge-modal-name').value = b.name;
  6593. document.getElementById('bridge-modal-name').disabled = true;
  6594. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  6595. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  6596. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  6597. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  6598. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  6599. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  6600. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  6601. document.getElementById('bridge-modal-comment').value = b.comment || '';
  6602. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  6603. toggleBridgeModalVlanFiltering();
  6604. document.getElementById('bridge-modal').classList.remove('hidden');
  6605. }
  6606. function closeBridgeModal() {
  6607. document.getElementById('bridge-modal').classList.add('hidden');
  6608. }
  6609. function toggleBridgeModalVlanFiltering() {
  6610. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  6611. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  6612. if (pvidBox) {
  6613. if (chk) pvidBox.classList.remove('opacity-40');
  6614. else pvidBox.classList.add('opacity-40');
  6615. }
  6616. }
  6617. async function submitSaveBridge(e) {
  6618. e.preventDefault();
  6619. const id = document.getElementById('bridge-modal-id').value;
  6620. const name = document.getElementById('bridge-modal-name').value.trim();
  6621. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  6622. const mac = document.getElementById('bridge-modal-mac').value.trim();
  6623. const stp = document.getElementById('bridge-modal-stp').value;
  6624. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  6625. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  6626. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  6627. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  6628. const comment = document.getElementById('bridge-modal-comment').value.trim();
  6629. const disabled = document.getElementById('bridge-modal-disabled').checked;
  6630. try {
  6631. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  6632. method: 'POST',
  6633. headers: { 'Content-Type': 'application/json' },
  6634. body: JSON.stringify({
  6635. id,
  6636. name,
  6637. mtu,
  6638. mac_address: mac,
  6639. stp,
  6640. priority,
  6641. vlan_filtering: vlanFiltering,
  6642. pvid,
  6643. fast_forward: fastForward,
  6644. comment,
  6645. disabled
  6646. })
  6647. });
  6648. if (res.ok) {
  6649. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  6650. closeBridgeModal();
  6651. loadBridge();
  6652. fetchData(false);
  6653. } else {
  6654. const err = await res.json();
  6655. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  6656. }
  6657. } catch (err) {
  6658. showToast('Error', err.message, 'error');
  6659. }
  6660. }
  6661. async function toggleBridgeState(id, disabled) {
  6662. try {
  6663. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  6664. method: 'POST',
  6665. headers: { 'Content-Type': 'application/json' },
  6666. body: JSON.stringify({ disabled })
  6667. });
  6668. if (res.ok) {
  6669. loadBridge();
  6670. fetchData(false);
  6671. }
  6672. } catch (err) {
  6673. showToast('Error', err.message, 'error');
  6674. }
  6675. }
  6676. async function deleteBridge(id) {
  6677. const b = (state.bridges || []).find(x => x.id === id);
  6678. const name = b ? b.name : id;
  6679. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  6680. try {
  6681. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6682. if (res.ok) {
  6683. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  6684. loadBridge();
  6685. fetchData(false);
  6686. } else {
  6687. const err = await res.json();
  6688. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  6689. }
  6690. } catch (err) {
  6691. showToast('Error', err.message, 'error');
  6692. }
  6693. }
  6694. // ----------------- Bridge IP Assignments -----------------
  6695. function openAddBridgeIPModal(id, name) {
  6696. document.getElementById('bridge-ip-modal-id').value = id;
  6697. document.getElementById('bridge-ip-modal-sub').innerText = name;
  6698. document.getElementById('bridge-ip-modal-cidr').value = '';
  6699. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  6700. }
  6701. function closeBridgeIPModal() {
  6702. document.getElementById('bridge-ip-modal').classList.add('hidden');
  6703. }
  6704. async function submitAddBridgeIP(e) {
  6705. e.preventDefault();
  6706. const id = document.getElementById('bridge-ip-modal-id').value;
  6707. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  6708. try {
  6709. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  6710. method: 'POST',
  6711. headers: { 'Content-Type': 'application/json' },
  6712. body: JSON.stringify({ ip })
  6713. });
  6714. if (res.ok) {
  6715. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  6716. closeBridgeIPModal();
  6717. loadBridge();
  6718. fetchData(false);
  6719. } else {
  6720. const err = await res.json();
  6721. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  6722. }
  6723. } catch (err) {
  6724. showToast('Error', err.message, 'error');
  6725. }
  6726. }
  6727. async function deleteBridgeIP(id, ip) {
  6728. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  6729. try {
  6730. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  6731. method: 'DELETE',
  6732. headers: { 'Content-Type': 'application/json' },
  6733. body: JSON.stringify({ ip })
  6734. });
  6735. if (res.ok) {
  6736. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  6737. loadBridge();
  6738. fetchData(false);
  6739. }
  6740. } catch (err) {
  6741. showToast('Error', err.message, 'error');
  6742. }
  6743. }
  6744. // ----------------- Bridge Ports -----------------
  6745. function renderBridgePorts() {
  6746. const tbody = document.getElementById('bridge-ports-table-body');
  6747. const empty = document.getElementById('bridge-empty-ports');
  6748. const countBadge = document.getElementById('bridge-ports-count-badge');
  6749. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  6750. if (!tbody) return;
  6751. tbody.innerHTML = '';
  6752. // Update filter select
  6753. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  6754. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  6755. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  6756. if (ports.length === 0) {
  6757. empty?.classList.remove('hidden');
  6758. return;
  6759. }
  6760. empty?.classList.add('hidden');
  6761. ports.forEach((p, idx) => {
  6762. const tr = document.createElement('tr');
  6763. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  6764. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  6765. tr.innerHTML = `
  6766. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  6767. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  6768. <td class="py-2.5 px-3 font-bold text-white text-sm">
  6769. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  6770. </td>
  6771. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  6772. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  6773. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  6774. <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>
  6775. <td class="py-2.5 px-3">
  6776. ${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>'}
  6777. </td>
  6778. <td class="py-2.5 px-3">
  6779. <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>
  6780. </td>
  6781. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  6782. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6783. <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>
  6784. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6785. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6786. </td>
  6787. `;
  6788. tbody.appendChild(tr);
  6789. });
  6790. }
  6791. function openAddBridgePortModal() {
  6792. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  6793. document.getElementById('bridge-port-modal-id').value = '';
  6794. populateBridgeSelect('bridge-port-modal-bridge');
  6795. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  6796. document.getElementById('bridge-port-modal-pvid').value = '1';
  6797. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  6798. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  6799. document.getElementById('bridge-port-modal-horizon').value = '0';
  6800. document.getElementById('bridge-port-modal-pathcost').value = '10';
  6801. document.getElementById('bridge-port-modal-priority').value = '128';
  6802. document.getElementById('bridge-port-modal-learn').checked = true;
  6803. document.getElementById('bridge-port-modal-comment').value = '';
  6804. document.getElementById('bridge-port-modal-disabled').checked = false;
  6805. document.getElementById('bridge-port-modal').classList.remove('hidden');
  6806. }
  6807. function openEditBridgePortModal(id) {
  6808. const p = (state.bridgePorts || []).find(x => x.id === id);
  6809. if (!p) return;
  6810. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  6811. document.getElementById('bridge-port-modal-id').value = p.id;
  6812. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  6813. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  6814. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  6815. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  6816. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  6817. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  6818. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  6819. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  6820. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  6821. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  6822. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  6823. document.getElementById('bridge-port-modal').classList.remove('hidden');
  6824. }
  6825. function closeBridgePortModal() {
  6826. document.getElementById('bridge-port-modal').classList.add('hidden');
  6827. }
  6828. async function submitSaveBridgePort(e) {
  6829. e.preventDefault();
  6830. const id = document.getElementById('bridge-port-modal-id').value;
  6831. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  6832. const iface = document.getElementById('bridge-port-modal-interface').value;
  6833. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  6834. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  6835. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  6836. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  6837. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  6838. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  6839. const learn = document.getElementById('bridge-port-modal-learn').checked;
  6840. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  6841. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  6842. try {
  6843. const res = await fetch(`${API_BASE}/bridge/ports`, {
  6844. method: 'POST',
  6845. headers: { 'Content-Type': 'application/json' },
  6846. body: JSON.stringify({
  6847. id,
  6848. bridge,
  6849. interface: iface,
  6850. pvid,
  6851. frame_types: frameTypes,
  6852. ingress_filtering: ingressFiltering,
  6853. horizon,
  6854. path_cost: pathCost,
  6855. priority,
  6856. learn,
  6857. comment,
  6858. disabled
  6859. })
  6860. });
  6861. if (res.ok) {
  6862. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  6863. closeBridgePortModal();
  6864. loadBridge();
  6865. fetchData(false);
  6866. } else {
  6867. const err = await res.json();
  6868. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  6869. }
  6870. } catch (err) {
  6871. showToast('Error', err.message, 'error');
  6872. }
  6873. }
  6874. async function toggleBridgePortState(id, disabled) {
  6875. try {
  6876. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  6877. method: 'POST',
  6878. headers: { 'Content-Type': 'application/json' },
  6879. body: JSON.stringify({ disabled })
  6880. });
  6881. if (res.ok) {
  6882. loadBridge();
  6883. fetchData(false);
  6884. }
  6885. } catch (err) {
  6886. showToast('Error', err.message, 'error');
  6887. }
  6888. }
  6889. async function deleteBridgePort(id) {
  6890. const p = (state.bridgePorts || []).find(x => x.id === id);
  6891. const iface = p ? p.interface : id;
  6892. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  6893. try {
  6894. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6895. if (res.ok) {
  6896. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  6897. loadBridge();
  6898. fetchData(false);
  6899. }
  6900. } catch (err) {
  6901. showToast('Error', err.message, 'error');
  6902. }
  6903. }
  6904. // ----------------- Bridge VLANs -----------------
  6905. function renderBridgeVLANs() {
  6906. const tbody = document.getElementById('bridge-vlans-table-body');
  6907. const empty = document.getElementById('bridge-empty-vlans');
  6908. const countBadge = document.getElementById('bridge-vlans-count-badge');
  6909. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  6910. if (!tbody) return;
  6911. tbody.innerHTML = '';
  6912. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  6913. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  6914. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  6915. if (vlans.length === 0) {
  6916. empty?.classList.remove('hidden');
  6917. return;
  6918. }
  6919. empty?.classList.add('hidden');
  6920. vlans.forEach((v, idx) => {
  6921. const tr = document.createElement('tr');
  6922. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  6923. const taggedHtml = (v.tagged && v.tagged.length > 0)
  6924. ? 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(' ')
  6925. : '<span class="text-slate-600">none</span>';
  6926. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  6927. ? 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(' ')
  6928. : '<span class="text-slate-600">none</span>';
  6929. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  6930. tr.innerHTML = `
  6931. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  6932. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  6933. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  6934. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  6935. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  6936. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  6937. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  6938. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6939. <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>
  6940. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6941. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6942. </td>
  6943. `;
  6944. tbody.appendChild(tr);
  6945. });
  6946. }
  6947. function openAddBridgeVLANModal() {
  6948. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  6949. document.getElementById('bridge-vlan-modal-id').value = '';
  6950. populateBridgeSelect('bridge-vlan-modal-bridge');
  6951. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  6952. document.getElementById('bridge-vlan-modal-comment').value = '';
  6953. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  6954. updateBridgeVlanPortCheckboxes();
  6955. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  6956. }
  6957. function openEditBridgeVLANModal(id) {
  6958. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  6959. if (!v) return;
  6960. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  6961. document.getElementById('bridge-vlan-modal-id').value = v.id;
  6962. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  6963. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  6964. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  6965. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  6966. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  6967. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  6968. }
  6969. function closeBridgeVlanModal() {
  6970. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  6971. }
  6972. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  6973. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  6974. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  6975. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  6976. if (!taggedBox || !untaggedBox) return;
  6977. // Ports belonging to the selected bridge
  6978. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  6979. if (memberPorts.length === 0) {
  6980. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  6981. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  6982. return;
  6983. }
  6984. taggedBox.innerHTML = memberPorts.map(p => `
  6985. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  6986. <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">
  6987. <span>${p.interface}</span>
  6988. </label>
  6989. `).join('');
  6990. untaggedBox.innerHTML = memberPorts.map(p => `
  6991. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  6992. <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">
  6993. <span>${p.interface}</span>
  6994. </label>
  6995. `).join('');
  6996. }
  6997. async function submitSaveBridgeVLAN(e) {
  6998. e.preventDefault();
  6999. const id = document.getElementById('bridge-vlan-modal-id').value;
  7000. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  7001. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  7002. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  7003. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  7004. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  7005. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  7006. try {
  7007. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  7008. method: 'POST',
  7009. headers: { 'Content-Type': 'application/json' },
  7010. body: JSON.stringify({
  7011. id,
  7012. bridge,
  7013. vlan_ids: vlanIDs,
  7014. tagged,
  7015. untagged,
  7016. comment,
  7017. disabled
  7018. })
  7019. });
  7020. if (res.ok) {
  7021. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  7022. closeBridgeVlanModal();
  7023. loadBridge();
  7024. } else {
  7025. const err = await res.json();
  7026. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  7027. }
  7028. } catch (err) {
  7029. showToast('Error', err.message, 'error');
  7030. }
  7031. }
  7032. async function toggleBridgeVLANState(id, disabled) {
  7033. try {
  7034. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  7035. method: 'POST',
  7036. headers: { 'Content-Type': 'application/json' },
  7037. body: JSON.stringify({ disabled })
  7038. });
  7039. if (res.ok) loadBridge();
  7040. } catch (err) {
  7041. showToast('Error', err.message, 'error');
  7042. }
  7043. }
  7044. async function deleteBridgeVLAN(id) {
  7045. if (!confirm('Delete this bridge VLAN entry?')) return;
  7046. try {
  7047. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7048. if (res.ok) {
  7049. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  7050. loadBridge();
  7051. }
  7052. } catch (err) {
  7053. showToast('Error', err.message, 'error');
  7054. }
  7055. }
  7056. // ----------------- Hosts / MAC Table -----------------
  7057. async function loadBridgeHosts() {
  7058. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  7059. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  7060. try {
  7061. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  7062. const res = await fetch(url);
  7063. if (res.ok) {
  7064. state.bridgeHosts = await res.json();
  7065. renderBridgeHosts();
  7066. }
  7067. } catch (err) {
  7068. console.error('Failed to load bridge hosts:', err);
  7069. }
  7070. }
  7071. function renderBridgeHosts() {
  7072. const tbody = document.getElementById('bridge-hosts-table-body');
  7073. const empty = document.getElementById('bridge-empty-hosts');
  7074. const countBadge = document.getElementById('bridge-hosts-count-badge');
  7075. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  7076. if (!tbody) return;
  7077. tbody.innerHTML = '';
  7078. const hosts = (state.bridgeHosts || []).filter(h => {
  7079. if (!search) return true;
  7080. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  7081. });
  7082. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  7083. if (hosts.length === 0) {
  7084. empty?.classList.remove('hidden');
  7085. return;
  7086. }
  7087. empty?.classList.add('hidden');
  7088. hosts.forEach(h => {
  7089. const tr = document.createElement('tr');
  7090. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  7091. let flagBadges = '';
  7092. 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>';
  7093. 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>';
  7094. 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>';
  7095. tr.innerHTML = `
  7096. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  7097. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  7098. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  7099. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  7100. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  7101. <td class="py-2.5 px-3">${flagBadges}</td>
  7102. `;
  7103. tbody.appendChild(tr);
  7104. });
  7105. }
  7106. async function flushBridgeHosts() {
  7107. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  7108. if (!selBridge) {
  7109. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  7110. return;
  7111. }
  7112. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  7113. try {
  7114. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  7115. method: 'POST',
  7116. headers: { 'Content-Type': 'application/json' },
  7117. body: JSON.stringify({ bridge: selBridge })
  7118. });
  7119. if (res.ok) {
  7120. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  7121. loadBridgeHosts();
  7122. }
  7123. } catch (err) {
  7124. showToast('Error', err.message, 'error');
  7125. }
  7126. }
  7127. // ----------------- Helpers -----------------
  7128. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  7129. const sel = document.getElementById(selectId);
  7130. if (!sel) return;
  7131. const prevVal = currentVal || sel.value;
  7132. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  7133. (state.bridges || []).forEach(b => {
  7134. const opt = document.createElement('option');
  7135. opt.value = b.name;
  7136. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  7137. if (b.name === prevVal) opt.selected = true;
  7138. sel.appendChild(opt);
  7139. });
  7140. }
  7141. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  7142. const sel = document.getElementById(selectId);
  7143. if (!sel) return;
  7144. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  7145. // 1. Physical Interfaces
  7146. const grpPhys = document.createElement('optgroup');
  7147. grpPhys.label = 'Physical Interfaces';
  7148. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  7149. const opt = document.createElement('option');
  7150. opt.value = i.name;
  7151. opt.innerText = `${i.name} (${i.role || i.type})`;
  7152. if (i.name === currentVal) opt.selected = true;
  7153. grpPhys.appendChild(opt);
  7154. });
  7155. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  7156. // 2. VLAN Sub-interfaces
  7157. const grpVlans = document.createElement('optgroup');
  7158. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  7159. (state.vlans || []).forEach(v => {
  7160. const opt = document.createElement('option');
  7161. opt.value = v.name;
  7162. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  7163. if (v.name === currentVal) opt.selected = true;
  7164. grpVlans.appendChild(opt);
  7165. });
  7166. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  7167. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  7168. const grpEoip = document.createElement('optgroup');
  7169. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  7170. (state.eoipTunnels || []).forEach(t => {
  7171. const opt = document.createElement('option');
  7172. opt.value = t.name;
  7173. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  7174. if (t.name === currentVal) opt.selected = true;
  7175. grpEoip.appendChild(opt);
  7176. });
  7177. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  7178. }
  7179. // -------------------------------------------------------------
  7180. // Routing Filters Management (/routing filter)
  7181. // -------------------------------------------------------------
  7182. function renderRoutingFilters() {
  7183. const tbody = document.getElementById('routing-filters-table-body');
  7184. if (!tbody) return;
  7185. const empty = document.getElementById('routing-filters-empty');
  7186. const countBadge = document.getElementById('routing-filters-count-badge');
  7187. const navBadge = document.getElementById('badge-filters-count');
  7188. const chainSelect = document.getElementById('routing-filter-chain-select');
  7189. const allRules = state.routingFilters || [];
  7190. if (navBadge) navBadge.innerText = allRules.length;
  7191. // Populate chain filter select options dynamically
  7192. if (chainSelect) {
  7193. const currentVal = state.filterChainSelected || 'all';
  7194. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  7195. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  7196. uniqueChains.map(ch => {
  7197. const count = allRules.filter(r => r.chain === ch).length;
  7198. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  7199. }).join('');
  7200. chainSelect.value = currentVal;
  7201. }
  7202. // Filter rules by selected chain
  7203. const filteredRules = (state.filterChainSelected && state.filterChainSelected !== 'all')
  7204. ? allRules.filter(r => r.chain === state.filterChainSelected)
  7205. : allRules.slice();
  7206. // Sort by chain then rule_order
  7207. filteredRules.sort((a, b) => {
  7208. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  7209. return (a.rule_order || 0) - (b.rule_order || 0);
  7210. });
  7211. if (countBadge) countBadge.innerText = `${filteredRules.length} Rules`;
  7212. if (filteredRules.length === 0) {
  7213. tbody.innerHTML = '';
  7214. if (empty) empty.classList.remove('hidden');
  7215. return;
  7216. }
  7217. if (empty) empty.classList.add('hidden');
  7218. tbody.innerHTML = filteredRules.map(r => {
  7219. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  7220. const flagX = r.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  7221. let actionBadge = '';
  7222. if (r.action === 'accept') {
  7223. actionBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-sans font-semibold bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">accept</span>';
  7224. } else if (r.action === 'discard') {
  7225. actionBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-sans font-semibold bg-rose-500/10 text-rose-400 border border-rose-500/20">discard</span>';
  7226. } else if (r.action === 'reject') {
  7227. actionBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-sans font-semibold bg-red-950 text-red-300 border border-red-800/40">reject</span>';
  7228. } else {
  7229. actionBadge = `<span class="px-2 py-0.5 rounded text-[10px] font-sans font-semibold bg-blue-500/10 text-blue-400 border border-blue-500/20">${escapeHtml(r.action || 'accept')}</span>`;
  7230. }
  7231. // Prefix match
  7232. let matchPfx = '';
  7233. if (r.prefix) {
  7234. matchPfx = `<span class="font-bold text-white">${escapeHtml(r.prefix)}</span>`;
  7235. if (r.prefix_len) {
  7236. matchPfx += ` <span class="text-slate-400 text-[11px] font-normal">[${escapeHtml(r.prefix_len)}]</span>`;
  7237. }
  7238. } else {
  7239. matchPfx = '<span class="text-slate-500 italic">any prefix</span>';
  7240. }
  7241. // Other matches
  7242. const matchExtra = [];
  7243. if (r.match_protocol && r.match_protocol !== 'any') {
  7244. matchExtra.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 border border-slate-700">proto:${escapeHtml(r.match_protocol)}</span>`);
  7245. }
  7246. if (r.match_as_path) {
  7247. matchExtra.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-950 text-purple-300 border border-purple-800/40 font-mono">as-path:${escapeHtml(r.match_as_path)}</span>`);
  7248. }
  7249. if (r.match_community) {
  7250. matchExtra.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-indigo-950 text-indigo-300 border border-indigo-800/40 font-mono">comm:${escapeHtml(r.match_community)}</span>`);
  7251. }
  7252. const matchExtraHtml = matchExtra.length > 0 ? matchExtra.join(' ') : '<span class="text-slate-600">-</span>';
  7253. // Set modifications
  7254. const setBadges = [];
  7255. if (r.set_local_pref > 0) {
  7256. setBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-cyan-950 text-cyan-300 border border-cyan-800/40">loc-pref: ${r.set_local_pref}</span>`);
  7257. }
  7258. if (r.set_metric > 0) {
  7259. setBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-amber-950 text-amber-300 border border-amber-800/40">med: ${r.set_metric}</span>`);
  7260. }
  7261. if (r.set_as_prepend > 0) {
  7262. setBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-950 text-purple-300 border border-purple-800/40">prepend: +${r.set_as_prepend}</span>`);
  7263. }
  7264. if (r.set_community) {
  7265. setBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-indigo-950 text-indigo-300 border border-indigo-800/40">comm: ${escapeHtml(r.set_community)}</span>`);
  7266. }
  7267. if (r.set_next_hop) {
  7268. setBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-blue-950 text-blue-300 border border-blue-800/40">nh: ${escapeHtml(r.set_next_hop)}</span>`);
  7269. }
  7270. const setHtml = setBadges.length > 0 ? setBadges.join(' ') : '<span class="text-slate-600">-</span>';
  7271. return `
  7272. <tr class="hover:bg-slate-800/40 transition">
  7273. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagX}</td>
  7274. <td class="py-2.5 px-3 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  7275. <td class="py-2.5 px-3">
  7276. <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>
  7277. </td>
  7278. <td class="py-2.5 px-3">${actionBadge}</td>
  7279. <td class="py-2.5 px-3 font-mono">${matchPfx}</td>
  7280. <td class="py-2.5 px-3 space-x-1">${matchExtraHtml}</td>
  7281. <td class="py-2.5 px-3 space-x-1 font-mono">${setHtml}</td>
  7282. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  7283. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  7284. <button onclick="toggleRoutingFilterState('${r.id}', ${!r.disabled})" class="px-2 py-1 rounded text-[11px] ${r.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  7285. ${r.disabled ? 'Enable' : 'Disable'}
  7286. </button>
  7287. <button onclick="openEditRoutingFilterModal('${r.id}')" class="px-2 py-1 rounded text-[11px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  7288. Edit
  7289. </button>
  7290. <button onclick="deleteRoutingFilter('${r.id}')" class="px-2 py-1 rounded text-[11px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  7291. Delete
  7292. </button>
  7293. </td>
  7294. </tr>
  7295. `;
  7296. }).join('');
  7297. }
  7298. function filterRoutingFiltersByChain(chain) {
  7299. state.filterChainSelected = chain;
  7300. renderRoutingFilters();
  7301. }
  7302. function openAddRoutingFilterModal(defaultChain = '') {
  7303. const form = document.getElementById('routing-filter-form');
  7304. if (form) form.reset();
  7305. const idEl = document.getElementById('modal-rf-id');
  7306. if (idEl) idEl.value = '';
  7307. const titleEl = document.getElementById('modal-rf-title');
  7308. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  7309. const chainEl = document.getElementById('modal-rf-chain');
  7310. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  7311. const orderEl = document.getElementById('modal-rf-order');
  7312. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  7313. const actEl = document.getElementById('modal-rf-action');
  7314. if (actEl) actEl.value = 'accept';
  7315. const protoEl = document.getElementById('modal-rf-protocol');
  7316. if (protoEl) protoEl.value = 'any';
  7317. const disEl = document.getElementById('modal-rf-disabled');
  7318. if (disEl) disEl.checked = false;
  7319. const modal = document.getElementById('modal-routing-filter');
  7320. if (modal) modal.classList.remove('hidden');
  7321. }
  7322. function openEditRoutingFilterModal(id) {
  7323. const r = (state.routingFilters || []).find(item => item.id === id);
  7324. if (!r) return;
  7325. const idEl = document.getElementById('modal-rf-id');
  7326. if (idEl) idEl.value = r.id;
  7327. const titleEl = document.getElementById('modal-rf-title');
  7328. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  7329. const chainEl = document.getElementById('modal-rf-chain');
  7330. if (chainEl) chainEl.value = r.chain || '';
  7331. const orderEl = document.getElementById('modal-rf-order');
  7332. if (orderEl) orderEl.value = r.rule_order || 10;
  7333. const actEl = document.getElementById('modal-rf-action');
  7334. if (actEl) actEl.value = r.action || 'accept';
  7335. const pfxEl = document.getElementById('modal-rf-prefix');
  7336. if (pfxEl) pfxEl.value = r.prefix || '';
  7337. const pfxLenEl = document.getElementById('modal-rf-prefix-len');
  7338. if (pfxLenEl) pfxLenEl.value = r.prefix_len || '';
  7339. const protoEl = document.getElementById('modal-rf-protocol');
  7340. if (protoEl) protoEl.value = r.match_protocol || 'any';
  7341. const aspEl = document.getElementById('modal-rf-as-path');
  7342. if (aspEl) aspEl.value = r.match_as_path || '';
  7343. const commEl = document.getElementById('modal-rf-community');
  7344. if (commEl) commEl.value = r.match_community || '';
  7345. const lpEl = document.getElementById('modal-rf-set-local-pref');
  7346. if (lpEl) lpEl.value = r.set_local_pref || '';
  7347. const metEl = document.getElementById('modal-rf-set-metric');
  7348. if (metEl) metEl.value = r.set_metric || '';
  7349. const prepEl = document.getElementById('modal-rf-set-as-prepend');
  7350. if (prepEl) prepEl.value = r.set_as_prepend || '';
  7351. const setCommEl = document.getElementById('modal-rf-set-community');
  7352. if (setCommEl) setCommEl.value = r.set_community || '';
  7353. const nhEl = document.getElementById('modal-rf-set-next-hop');
  7354. if (nhEl) nhEl.value = r.set_next_hop || '';
  7355. const comEl = document.getElementById('modal-rf-comment');
  7356. if (comEl) comEl.value = r.comment || '';
  7357. const disEl = document.getElementById('modal-rf-disabled');
  7358. if (disEl) disEl.checked = !!r.disabled;
  7359. const modal = document.getElementById('modal-routing-filter');
  7360. if (modal) modal.classList.remove('hidden');
  7361. }
  7362. function closeRoutingFilterModal() {
  7363. const modal = document.getElementById('modal-routing-filter');
  7364. if (modal) modal.classList.add('hidden');
  7365. }
  7366. async function submitRoutingFilter(e) {
  7367. e.preventDefault();
  7368. const payload = {
  7369. id: document.getElementById('modal-rf-id').value,
  7370. chain: document.getElementById('modal-rf-chain').value.trim(),
  7371. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  7372. action: document.getElementById('modal-rf-action').value,
  7373. prefix: document.getElementById('modal-rf-prefix').value.trim(),
  7374. prefix_len: document.getElementById('modal-rf-prefix-len').value.trim(),
  7375. match_protocol: document.getElementById('modal-rf-protocol').value,
  7376. match_as_path: document.getElementById('modal-rf-as-path').value.trim(),
  7377. match_community: document.getElementById('modal-rf-community').value.trim(),
  7378. set_local_pref: parseInt(document.getElementById('modal-rf-set-local-pref').value, 10) || 0,
  7379. set_metric: parseInt(document.getElementById('modal-rf-set-metric').value, 10) || 0,
  7380. set_as_prepend: parseInt(document.getElementById('modal-rf-set-as-prepend').value, 10) || 0,
  7381. set_community: document.getElementById('modal-rf-set-community').value.trim(),
  7382. set_next_hop: document.getElementById('modal-rf-set-next-hop').value.trim(),
  7383. comment: document.getElementById('modal-rf-comment').value.trim(),
  7384. disabled: document.getElementById('modal-rf-disabled').checked
  7385. };
  7386. try {
  7387. const res = await fetch(`${API_BASE}/routing/filters`, {
  7388. method: 'POST',
  7389. headers: { 'Content-Type': 'application/json' },
  7390. body: JSON.stringify(payload)
  7391. });
  7392. if (res.ok) {
  7393. closeRoutingFilterModal();
  7394. showToast('Success', 'Routing filter rule saved', 'success');
  7395. loadDynamicRouting();
  7396. } else {
  7397. const err = await res.json();
  7398. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  7399. }
  7400. } catch (err) {
  7401. showToast('Error', err.message, 'error');
  7402. }
  7403. }
  7404. async function deleteRoutingFilter(id) {
  7405. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  7406. try {
  7407. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7408. if (res.ok) {
  7409. showToast('Deleted', 'Routing filter rule removed', 'info');
  7410. loadDynamicRouting();
  7411. } else {
  7412. const err = await res.json();
  7413. showToast('Error', err.error || 'Failed to delete rule', 'error');
  7414. }
  7415. } catch (err) {
  7416. showToast('Error', err.message, 'error');
  7417. }
  7418. }
  7419. async function toggleRoutingFilterState(id, disabled) {
  7420. try {
  7421. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  7422. method: 'POST',
  7423. headers: { 'Content-Type': 'application/json' },
  7424. body: JSON.stringify({ disabled })
  7425. });
  7426. if (res.ok) {
  7427. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  7428. loadDynamicRouting();
  7429. } else {
  7430. const err = await res.json();
  7431. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  7432. }
  7433. } catch (err) {
  7434. showToast('Error', err.message, 'error');
  7435. }
  7436. }
  7437. // ==========================================
  7438. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  7439. // ==========================================
  7440. function loadToolsView() {
  7441. populateToolsInterfaces();
  7442. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  7443. }
  7444. function populateToolsInterfaces() {
  7445. const pingSel = document.getElementById('tools-ping-iface');
  7446. const traceSel = document.getElementById('tools-tr-iface');
  7447. let opts = '<option value="">Auto (Default Route)</option>';
  7448. if (Array.isArray(state.interfaces)) {
  7449. state.interfaces.forEach(iface => {
  7450. if (iface.name) {
  7451. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  7452. }
  7453. });
  7454. }
  7455. if (pingSel) {
  7456. const cur = pingSel.value;
  7457. pingSel.innerHTML = opts;
  7458. if (cur) pingSel.value = cur;
  7459. }
  7460. if (traceSel) {
  7461. const cur = traceSel.value;
  7462. traceSel.innerHTML = opts;
  7463. if (cur) traceSel.value = cur;
  7464. }
  7465. }
  7466. function switchToolsSubTab(subTab) {
  7467. state.activeToolsSubTab = subTab;
  7468. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  7469. tabs.forEach(t => {
  7470. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  7471. const view = document.getElementById(`tools-view-${t}`);
  7472. if (btn) {
  7473. if (t === subTab) {
  7474. 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';
  7475. } else {
  7476. 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';
  7477. }
  7478. }
  7479. if (view) {
  7480. if (t === subTab) {
  7481. view.classList.remove('hidden');
  7482. } else {
  7483. view.classList.add('hidden');
  7484. }
  7485. }
  7486. });
  7487. }
  7488. function setPortPreset(port) {
  7489. const input = document.getElementById('tools-port-num');
  7490. if (input) input.value = port;
  7491. }
  7492. let pingAbortController = null;
  7493. let tracerouteAbortController = null;
  7494. function clearPingTable() {
  7495. const tbody = document.getElementById('tools-ping-tbody');
  7496. if (tbody) tbody.innerHTML = '';
  7497. const rawEl = document.getElementById('tools-ping-raw');
  7498. if (rawEl) rawEl.innerText = '';
  7499. const sentEl = document.getElementById('tools-ping-stat-sent');
  7500. if (sentEl) sentEl.innerText = '0';
  7501. const recvEl = document.getElementById('tools-ping-stat-recv');
  7502. if (recvEl) recvEl.innerText = '0';
  7503. const lossEl = document.getElementById('tools-ping-stat-loss');
  7504. if (lossEl) lossEl.innerText = '0%';
  7505. const avgEl = document.getElementById('tools-ping-stat-avg');
  7506. if (avgEl) avgEl.innerText = '0 ms';
  7507. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  7508. if (minMaxEl) minMaxEl.innerText = '-';
  7509. const badge = document.getElementById('tools-ping-status-badge');
  7510. if (badge) {
  7511. badge.className = '';
  7512. badge.innerText = '';
  7513. }
  7514. }
  7515. function clearTracerouteTable() {
  7516. const tbody = document.getElementById('tools-tr-tbody');
  7517. if (tbody) tbody.innerHTML = '';
  7518. const rawEl = document.getElementById('tools-tr-raw');
  7519. if (rawEl) rawEl.innerText = '';
  7520. const statHops = document.getElementById('tools-tr-hops-count');
  7521. if (statHops) statHops.innerText = '0 Hops';
  7522. }
  7523. function resetPingButton() {
  7524. const btn = document.getElementById('tools-ping-btn');
  7525. const btnText = document.getElementById('tools-ping-btn-text');
  7526. const spinner = document.getElementById('tools-ping-spinner');
  7527. if (btn) {
  7528. btn.disabled = false;
  7529. 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';
  7530. }
  7531. if (btnText) btnText.innerText = 'Start Ping';
  7532. if (spinner) spinner.classList.add('hidden');
  7533. }
  7534. function setPingRunningButton() {
  7535. const btn = document.getElementById('tools-ping-btn');
  7536. const btnText = document.getElementById('tools-ping-btn-text');
  7537. const spinner = document.getElementById('tools-ping-spinner');
  7538. if (btn) {
  7539. btn.disabled = false;
  7540. 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';
  7541. }
  7542. if (btnText) btnText.innerText = 'Stop Ping';
  7543. if (spinner) spinner.classList.remove('hidden');
  7544. }
  7545. function resetTracerouteButton() {
  7546. const btn = document.getElementById('tools-tr-btn');
  7547. const btnText = document.getElementById('tools-tr-btn-text');
  7548. const spinner = document.getElementById('tools-tr-spinner');
  7549. if (btn) {
  7550. btn.disabled = false;
  7551. 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';
  7552. }
  7553. if (btnText) btnText.innerText = 'Start Traceroute';
  7554. if (spinner) spinner.classList.add('hidden');
  7555. }
  7556. function setTracerouteRunningButton() {
  7557. const btn = document.getElementById('tools-tr-btn');
  7558. const btnText = document.getElementById('tools-tr-btn-text');
  7559. const spinner = document.getElementById('tools-tr-spinner');
  7560. if (btn) {
  7561. btn.disabled = false;
  7562. 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';
  7563. }
  7564. if (btnText) btnText.innerText = 'Stop Traceroute';
  7565. if (spinner) spinner.classList.remove('hidden');
  7566. }
  7567. async function executePing(e) {
  7568. if (e) e.preventDefault();
  7569. // If already running, clicking the button stops the stream!
  7570. if (pingAbortController) {
  7571. pingAbortController.abort();
  7572. pingAbortController = null;
  7573. resetPingButton();
  7574. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  7575. return;
  7576. }
  7577. const target = document.getElementById('tools-ping-target')?.value?.trim();
  7578. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  7579. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  7580. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  7581. const iface = document.getElementById('tools-ping-iface')?.value || '';
  7582. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  7583. if (!target) {
  7584. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  7585. return;
  7586. }
  7587. clearPingTable();
  7588. const resCard = document.getElementById('tools-ping-results');
  7589. if (resCard) resCard.classList.remove('hidden');
  7590. pingAbortController = new AbortController();
  7591. setPingRunningButton();
  7592. try {
  7593. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  7594. method: 'POST',
  7595. headers: { 'Content-Type': 'application/json' },
  7596. body: JSON.stringify({
  7597. target,
  7598. count,
  7599. size,
  7600. timeout,
  7601. interface: iface,
  7602. dont_frag: dontFrag
  7603. }),
  7604. signal: pingAbortController.signal
  7605. });
  7606. if (!res.ok) {
  7607. const errText = await res.text();
  7608. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  7609. resetPingButton();
  7610. pingAbortController = null;
  7611. return;
  7612. }
  7613. const reader = res.body.getReader();
  7614. const decoder = new TextDecoder('utf-8');
  7615. let buffer = '';
  7616. while (true) {
  7617. const { done, value } = await reader.read();
  7618. if (done) break;
  7619. buffer += decoder.decode(value, { stream: true });
  7620. const blocks = buffer.split('\n\n');
  7621. buffer = blocks.pop() || '';
  7622. for (const block of blocks) {
  7623. const trimmed = block.trim();
  7624. if (!trimmed) continue;
  7625. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  7626. try {
  7627. const evt = JSON.parse(line);
  7628. handleLivePingEvent(evt);
  7629. } catch (parseErr) {
  7630. console.warn('Ping SSE parse error:', parseErr, line);
  7631. }
  7632. }
  7633. }
  7634. } catch (err) {
  7635. if (err.name === 'AbortError') {
  7636. // User aborted normally
  7637. } else {
  7638. showToast('Ping Error', err.message, 'error');
  7639. }
  7640. } finally {
  7641. pingAbortController = null;
  7642. resetPingButton();
  7643. }
  7644. }
  7645. function handleLivePingEvent(evt) {
  7646. const sentEl = document.getElementById('tools-ping-stat-sent');
  7647. const recvEl = document.getElementById('tools-ping-stat-recv');
  7648. const lossEl = document.getElementById('tools-ping-stat-loss');
  7649. const avgEl = document.getElementById('tools-ping-stat-avg');
  7650. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  7651. const badge = document.getElementById('tools-ping-status-badge');
  7652. const tbody = document.getElementById('tools-ping-tbody');
  7653. const rawEl = document.getElementById('tools-ping-raw');
  7654. if (evt.raw && rawEl) {
  7655. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  7656. rawEl.scrollTop = rawEl.scrollHeight;
  7657. }
  7658. if (evt.type === 'reply') {
  7659. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  7660. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  7661. if (lossEl && evt.packet_loss_pct !== undefined) {
  7662. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  7663. lossEl.className = evt.packet_loss_pct === 0
  7664. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  7665. : (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');
  7666. }
  7667. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  7668. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  7669. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  7670. }
  7671. if (badge) {
  7672. if (evt.packet_loss_pct === 0) {
  7673. 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';
  7674. badge.innerText = '100% OK';
  7675. } else {
  7676. 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';
  7677. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  7678. }
  7679. }
  7680. if (tbody) {
  7681. const tr = document.createElement('tr');
  7682. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  7683. tr.innerHTML = `
  7684. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  7685. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  7686. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  7687. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  7688. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  7689. <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>
  7690. `;
  7691. tbody.appendChild(tr);
  7692. }
  7693. } else if (evt.type === 'timeout') {
  7694. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  7695. if (lossEl && evt.packet_loss_pct !== undefined) {
  7696. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  7697. 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';
  7698. }
  7699. if (badge) {
  7700. 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';
  7701. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  7702. }
  7703. if (tbody) {
  7704. const tr = document.createElement('tr');
  7705. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  7706. tr.innerHTML = `
  7707. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  7708. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  7709. <td class="py-2 px-3 text-slate-600">--</td>
  7710. <td class="py-2 px-3 text-slate-600">--</td>
  7711. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  7712. <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>
  7713. `;
  7714. tbody.appendChild(tr);
  7715. }
  7716. } else if (evt.type === 'unreach') {
  7717. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  7718. if (lossEl && evt.packet_loss_pct !== undefined) {
  7719. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  7720. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  7721. }
  7722. if (badge) {
  7723. 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';
  7724. badge.innerText = 'UNREACHABLE';
  7725. }
  7726. if (tbody) {
  7727. const tr = document.createElement('tr');
  7728. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  7729. tr.innerHTML = `
  7730. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  7731. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  7732. <td class="py-2 px-3 text-slate-600">--</td>
  7733. <td class="py-2 px-3 text-slate-600">--</td>
  7734. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  7735. <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>
  7736. `;
  7737. tbody.appendChild(tr);
  7738. }
  7739. } else if (evt.type === 'stats') {
  7740. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  7741. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  7742. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  7743. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  7744. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  7745. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  7746. }
  7747. } else if (evt.type === 'done') {
  7748. 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');
  7749. }
  7750. }
  7751. async function executeTraceroute(e) {
  7752. if (e) e.preventDefault();
  7753. if (tracerouteAbortController) {
  7754. tracerouteAbortController.abort();
  7755. tracerouteAbortController = null;
  7756. resetTracerouteButton();
  7757. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  7758. return;
  7759. }
  7760. const target = document.getElementById('tools-tr-target')?.value?.trim();
  7761. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  7762. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  7763. const iface = document.getElementById('tools-tr-iface')?.value || '';
  7764. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  7765. if (!target) {
  7766. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  7767. return;
  7768. }
  7769. clearTracerouteTable();
  7770. const resCard = document.getElementById('tools-tr-results');
  7771. if (resCard) resCard.classList.remove('hidden');
  7772. tracerouteAbortController = new AbortController();
  7773. setTracerouteRunningButton();
  7774. try {
  7775. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  7776. method: 'POST',
  7777. headers: { 'Content-Type': 'application/json' },
  7778. body: JSON.stringify({
  7779. target,
  7780. max_hops: maxHops,
  7781. protocol,
  7782. interface: iface,
  7783. resolve
  7784. }),
  7785. signal: tracerouteAbortController.signal
  7786. });
  7787. if (!res.ok) {
  7788. const errText = await res.text();
  7789. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  7790. resetTracerouteButton();
  7791. tracerouteAbortController = null;
  7792. return;
  7793. }
  7794. const reader = res.body.getReader();
  7795. const decoder = new TextDecoder('utf-8');
  7796. let buffer = '';
  7797. while (true) {
  7798. const { done, value } = await reader.read();
  7799. if (done) break;
  7800. buffer += decoder.decode(value, { stream: true });
  7801. const blocks = buffer.split('\n\n');
  7802. buffer = blocks.pop() || '';
  7803. for (const block of blocks) {
  7804. const trimmed = block.trim();
  7805. if (!trimmed) continue;
  7806. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  7807. try {
  7808. const evt = JSON.parse(line);
  7809. handleLiveTracerouteEvent(evt);
  7810. } catch (parseErr) {
  7811. console.warn('Traceroute SSE parse error:', parseErr, line);
  7812. }
  7813. }
  7814. }
  7815. } catch (err) {
  7816. if (err.name === 'AbortError') {
  7817. // User aborted normally
  7818. } else {
  7819. showToast('Traceroute Error', err.message, 'error');
  7820. }
  7821. } finally {
  7822. tracerouteAbortController = null;
  7823. resetTracerouteButton();
  7824. }
  7825. }
  7826. function handleLiveTracerouteEvent(evt) {
  7827. const statHops = document.getElementById('tools-tr-hops-count');
  7828. const tbody = document.getElementById('tools-tr-tbody');
  7829. const rawEl = document.getElementById('tools-tr-raw');
  7830. if (evt.raw && rawEl) {
  7831. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  7832. rawEl.scrollTop = rawEl.scrollHeight;
  7833. }
  7834. if (evt.hops_count !== undefined && statHops) {
  7835. statHops.innerText = `${evt.hops_count} Hops`;
  7836. }
  7837. if (evt.type === 'hop' && evt.hop && tbody) {
  7838. const h = evt.hop;
  7839. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  7840. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  7841. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  7842. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  7843. const tr = document.createElement('tr');
  7844. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  7845. tr.innerHTML = `
  7846. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  7847. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  7848. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  7849. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  7850. <td class="py-2.5 px-3 text-right">
  7851. ${isTimeout
  7852. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  7853. : '<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>'}
  7854. </td>
  7855. `;
  7856. tbody.appendChild(tr);
  7857. } else if (evt.type === 'done') {
  7858. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  7859. }
  7860. }
  7861. async function executeMTR(e) {
  7862. if (e) e.preventDefault();
  7863. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  7864. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  7865. if (!target) {
  7866. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  7867. return;
  7868. }
  7869. const btn = document.getElementById('tools-mtr-btn');
  7870. const spinner = document.getElementById('tools-mtr-spinner');
  7871. if (btn) btn.disabled = true;
  7872. if (spinner) spinner.classList.remove('hidden');
  7873. try {
  7874. const res = await fetch(`${API_BASE}/tools/mtr`, {
  7875. method: 'POST',
  7876. headers: { 'Content-Type': 'application/json' },
  7877. body: JSON.stringify({ target, count: cycles })
  7878. });
  7879. const data = await res.json();
  7880. if (!res.ok) {
  7881. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  7882. return;
  7883. }
  7884. const resCard = document.getElementById('tools-mtr-results');
  7885. if (resCard) resCard.classList.remove('hidden');
  7886. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  7887. const statHops = document.getElementById('tools-mtr-hops-count');
  7888. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  7889. const tbody = document.getElementById('tools-mtr-tbody');
  7890. if (tbody) {
  7891. if (hopsCount > 0) {
  7892. tbody.innerHTML = data.hops.map(h => {
  7893. 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');
  7894. return `
  7895. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  7896. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  7897. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  7898. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  7899. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  7900. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  7901. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  7902. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  7903. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  7904. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  7905. </tr>
  7906. `;
  7907. }).join('');
  7908. } else {
  7909. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  7910. }
  7911. }
  7912. const rawEl = document.getElementById('tools-mtr-raw');
  7913. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  7914. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  7915. } catch (err) {
  7916. showToast('MTR Error', err.message, 'error');
  7917. } finally {
  7918. if (btn) btn.disabled = false;
  7919. if (spinner) spinner.classList.add('hidden');
  7920. }
  7921. }
  7922. async function executeDNS(e) {
  7923. if (e) e.preventDefault();
  7924. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  7925. const type = document.getElementById('tools-dns-type')?.value || 'A';
  7926. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  7927. if (!domain) {
  7928. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  7929. return;
  7930. }
  7931. const btn = document.getElementById('tools-dns-btn');
  7932. const spinner = document.getElementById('tools-dns-spinner');
  7933. if (btn) btn.disabled = true;
  7934. if (spinner) spinner.classList.remove('hidden');
  7935. try {
  7936. const res = await fetch(`${API_BASE}/tools/dns`, {
  7937. method: 'POST',
  7938. headers: { 'Content-Type': 'application/json' },
  7939. body: JSON.stringify({ domain, type, server })
  7940. });
  7941. const data = await res.json();
  7942. if (!res.ok) {
  7943. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  7944. return;
  7945. }
  7946. const resCard = document.getElementById('tools-dns-results');
  7947. if (resCard) resCard.classList.remove('hidden');
  7948. const metaEl = document.getElementById('tools-dns-meta');
  7949. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  7950. const tbody = document.getElementById('tools-dns-tbody');
  7951. if (tbody) {
  7952. if (Array.isArray(data.records) && data.records.length > 0) {
  7953. tbody.innerHTML = data.records.map(r => `
  7954. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  7955. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  7956. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  7957. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  7958. <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>
  7959. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  7960. </tr>
  7961. `).join('');
  7962. } else {
  7963. 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>`;
  7964. }
  7965. }
  7966. const rawEl = document.getElementById('tools-dns-raw');
  7967. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  7968. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  7969. } catch (err) {
  7970. showToast('DNS Error', err.message, 'error');
  7971. } finally {
  7972. if (btn) btn.disabled = false;
  7973. if (spinner) spinner.classList.add('hidden');
  7974. }
  7975. }
  7976. async function executePortProbe(e) {
  7977. if (e) e.preventDefault();
  7978. const target = document.getElementById('tools-port-target')?.value?.trim();
  7979. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  7980. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  7981. if (!target || !port) {
  7982. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  7983. return;
  7984. }
  7985. const btn = document.getElementById('tools-port-btn');
  7986. const spinner = document.getElementById('tools-port-spinner');
  7987. if (btn) btn.disabled = true;
  7988. if (spinner) spinner.classList.remove('hidden');
  7989. try {
  7990. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  7991. method: 'POST',
  7992. headers: { 'Content-Type': 'application/json' },
  7993. body: JSON.stringify({ target, port, timeout })
  7994. });
  7995. const data = await res.json();
  7996. if (!res.ok) {
  7997. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  7998. return;
  7999. }
  8000. const resCard = document.getElementById('tools-port-results');
  8001. if (resCard) resCard.classList.remove('hidden');
  8002. const banner = document.getElementById('tools-port-banner');
  8003. const icon = document.getElementById('tools-port-icon');
  8004. const title = document.getElementById('tools-port-title');
  8005. const sub = document.getElementById('tools-port-sub');
  8006. const latency = document.getElementById('tools-port-latency');
  8007. if (data.open) {
  8008. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  8009. if (icon) {
  8010. 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';
  8011. icon.innerText = '✓';
  8012. }
  8013. if (title) {
  8014. title.className = 'text-sm font-bold text-emerald-300';
  8015. title.innerText = `PORT ${port} OPEN / LISTENING`;
  8016. }
  8017. if (sub) {
  8018. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  8019. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  8020. }
  8021. if (latency) {
  8022. latency.className = 'text-base font-bold font-mono text-emerald-300';
  8023. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  8024. }
  8025. } else {
  8026. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  8027. if (icon) {
  8028. 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';
  8029. icon.innerText = '✕';
  8030. }
  8031. if (title) {
  8032. title.className = 'text-sm font-bold text-rose-300';
  8033. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  8034. }
  8035. if (sub) {
  8036. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  8037. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  8038. }
  8039. if (latency) {
  8040. latency.className = 'text-base font-bold font-mono text-slate-500';
  8041. latency.innerText = '--';
  8042. }
  8043. }
  8044. const rawEl = document.getElementById('tools-port-raw');
  8045. 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'}`);
  8046. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  8047. } catch (err) {
  8048. showToast('Probe Error', err.message, 'error');
  8049. } finally {
  8050. if (btn) btn.disabled = false;
  8051. if (spinner) spinner.classList.add('hidden');
  8052. }
  8053. }
  8054. // ==========================================
  8055. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  8056. // ==========================================
  8057. async function loadDHCPClients(showToastMsg = false) {
  8058. try {
  8059. const [clientsRes, sumRes] = await Promise.all([
  8060. fetch(`${API_BASE}/dhcp/clients`),
  8061. fetch(`${API_BASE}/dhcp/clients/summary`)
  8062. ]);
  8063. if (clientsRes.ok) {
  8064. state.dhcpClients = await clientsRes.json();
  8065. }
  8066. if (sumRes.ok) {
  8067. state.dhcpSummary = await sumRes.json();
  8068. }
  8069. renderDHCPClients();
  8070. updateDHCPSummaryCards();
  8071. const bDhcp = document.getElementById('badge-dhcp-client-count');
  8072. if (bDhcp && state.dhcpSummary) {
  8073. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  8074. }
  8075. if (showToastMsg) {
  8076. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  8077. }
  8078. } catch (err) {
  8079. console.error('Failed to load DHCP clients:', err);
  8080. if (showToastMsg) {
  8081. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  8082. }
  8083. }
  8084. }
  8085. function updateDHCPSummaryCards() {
  8086. const sum = state.dhcpSummary || {
  8087. total_clients: (state.dhcpClients || []).length,
  8088. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  8089. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  8090. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  8091. };
  8092. const totalEl = document.getElementById('dhcp-stat-total');
  8093. const boundEl = document.getElementById('dhcp-stat-bound');
  8094. const searchEl = document.getElementById('dhcp-stat-searching');
  8095. const disEl = document.getElementById('dhcp-stat-disabled');
  8096. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  8097. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  8098. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  8099. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  8100. }
  8101. function renderDHCPClients() {
  8102. const tbody = document.getElementById('dhcp-clients-tbody');
  8103. const emptyState = document.getElementById('dhcp-clients-empty');
  8104. if (!tbody) return;
  8105. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  8106. if (clients.length === 0) {
  8107. tbody.innerHTML = '';
  8108. if (emptyState) emptyState.classList.remove('hidden');
  8109. return;
  8110. }
  8111. if (emptyState) emptyState.classList.add('hidden');
  8112. tbody.innerHTML = clients.map(c => {
  8113. let statusBadge = '';
  8114. if (!c.enabled) {
  8115. 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>';
  8116. } else if (c.status === 'bound') {
  8117. 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>';
  8118. } else if (c.status === 'searching') {
  8119. 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>';
  8120. } else if (c.status === 'stopped') {
  8121. 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>';
  8122. } else {
  8123. 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>`;
  8124. }
  8125. 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>';
  8126. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  8127. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  8128. 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>';
  8129. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  8130. // Option flags
  8131. const flags = [];
  8132. 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>');
  8133. 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>');
  8134. 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>');
  8135. 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>`);
  8136. return `
  8137. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  8138. <td class="py-3 px-4">
  8139. <div class="flex items-center gap-2">
  8140. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  8141. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  8142. </div>
  8143. </td>
  8144. <td class="py-3 px-4">${statusBadge}</td>
  8145. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  8146. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  8147. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  8148. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  8149. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  8150. <td class="py-3 px-4">
  8151. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  8152. </td>
  8153. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  8154. ${c.enabled ? `
  8155. <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>
  8156. <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>
  8157. <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>
  8158. ` : `
  8159. <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>
  8160. `}
  8161. <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>
  8162. <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>
  8163. </td>
  8164. </tr>
  8165. `;
  8166. }).join('');
  8167. }
  8168. function openDHCPClientModal(clientId = null) {
  8169. const modal = document.getElementById('modal-dhcp-client');
  8170. if (!modal) return;
  8171. const title = document.getElementById('modal-dhcp-title');
  8172. const idInput = document.getElementById('modal-dhcp-id');
  8173. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  8174. const distInput = document.getElementById('modal-dhcp-distance');
  8175. const commentInput = document.getElementById('modal-dhcp-comment');
  8176. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  8177. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  8178. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  8179. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  8180. // Populate interfaces
  8181. if (ifaceSelect) {
  8182. let opts = '<option value="">Select interface...</option>';
  8183. const allIfaces = state.interfaces || [];
  8184. const allVlans = state.vlans || [];
  8185. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  8186. // Group 1: Physical & Bridge Interfaces
  8187. opts += '<optgroup label="Physical & Bridge Interfaces">';
  8188. allIfaces.forEach(i => {
  8189. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  8190. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  8191. });
  8192. opts += '</optgroup>';
  8193. // Group 2: VLAN Interfaces
  8194. if (allVlans.length > 0) {
  8195. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  8196. allVlans.forEach(v => {
  8197. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  8198. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  8199. });
  8200. opts += '</optgroup>';
  8201. }
  8202. ifaceSelect.innerHTML = opts;
  8203. }
  8204. if (clientId) {
  8205. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  8206. if (client) {
  8207. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  8208. if (idInput) idInput.value = client.id;
  8209. if (ifaceSelect) {
  8210. ifaceSelect.value = client.interface;
  8211. ifaceSelect.disabled = true; // interface cannot be changed on edit
  8212. }
  8213. if (distInput) distInput.value = client.default_route_distance || 1;
  8214. if (commentInput) commentInput.value = client.comment || '';
  8215. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  8216. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  8217. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  8218. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  8219. }
  8220. } else {
  8221. if (title) title.innerText = 'Add DHCP Client';
  8222. if (idInput) idInput.value = '';
  8223. if (ifaceSelect) {
  8224. ifaceSelect.value = '';
  8225. ifaceSelect.disabled = false;
  8226. }
  8227. if (distInput) distInput.value = 1;
  8228. if (commentInput) commentInput.value = '';
  8229. if (defRouteCheck) defRouteCheck.checked = true;
  8230. if (peerDnsCheck) peerDnsCheck.checked = true;
  8231. if (peerNtpCheck) peerNtpCheck.checked = true;
  8232. if (enabledCheck) enabledCheck.checked = true;
  8233. }
  8234. modal.classList.remove('hidden');
  8235. }
  8236. function openDHCPClientModalForIface(ifaceName) {
  8237. openDHCPClientModal();
  8238. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  8239. if (ifaceSelect && ifaceName) {
  8240. ifaceSelect.value = ifaceName;
  8241. }
  8242. }
  8243. function closeDHCPClientModal() {
  8244. const modal = document.getElementById('modal-dhcp-client');
  8245. if (modal) modal.classList.add('hidden');
  8246. }
  8247. async function submitSaveDHCPClient(e) {
  8248. if (e) e.preventDefault();
  8249. const id = document.getElementById('modal-dhcp-id')?.value;
  8250. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  8251. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  8252. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  8253. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  8254. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  8255. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  8256. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  8257. if (!id && !iface) {
  8258. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  8259. return;
  8260. }
  8261. try {
  8262. let res;
  8263. if (id) {
  8264. // PUT update
  8265. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  8266. method: 'PUT',
  8267. headers: { 'Content-Type': 'application/json' },
  8268. body: JSON.stringify({
  8269. enabled,
  8270. add_default_route: defRoute,
  8271. default_route_distance: distance,
  8272. use_peer_dns: peerDns,
  8273. use_peer_ntp: peerNtp,
  8274. comment
  8275. })
  8276. });
  8277. } else {
  8278. // POST create
  8279. res = await fetch(`${API_BASE}/dhcp/clients`, {
  8280. method: 'POST',
  8281. headers: { 'Content-Type': 'application/json' },
  8282. body: JSON.stringify({
  8283. interface: iface,
  8284. enabled,
  8285. add_default_route: defRoute,
  8286. default_route_distance: distance,
  8287. use_peer_dns: peerDns,
  8288. use_peer_ntp: peerNtp,
  8289. comment
  8290. })
  8291. });
  8292. }
  8293. const data = await res.json();
  8294. if (!res.ok) {
  8295. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  8296. return;
  8297. }
  8298. closeDHCPClientModal();
  8299. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  8300. await loadDHCPClients();
  8301. fetchData(); // refresh interfaces list with new lease/status
  8302. } catch (err) {
  8303. showToast('Error', err.message, 'error');
  8304. }
  8305. }
  8306. async function toggleDHCPClientState(id, enabled) {
  8307. try {
  8308. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  8309. method: 'POST',
  8310. headers: { 'Content-Type': 'application/json' },
  8311. body: JSON.stringify({ enabled })
  8312. });
  8313. const data = await res.json();
  8314. if (!res.ok) {
  8315. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  8316. return;
  8317. }
  8318. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  8319. await loadDHCPClients();
  8320. fetchData();
  8321. } catch (err) {
  8322. showToast('Error', err.message, 'error');
  8323. }
  8324. }
  8325. async function renewDHCPClient(id) {
  8326. try {
  8327. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  8328. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  8329. method: 'POST'
  8330. });
  8331. const data = await res.json();
  8332. if (!res.ok) {
  8333. showToast('Error', data.error || 'Failed to renew lease', 'error');
  8334. return;
  8335. }
  8336. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  8337. setTimeout(() => {
  8338. loadDHCPClients();
  8339. fetchData();
  8340. }, 1500);
  8341. } catch (err) {
  8342. showToast('Error', err.message, 'error');
  8343. }
  8344. }
  8345. async function releaseDHCPClient(id) {
  8346. try {
  8347. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  8348. method: 'POST'
  8349. });
  8350. const data = await res.json();
  8351. if (!res.ok) {
  8352. showToast('Error', data.error || 'Failed to release lease', 'error');
  8353. return;
  8354. }
  8355. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  8356. await loadDHCPClients();
  8357. fetchData();
  8358. } catch (err) {
  8359. showToast('Error', err.message, 'error');
  8360. }
  8361. }
  8362. async function deleteDHCPClient(id, ifaceName) {
  8363. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  8364. return;
  8365. }
  8366. try {
  8367. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  8368. method: 'DELETE'
  8369. });
  8370. const data = await res.json();
  8371. if (!res.ok) {
  8372. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  8373. return;
  8374. }
  8375. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  8376. await loadDHCPClients();
  8377. fetchData();
  8378. } catch (err) {
  8379. showToast('Error', err.message, 'error');
  8380. }
  8381. }