app.js 424 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146
  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. initTableSorting();
  64. fetchData();
  65. // Live polling every 2.5 seconds
  66. setInterval(() => {
  67. if (state.isPolling) {
  68. fetchData(false);
  69. }
  70. }, 2500);
  71. });
  72. // Navigation Handler
  73. function navigate(tabName) {
  74. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  75. navigate('bgp');
  76. return;
  77. }
  78. if (tabName === 'vlans') {
  79. navigate('interfaces');
  80. return;
  81. }
  82. state.activeTab = tabName;
  83. window.location.hash = tabName;
  84. // Update nav links styling
  85. document.querySelectorAll('.nav-link').forEach(link => {
  86. 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';
  87. });
  88. const activeNav = document.getElementById(`nav-${tabName}`);
  89. if (activeNav) {
  90. 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';
  91. }
  92. // Update page headers
  93. const titles = {
  94. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  95. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  96. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  97. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  98. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  99. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  100. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  101. bgp: { title: 'BGP Routing (/routing bgp)', sub: 'FRRouting BGP peering sessions, advertised networks, and BGP routing table (RIB)' },
  102. ospf: { title: 'OSPF Routing (/routing ospf)', sub: 'FRRouting OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  103. 'routing-filters': { title: 'Routing Filters (/routing filter)', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  104. 'dynamic-routing': { title: 'BGP Routing (/routing bgp)', sub: 'FRRouting dynamic routing' },
  105. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  106. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  107. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  108. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  109. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  110. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  111. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  112. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  113. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' }
  114. };
  115. const header = titles[tabName] || titles.dashboard;
  116. const pTitle = document.getElementById('page-title');
  117. if (pTitle) pTitle.innerText = header.title;
  118. const pSub = document.getElementById('page-subtitle');
  119. if (pSub) pSub.innerText = header.sub;
  120. // Toggle sections dynamically for all section elements
  121. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  122. if (el.id === `section-${tabName}`) {
  123. el.classList.remove('hidden');
  124. } else {
  125. el.classList.add('hidden');
  126. }
  127. });
  128. if (tabName === 'bridge') loadBridge();
  129. if (tabName === 'firewall') loadFirewall();
  130. if (tabName === 'routes') loadRoutes();
  131. if (tabName === 'bgp') {
  132. loadDynamicRouting();
  133. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  134. }
  135. if (tabName === 'ospf') {
  136. loadDynamicRouting();
  137. switchOspfSubTab(state.activeOspfSubTab || 'ospf-ifaces');
  138. }
  139. if (tabName === 'routing-filters') loadDynamicRouting();
  140. if (tabName === 'dynamic-routing') loadDynamicRouting();
  141. if (tabName === 'ppp') loadPPP();
  142. if (tabName === 'eoip') loadEoIP();
  143. if (tabName === 'persistence') loadDebianConfig();
  144. if (tabName === 'pppoe') loadPPPoE();
  145. if (tabName === 'wireguard') loadWireGuard();
  146. if (tabName === 'ipsec') loadIPSec();
  147. if (tabName === 'l2tp') loadL2TP();
  148. if (tabName === 'pptp') loadPPTP();
  149. if (tabName === 'tools') loadToolsView();
  150. if (tabName === 'dhcp-client') loadDHCPClients();
  151. setTimeout(initTableSorting, 50);
  152. }
  153. // Fetch all core system, network and VPN telemetry
  154. async function fetchData(isManual = false) {
  155. const spinner = document.getElementById('refresh-spinner');
  156. if (isManual && spinner) spinner.classList.add('animate-spin');
  157. try {
  158. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes] = await Promise.all([
  159. fetch(`${API_BASE}/system/status`),
  160. fetch(`${API_BASE}/interfaces`),
  161. fetch(`${API_BASE}/vlans`),
  162. fetch(`${API_BASE}/vpn/status`),
  163. fetch(`${API_BASE}/firewall/summary`),
  164. fetch(`${API_BASE}/routing/dynamic/summary`),
  165. fetch(`${API_BASE}/bridge/summary`),
  166. fetch(`${API_BASE}/dhcp/clients/summary`),
  167. fetch(`${API_BASE}/dhcp/clients`)
  168. ]);
  169. if (dhcpSumRes && dhcpSumRes.ok) {
  170. state.dhcpSummary = await dhcpSumRes.json();
  171. const bDhcp = document.getElementById('badge-dhcp-client-count');
  172. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  173. }
  174. if (dhcpClientsRes && dhcpClientsRes.ok) {
  175. state.dhcpClients = await dhcpClientsRes.json();
  176. }
  177. if (brSummaryRes.ok) {
  178. state.bridgeSummary = await brSummaryRes.json();
  179. const bBridge = document.getElementById('badge-bridge-count');
  180. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  181. const sBr = document.getElementById('bridge-stat-bridges');
  182. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  183. const sPorts = document.getElementById('bridge-stat-ports');
  184. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  185. const sHosts = document.getElementById('bridge-stat-hosts');
  186. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  187. }
  188. if (statusRes.ok) state.systemStatus = await statusRes.json();
  189. if (ifacesRes.ok) {
  190. const ifacesData = await ifacesRes.json();
  191. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  192. state.interfaces = rawIfaces.filter(i => {
  193. if (!i.name) return false;
  194. if (i.name.startsWith('ep_')) return false;
  195. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  196. });
  197. try { populateToolsInterfaces(); } catch (e) {}
  198. }
  199. if (vlansRes.ok) {
  200. const vlansData = await vlansRes.json();
  201. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  202. }
  203. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  204. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  205. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  206. updateSystemMetrics();
  207. updateBadges();
  208. if (state.activeTab === 'dashboard') renderDashboard();
  209. if (state.activeTab === 'interfaces') renderInterfacesList();
  210. if (state.activeTab === 'vlans') renderVlansList();
  211. if (state.activeTab === 'firewall') loadFirewall(false);
  212. if (state.activeTab === 'routes') loadRoutes(false);
  213. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  214. if (state.activeTab === 'ppp') loadPPP(false);
  215. if (state.activeTab === 'eoip') loadEoIP(false);
  216. if (state.activeTab === 'pppoe') loadPPPoE(false);
  217. if (state.activeTab === 'wireguard') loadWireGuard(false);
  218. if (state.activeTab === 'ipsec') loadIPSec(false);
  219. if (state.activeTab === 'l2tp') loadL2TP(false);
  220. if (state.activeTab === 'pptp') loadPPTP(false);
  221. if (state.activeTab === 'dhcp-client') loadDHCPClients(false);
  222. } catch (err) {
  223. console.error('Failed to fetch router state:', err);
  224. } finally {
  225. if (isManual && spinner) {
  226. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  227. }
  228. }
  229. }
  230. // Update Top KPI and Sidebar Telemetry
  231. function updateSystemMetrics() {
  232. const s = state.systemStatus;
  233. const v = state.vpnStatus;
  234. if (!s) return;
  235. // Sidebar Host & Uptime
  236. const sideHost = document.getElementById('side-hostname');
  237. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  238. const sideUp = document.getElementById('side-uptime');
  239. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  240. const sideGw = document.getElementById('side-gateway-ip');
  241. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  242. // Compute CPU Metrics
  243. let cpuPct = 0;
  244. if (s.cpu_pct !== undefined) {
  245. cpuPct = s.cpu_pct;
  246. } else if (s.cpu_load && s.cpu_load.length > 0) {
  247. const cores = s.cpu_cores || 1;
  248. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  249. }
  250. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  251. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  252. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  253. // Sidebar CPU
  254. const sideCpuVal = document.getElementById('side-cpu-val');
  255. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  256. const sideCpuBar = document.getElementById('side-cpu-bar');
  257. if (sideCpuBar) {
  258. sideCpuBar.style.width = cpuWidth;
  259. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  260. }
  261. // Dashboard CPU Card
  262. const dashCpuVal = document.getElementById('dash-cpu-val');
  263. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  264. const dashCpuBar = document.getElementById('dash-cpu-bar');
  265. if (dashCpuBar) {
  266. dashCpuBar.style.width = cpuWidth;
  267. if (cpuPct > 85) {
  268. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  269. } else if (cpuPct > 65) {
  270. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  271. } else {
  272. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  273. }
  274. }
  275. const dashCpuCores = document.getElementById('dash-cpu-cores');
  276. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  277. const dashCpuLoad = document.getElementById('dash-cpu-load');
  278. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  279. const dashCpuStatus = document.getElementById('dash-cpu-status');
  280. if (dashCpuStatus) {
  281. if (cpuPct > 85) {
  282. dashCpuStatus.innerText = 'High';
  283. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  284. } else if (cpuPct > 65) {
  285. dashCpuStatus.innerText = 'Heavy';
  286. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  287. } else {
  288. dashCpuStatus.innerText = 'Normal';
  289. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  290. }
  291. }
  292. // Compute RAM Metrics
  293. const memPct = Math.round(s.mem_usage_pct || 0);
  294. const memPctStr = `${memPct}%`;
  295. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  296. const usedMB = s.mem_used_mb || 0;
  297. const totalMB = s.mem_total_mb || 0;
  298. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  299. function fmtMemMB(mb) {
  300. if (mb >= 1024) {
  301. return `${(mb / 1024).toFixed(1)} GB`;
  302. }
  303. return `${mb} MB`;
  304. }
  305. // Sidebar RAM
  306. const sideRamVal = document.getElementById('side-ram-val');
  307. if (sideRamVal) sideRamVal.innerText = memPctStr;
  308. const sideRamBar = document.getElementById('side-ram-bar');
  309. if (sideRamBar) sideRamBar.style.width = memWidth;
  310. // Dashboard RAM Card
  311. const dashRamVal = document.getElementById('dash-ram-val');
  312. if (dashRamVal) dashRamVal.innerText = memPctStr;
  313. const dashRamBar = document.getElementById('dash-ram-bar');
  314. if (dashRamBar) {
  315. dashRamBar.style.width = memWidth;
  316. if (memPct > 85) {
  317. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  318. } else if (memPct > 70) {
  319. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  320. } else {
  321. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  322. }
  323. }
  324. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  325. if (dashRamUsedTotal) {
  326. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  327. }
  328. const dashRamFree = document.getElementById('dash-ram-free');
  329. if (dashRamFree) {
  330. dashRamFree.innerText = fmtMemMB(freeMB);
  331. }
  332. const dashRamStatus = document.getElementById('dash-ram-status');
  333. if (dashRamStatus) {
  334. if (memPct > 85) {
  335. dashRamStatus.innerText = 'High';
  336. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  337. } else {
  338. dashRamStatus.innerText = 'Active';
  339. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  340. }
  341. }
  342. // Legacy Dashboard Stats (Safe checks)
  343. const elIfacesUp = document.getElementById('stat-ifaces-up');
  344. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  345. const elIfacesTot = document.getElementById('stat-ifaces-total');
  346. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  347. const elIfacesDown = document.getElementById('stat-ifaces-down');
  348. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  349. const elVlans = document.getElementById('stat-vlans-count');
  350. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  351. // VPN Status Indicators
  352. if (v) {
  353. const totalActive = v.total_active_tunnels || 0;
  354. const statVpnActive = document.getElementById('stat-vpn-active');
  355. if (statVpnActive) statVpnActive.innerText = totalActive;
  356. const tunnelsDot = document.getElementById('tunnels-dot');
  357. const tunnelsLabel = document.getElementById('tunnels-label');
  358. if (tunnelsDot && tunnelsLabel) {
  359. if (totalActive > 0) {
  360. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  361. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  362. } else {
  363. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  364. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  365. }
  366. }
  367. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  368. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  369. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  370. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  371. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  372. }
  373. // Total Live Bandwidth Rate
  374. let totalRx = 0;
  375. let totalTx = 0;
  376. (state.interfaces || []).forEach(i => {
  377. if (i.rate) {
  378. totalRx += i.rate.rx_bytes_sec || 0;
  379. totalTx += i.rate.tx_bytes_sec || 0;
  380. }
  381. });
  382. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  383. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  384. }
  385. function setDotBadge(id, active) {
  386. const el = document.getElementById(id);
  387. if (!el) return;
  388. if (active) {
  389. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  390. } else {
  391. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  392. }
  393. }
  394. function updateBadges() {
  395. const bIfaces = document.getElementById('badge-ifaces-count');
  396. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  397. const bVlans = document.getElementById('badge-vlans-count');
  398. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  399. if (state.fwSummary) {
  400. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  401. const badgeFw = document.getElementById('badge-firewall-count');
  402. if (badgeFw) badgeFw.innerText = totalFwRules;
  403. }
  404. if (state.vpnStatus) {
  405. const v = state.vpnStatus;
  406. const bEoIP = document.getElementById('badge-eoip-count');
  407. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  408. const bPPPSess = document.getElementById('badge-ppp-sessions');
  409. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  410. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  411. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  412. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  413. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  414. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  415. }
  416. if (state.dynSummary) {
  417. const d = state.dynSummary;
  418. setDotBadge('badge-bgp-dot', d.bgp_running);
  419. setDotBadge('badge-ospf-dot', d.ospf_running);
  420. const bBgp = document.getElementById('badge-bgp-count');
  421. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  422. const bOspf = document.getElementById('badge-ospf-count');
  423. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  424. const bFilters = document.getElementById('badge-filters-count');
  425. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  426. }
  427. }
  428. // Render Dashboard View
  429. function renderDashboard() {
  430. const matrix = document.getElementById('port-matrix');
  431. matrix.innerHTML = '';
  432. (state.interfaces || []).forEach(iface => {
  433. const isUp = iface.state === 'UP';
  434. const isVlan = iface.is_vlan;
  435. const portCard = document.createElement('div');
  436. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  437. isUp
  438. ? (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')
  439. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  440. }`;
  441. portCard.onclick = () => openIfaceModal(iface.name);
  442. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  443. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  444. portCard.innerHTML = `
  445. <div class="flex items-center justify-between mb-2">
  446. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  447. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  448. </div>
  449. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  450. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  451. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  452. <span>${iface.rate?.rx_human || '0 B/s'}</span>
  453. </div>
  454. `;
  455. matrix.appendChild(portCard);
  456. });
  457. const ifaceTbody = document.getElementById('quick-interfaces-table');
  458. if (ifaceTbody) {
  459. ifaceTbody.innerHTML = '';
  460. (state.interfaces || []).forEach(i => {
  461. const isUp = i.state === 'UP';
  462. const tr = document.createElement('tr');
  463. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  464. tr.onclick = () => openIfaceModal(i.name);
  465. const rxStr = i.rate?.rx_human || '0 B/s';
  466. const txStr = i.rate?.tx_human || '0 B/s';
  467. tr.innerHTML = `
  468. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  469. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  470. <span>${i.name}</span>
  471. </td>
  472. <td class="py-2.5 text-slate-300 font-sans">
  473. <span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 font-medium">${i.role || i.type || 'Ethernet'}</span>
  474. </td>
  475. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  476. <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>
  477. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  478. <span class="text-emerald-400">↓ ${rxStr}</span> <span class="text-slate-600">•</span> <span class="text-cyan-400">↑ ${txStr}</span>
  479. </td>
  480. <td class="py-2.5 text-right font-sans font-semibold">
  481. <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>
  482. </td>
  483. `;
  484. ifaceTbody.appendChild(tr);
  485. });
  486. }
  487. const vlanTbody = document.getElementById('quick-vlans-table');
  488. if (vlanTbody) {
  489. vlanTbody.innerHTML = '';
  490. }
  491. }
  492. // Expand / Collapse Handlers
  493. function toggleExpand(parentName) {
  494. if (state.expandedParents.has(parentName)) {
  495. state.expandedParents.delete(parentName);
  496. } else {
  497. state.expandedParents.add(parentName);
  498. }
  499. renderInterfacesList();
  500. }
  501. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  502. function supportsVLAN(iface) {
  503. if (!iface) return false;
  504. if (iface.is_vlan) return false;
  505. const name = (iface.name || '').toLowerCase();
  506. const type = (iface.type || '').toLowerCase();
  507. const role = (iface.role || '').toLowerCase();
  508. // Exclude loopback
  509. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  510. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  511. if (type === 'wireguard' || name.startsWith('wg')) return false;
  512. // Exclude PPP / PPPoE
  513. if (type === 'ppp' || name.startsWith('ppp')) return false;
  514. // Exclude other Layer 3 tunnels and dummy devices
  515. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  516. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  517. return false;
  518. }
  519. // If name already contains a dot, it's already a sub-interface
  520. if (name.includes('.')) return false;
  521. return true;
  522. }
  523. // Expand / Collapse Handlers
  524. function toggleExpand(parentName) {
  525. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  526. if (childVlans.length === 0) {
  527. // Cannot expand an interface with no VLANs
  528. state.expandedParents.delete(parentName);
  529. return;
  530. }
  531. if (state.expandedParents.has(parentName)) {
  532. state.expandedParents.delete(parentName);
  533. } else {
  534. state.expandedParents.add(parentName);
  535. }
  536. renderInterfacesList();
  537. }
  538. function expandAllIfaces(expand) {
  539. if (expand) {
  540. (state.interfaces || []).forEach(i => {
  541. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  542. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  543. });
  544. } else {
  545. state.expandedParents.clear();
  546. }
  547. renderInterfacesList();
  548. }
  549. // Filter and Render Hierarchical Interfaces List
  550. function filterIfaces(filter) {
  551. state.ifaceFilter = filter || 'all';
  552. renderInterfacesList();
  553. }
  554. function renderInterfacesList() {
  555. const tbody = document.getElementById('interfaces-tree-tbody');
  556. const emptyState = document.getElementById('interfaces-empty-state');
  557. const summary = document.getElementById('ifaces-list-summary');
  558. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  559. tbody.innerHTML = '';
  560. const allIfaces = state.interfaces || [];
  561. const allVlans = state.vlans || [];
  562. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  563. const filteredParents = parentIfaces.filter(parent => {
  564. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  565. if (query) {
  566. const matchName = parent.name.toLowerCase().includes(query);
  567. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  568. const matchRole = (parent.role || '').toLowerCase().includes(query);
  569. const matchType = (parent.type || '').toLowerCase().includes(query);
  570. const matchVlan = childVlans.some(v =>
  571. v.name.toLowerCase().includes(query) ||
  572. String(v.vlan_id).includes(query) ||
  573. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  574. (v.description || '').toLowerCase().includes(query)
  575. );
  576. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  577. }
  578. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  579. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  580. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  581. return true;
  582. });
  583. if (summary) {
  584. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  585. }
  586. if (filteredParents.length === 0) {
  587. emptyState?.classList.remove('hidden');
  588. return;
  589. }
  590. emptyState?.classList.add('hidden');
  591. filteredParents.forEach(parent => {
  592. const isUp = parent.state === 'UP';
  593. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  594. const hasVlans = childVlans.length > 0;
  595. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  596. const canHaveVlan = supportsVLAN(parent);
  597. const parentRow = document.createElement('tr');
  598. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  599. parentRow.innerHTML = `
  600. <td class="py-3 px-3 text-center">
  601. ${hasVlans ? `
  602. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  603. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  604. <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">
  605. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  606. </svg>
  607. </button>
  608. ` : `
  609. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  610. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  611. </div>
  612. `}
  613. </td>
  614. <td class="py-3 px-4">
  615. <div class="flex items-center space-x-2.5">
  616. <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">
  617. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  618. </div>
  619. <div>
  620. <div class="flex items-center gap-2">
  621. ${hasVlans ? `
  622. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400" onclick="toggleExpand('${parent.name}')">${parent.name}</span>
  623. <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>
  624. ` : `
  625. <span class="font-bold text-white text-sm">${parent.name}</span>
  626. <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>
  627. `}
  628. </div>
  629. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  630. </div>
  631. </div>
  632. </td>
  633. <td class="py-3 px-4 font-sans">
  634. <div class="flex items-center gap-1.5">
  635. <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>
  636. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  637. </div>
  638. </td>
  639. <td class="py-3 px-4">
  640. ${parent.ipv4 && parent.ipv4.length > 0
  641. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  642. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  643. }
  644. ${(() => {
  645. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  646. if (!c) return '';
  647. 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');
  648. 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>`;
  649. })()}
  650. </td>
  651. <td class="py-3 px-4 text-slate-400 text-[11px]">
  652. <div>${parent.mac || 'N/A'}</div>
  653. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  654. </td>
  655. <td class="py-3 px-4 text-[11px]">
  656. <div class="flex items-center space-x-2">
  657. <span class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  658. <span class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  659. </div>
  660. </td>
  661. <td class="py-3 px-4 font-sans">
  662. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  663. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  664. 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'
  665. }" title="Click to toggle link status">
  666. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  667. <span>${parent.state}</span>
  668. </button>
  669. </td>
  670. <td class="py-3 px-4 text-right space-x-2 font-sans">
  671. ${(() => {
  672. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  673. if (c) {
  674. 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>`;
  675. }
  676. 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>`;
  677. })()}
  678. ${canHaveVlan ? `
  679. <button onclick="openVlanModal('${parent.name}')"
  680. 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">
  681. + Add VLAN
  682. </button>
  683. ` : ''}
  684. <button onclick="openIfaceModal('${parent.name}')"
  685. 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">
  686. Configure
  687. </button>
  688. </td>
  689. `;
  690. tbody.appendChild(parentRow);
  691. if (isExpanded) {
  692. const drawerRow = document.createElement('tr');
  693. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  694. const drawerCell = document.createElement('td');
  695. drawerCell.colSpan = 8;
  696. drawerCell.className = 'p-0';
  697. drawerCell.innerHTML = `
  698. <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">
  699. <div class="flex items-center justify-between mb-3">
  700. <div class="flex items-center space-x-3">
  701. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  702. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  703. </span>
  704. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  705. ${childVlans.length} Attached
  706. </span>
  707. </div>
  708. <button onclick="openVlanModal('${parent.name}')"
  709. 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">
  710. <span>+ Create VLAN on ${parent.name}</span>
  711. </button>
  712. </div>
  713. ${childVlans.length === 0 ? `
  714. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  715. <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>
  716. <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">
  717. <span>+ Create Your First VLAN on ${parent.name}</span>
  718. </button>
  719. </div>
  720. ` : `
  721. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  722. <table class="w-full text-left text-xs font-mono">
  723. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  724. <tr>
  725. <th class="py-2.5 px-4">VLAN ID</th>
  726. <th class="py-2.5 px-4">Interface Device</th>
  727. <th class="py-2.5 px-4">Subnet Gateway</th>
  728. <th class="py-2.5 px-4">Role / Alias</th>
  729. <th class="py-2.5 px-4">MTU</th>
  730. <th class="py-2.5 px-4">Throughput</th>
  731. <th class="py-2.5 px-4">Status</th>
  732. <th class="py-2.5 px-4 text-right">Actions</th>
  733. </tr>
  734. </thead>
  735. <tbody class="divide-y divide-slate-800/70">
  736. ${childVlans.map(v => {
  737. const isVlanUp = v.state === 'UP';
  738. return `
  739. <tr class="hover:bg-slate-800/40 transition">
  740. <td class="py-2.5 px-4">
  741. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  742. VLAN ${v.vlan_id}
  743. </span>
  744. </td>
  745. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  746. <span class="text-cyan-500">└─</span>
  747. <span>${v.name}</span>
  748. </td>
  749. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  750. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  751. ${(() => {
  752. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  753. if (!c) return '';
  754. 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';
  755. 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>`;
  756. })()}
  757. </td>
  758. <td class="py-2.5 px-4 font-sans text-slate-300">
  759. <span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 mr-1.5">${v.role || 'VLAN'}</span>
  760. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  761. </td>
  762. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  763. <td class="py-2.5 px-4 text-[11px]">
  764. <span class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  765. <span class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  766. </td>
  767. <td class="py-2.5 px-4 font-sans">
  768. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  769. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  770. 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'
  771. }">
  772. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  773. <span>${v.state}</span>
  774. </button>
  775. </td>
  776. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  777. ${(() => {
  778. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  779. if (c) {
  780. 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>`;
  781. }
  782. 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>`;
  783. })()}
  784. <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>
  785. <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>
  786. </td>
  787. </tr>
  788. `;
  789. }).join('')}
  790. </tbody>
  791. </table>
  792. </div>
  793. `}
  794. </div>
  795. `;
  796. drawerRow.appendChild(drawerCell);
  797. tbody.appendChild(drawerRow);
  798. }
  799. });
  800. }
  801. // Render VLANs Dedicated View
  802. function renderVlansList() {
  803. const tbody = document.getElementById('vlans-table-body');
  804. if (!tbody) return;
  805. const emptyState = document.getElementById('vlans-empty-state');
  806. const countBadge = document.getElementById('vlans-table-count');
  807. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  808. tbody.innerHTML = '';
  809. const allVlans = state.vlans || [];
  810. if (countBadge) countBadge.innerText = allVlans.length;
  811. const filtered = allVlans.filter(v => {
  812. if (!query) return true;
  813. return v.name.toLowerCase().includes(query) ||
  814. String(v.vlan_id).includes(query) ||
  815. (v.description || '').toLowerCase().includes(query) ||
  816. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  817. });
  818. if (allVlans.length === 0) {
  819. emptyState.classList.remove('hidden');
  820. return;
  821. }
  822. emptyState.classList.add('hidden');
  823. filtered.forEach(v => {
  824. const isUp = v.state === 'UP';
  825. const tr = document.createElement('tr');
  826. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  827. tr.innerHTML = `
  828. <td class="py-3 px-4">
  829. <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">
  830. VLAN ${v.vlan_id}
  831. </span>
  832. </td>
  833. <td class="py-3 px-4 font-bold text-white">${v.name}</td>
  834. <td class="py-3 px-4 text-slate-300">
  835. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  836. </td>
  837. <td class="py-3 px-4 text-emerald-400 font-medium">
  838. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  839. </td>
  840. <td class="py-3 px-4 text-slate-300 font-sans">
  841. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  842. </td>
  843. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  844. <td class="py-3 px-4 font-sans">
  845. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  846. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  847. 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'
  848. }">
  849. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  850. <span>${v.state}</span>
  851. </button>
  852. </td>
  853. <td class="py-3 px-4 text-right space-x-2 font-sans">
  854. <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>
  855. <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>
  856. </td>
  857. `;
  858. tbody.appendChild(tr);
  859. });
  860. }
  861. // Toggle interface UP / DOWN
  862. async function toggleInterfaceState(name, newState) {
  863. try {
  864. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  865. method: 'POST',
  866. headers: { 'Content-Type': 'application/json' },
  867. body: JSON.stringify({ state: newState })
  868. });
  869. const data = await res.json();
  870. if (res.ok) {
  871. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  872. fetchData(false);
  873. } else {
  874. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  875. }
  876. } catch (err) {
  877. showToast('Error', err.message, 'error');
  878. }
  879. }
  880. // ---------------- MikroTik Flag & Utilities ----------------
  881. function renderMikroTikFlag(running, disabled) {
  882. if (running) {
  883. 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>`;
  884. }
  885. if (disabled) {
  886. 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>`;
  887. }
  888. 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>`;
  889. }
  890. function copyToClipboard(text, label = 'Text') {
  891. navigator.clipboard.writeText(text).then(() => {
  892. showToast('Copied', `${label} copied to clipboard`, 'success');
  893. }).catch(() => {
  894. prompt('Copy value:', text);
  895. });
  896. }
  897. // ======================== PPPoE Multi-Instance ========================
  898. async function loadPPPoE(populateInputs = true) {
  899. try {
  900. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  901. const list = await res.json();
  902. state.pppoeList = Array.isArray(list) ? list : [];
  903. const badge = document.getElementById('pppoe-count-badge');
  904. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  905. const tbody = document.getElementById('pppoe-table-body');
  906. const empty = document.getElementById('pppoe-empty');
  907. if (!tbody) return;
  908. tbody.innerHTML = '';
  909. if (state.pppoeList.length === 0) {
  910. if (empty) empty.classList.remove('hidden');
  911. } else {
  912. if (empty) empty.classList.add('hidden');
  913. state.pppoeList.forEach(inst => {
  914. const tr = document.createElement('tr');
  915. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  916. tr.innerHTML = `
  917. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  918. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  919. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.interface}</td>
  920. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  921. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  922. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  923. <td class="py-2.5 px-3 text-center">
  924. <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'}">
  925. ${inst.default_route ? 'Yes' : 'No'}
  926. </span>
  927. </td>
  928. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  929. ${inst.running ? `
  930. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  931. ` : `
  932. <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>
  933. `}
  934. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  935. ${inst.disabled ? 'Enable' : 'Disable'}
  936. </button>
  937. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  938. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  939. </td>
  940. `;
  941. tbody.appendChild(tr);
  942. });
  943. }
  944. } catch (err) {
  945. console.error('Failed to load PPPoE:', err);
  946. }
  947. }
  948. function openAddPPPoEModal() {
  949. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  950. document.getElementById('pppoe-modal-edit-orig').value = '';
  951. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  952. document.getElementById('pppoe-modal-name').readOnly = false;
  953. document.getElementById('pppoe-modal-user').value = '';
  954. document.getElementById('pppoe-modal-pass').value = '';
  955. document.getElementById('pppoe-modal-service').value = '';
  956. document.getElementById('pppoe-modal-mtu').value = '1492';
  957. document.getElementById('pppoe-modal-defroute').checked = true;
  958. document.getElementById('pppoe-modal-reconnect').checked = true;
  959. document.getElementById('pppoe-modal-disabled').checked = false;
  960. // Populate interfaces
  961. const sel = document.getElementById('pppoe-modal-iface');
  962. sel.innerHTML = '';
  963. (state.interfaces || []).forEach(i => {
  964. if (i.name === 'lo') return;
  965. const opt = document.createElement('option');
  966. opt.value = i.name;
  967. opt.innerText = `${i.name} (${i.role || i.type})`;
  968. sel.appendChild(opt);
  969. });
  970. document.getElementById('pppoe-modal').classList.remove('hidden');
  971. }
  972. function openEditPPPoEModal(name) {
  973. const inst = (state.pppoeList || []).find(i => i.name === name);
  974. if (!inst) return;
  975. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  976. document.getElementById('pppoe-modal-edit-orig').value = name;
  977. document.getElementById('pppoe-modal-name').value = inst.name;
  978. document.getElementById('pppoe-modal-name').readOnly = true;
  979. document.getElementById('pppoe-modal-user').value = inst.username || '';
  980. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  981. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  982. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  983. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  984. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  985. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  986. const sel = document.getElementById('pppoe-modal-iface');
  987. sel.innerHTML = '';
  988. (state.interfaces || []).forEach(i => {
  989. if (i.name === 'lo') return;
  990. const opt = document.createElement('option');
  991. opt.value = i.name;
  992. opt.innerText = `${i.name} (${i.role || i.type})`;
  993. if (i.name === inst.interface) opt.selected = true;
  994. sel.appendChild(opt);
  995. });
  996. document.getElementById('pppoe-modal').classList.remove('hidden');
  997. }
  998. function closePPPoEModal() {
  999. document.getElementById('pppoe-modal').classList.add('hidden');
  1000. }
  1001. async function submitSavePPPoE(e) {
  1002. e.preventDefault();
  1003. const name = document.getElementById('pppoe-modal-name').value.trim();
  1004. const iface = document.getElementById('pppoe-modal-iface').value;
  1005. const user = document.getElementById('pppoe-modal-user').value.trim();
  1006. const pass = document.getElementById('pppoe-modal-pass').value;
  1007. const service = document.getElementById('pppoe-modal-service').value.trim();
  1008. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1009. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1010. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1011. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1012. try {
  1013. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1014. method: 'POST',
  1015. headers: { 'Content-Type': 'application/json' },
  1016. body: JSON.stringify({
  1017. name,
  1018. interface: iface,
  1019. username: user,
  1020. password: pass,
  1021. service_name: service,
  1022. mtu,
  1023. default_route: defRoute,
  1024. auto_reconnect: reconnect,
  1025. disabled
  1026. })
  1027. });
  1028. if (res.ok) {
  1029. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1030. closePPPoEModal();
  1031. loadPPPoE(false);
  1032. fetchData(false);
  1033. } else {
  1034. const err = await res.json();
  1035. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1036. }
  1037. } catch (err) {
  1038. showToast('Error', err.message, 'error');
  1039. }
  1040. }
  1041. async function connectPPPoEInstance(name) {
  1042. try {
  1043. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1044. if (res.ok) {
  1045. showToast('Connecting', `Dialing ${name}...`, 'info');
  1046. setTimeout(() => loadPPPoE(false), 2000);
  1047. }
  1048. } catch (err) {
  1049. showToast('Error', err.message, 'error');
  1050. }
  1051. }
  1052. async function disconnectPPPoEInstance(name) {
  1053. try {
  1054. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1055. if (res.ok) {
  1056. showToast('Disconnected', `${name} session terminated`, 'info');
  1057. setTimeout(() => loadPPPoE(false), 1000);
  1058. }
  1059. } catch (err) {
  1060. showToast('Error', err.message, 'error');
  1061. }
  1062. }
  1063. async function togglePPPoEState(name, enable) {
  1064. try {
  1065. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1066. method: 'POST',
  1067. headers: { 'Content-Type': 'application/json' },
  1068. body: JSON.stringify({ enabled: enable })
  1069. });
  1070. if (res.ok) {
  1071. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1072. loadPPPoE(false);
  1073. }
  1074. } catch (err) {
  1075. showToast('Error', err.message, 'error');
  1076. }
  1077. }
  1078. async function deletePPPoEInstance(name) {
  1079. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1080. try {
  1081. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1082. if (res.ok) {
  1083. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1084. loadPPPoE(false);
  1085. fetchData(false);
  1086. }
  1087. } catch (err) {
  1088. showToast('Error', err.message, 'error');
  1089. }
  1090. }
  1091. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1092. state.wgSubTab = 'ifaces';
  1093. function switchWGSubTab(tab) {
  1094. state.wgSubTab = tab;
  1095. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1096. const peersPanel = document.getElementById('wg-subtab-peers');
  1097. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1098. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1099. if (tab === 'ifaces') {
  1100. ifacesPanel?.classList.remove('hidden');
  1101. peersPanel?.classList.add('hidden');
  1102. 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';
  1103. 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';
  1104. } else {
  1105. ifacesPanel?.classList.add('hidden');
  1106. peersPanel?.classList.remove('hidden');
  1107. 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';
  1108. 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';
  1109. renderWGPeers();
  1110. }
  1111. }
  1112. async function loadWireGuard(populateInputs = true) {
  1113. try {
  1114. const [ifacesRes, peersRes] = await Promise.all([
  1115. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1116. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1117. ]);
  1118. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1119. const peers = peersRes.ok ? await peersRes.json() : [];
  1120. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1121. state.wgPeers = Array.isArray(peers) ? peers : [];
  1122. // Badges
  1123. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1124. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1125. const peersCountBadge = document.getElementById('wg-peers-count');
  1126. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1127. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1128. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1129. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1130. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1131. // Render Interfaces
  1132. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1133. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1134. if (ifacesTbody) {
  1135. ifacesTbody.innerHTML = '';
  1136. if (state.wgInterfaces.length === 0) {
  1137. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1138. } else {
  1139. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1140. state.wgInterfaces.forEach(iface => {
  1141. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1142. const tr = document.createElement('tr');
  1143. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1144. tr.innerHTML = `
  1145. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1146. <td class="py-2.5 px-3">
  1147. <div class="flex items-center gap-1.5">
  1148. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1149. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1150. </div>
  1151. </td>
  1152. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1153. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1154. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1155. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1156. ${(iface.public_key || '').substring(0, 10)}... 📋
  1157. </span>
  1158. </td>
  1159. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1160. <td class="py-2.5 px-3 text-center">
  1161. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1162. </td>
  1163. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1164. ${iface.running ? `
  1165. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1166. ` : `
  1167. <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>
  1168. `}
  1169. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1170. ${iface.disabled ? 'Enable' : 'Disable'}
  1171. </button>
  1172. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1173. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1174. </td>
  1175. `;
  1176. ifacesTbody.appendChild(tr);
  1177. });
  1178. }
  1179. }
  1180. // Populate filter dropdown in peers tab
  1181. const filterSel = document.getElementById('wg-peers-filter-iface');
  1182. if (filterSel) {
  1183. const currentVal = filterSel.value;
  1184. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1185. state.wgInterfaces.forEach(i => {
  1186. const opt = document.createElement('option');
  1187. opt.value = i.name;
  1188. opt.innerText = i.name;
  1189. if (i.name === currentVal) opt.selected = true;
  1190. filterSel.appendChild(opt);
  1191. });
  1192. }
  1193. renderWGPeers();
  1194. } catch (err) {
  1195. console.error('Failed to load WireGuard:', err);
  1196. }
  1197. }
  1198. function renderWGPeers() {
  1199. const filterSel = document.getElementById('wg-peers-filter-iface');
  1200. const selectedIface = filterSel ? filterSel.value : '';
  1201. const tbody = document.getElementById('wg-peers-table-body');
  1202. const empty = document.getElementById('wg-peers-empty');
  1203. if (!tbody) return;
  1204. tbody.innerHTML = '';
  1205. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1206. if (filtered.length === 0) {
  1207. if (empty) empty.classList.remove('hidden');
  1208. } else {
  1209. if (empty) empty.classList.add('hidden');
  1210. filtered.forEach(p => {
  1211. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1212. const tr = document.createElement('tr');
  1213. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1214. tr.innerHTML = `
  1215. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1216. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1217. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1218. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1219. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1220. ${(p.public_key || '').substring(0, 10)}... 📋
  1221. </span>
  1222. </td>
  1223. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1224. <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>
  1225. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1226. <td class="py-2.5 px-3 font-mono text-[11px]">
  1227. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1228. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1229. </td>
  1230. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1231. <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">
  1232. ${p.disabled ? 'Enable' : 'Disable'}
  1233. </button>
  1234. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1235. <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>
  1236. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1237. </td>
  1238. `;
  1239. tbody.appendChild(tr);
  1240. });
  1241. }
  1242. }
  1243. function openAddWGInterfaceModal() {
  1244. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1245. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1246. const nameEl = document.getElementById('wg-iface-modal-name');
  1247. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1248. nameEl.readOnly = false;
  1249. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1250. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1251. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1252. document.getElementById('wg-iface-modal-comment').value = '';
  1253. document.getElementById('wg-iface-modal-pubkey').value = '';
  1254. document.getElementById('wg-iface-modal-privkey').value = '';
  1255. document.getElementById('wg-iface-modal-disabled').checked = false;
  1256. generateWGInterfaceKeys();
  1257. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1258. }
  1259. function openEditWGInterfaceModal(name) {
  1260. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1261. if (!iface) return;
  1262. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1263. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1264. const nameEl = document.getElementById('wg-iface-modal-name');
  1265. nameEl.value = iface.name;
  1266. nameEl.readOnly = false; // ALLOW RENAMING
  1267. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1268. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1269. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1270. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1271. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1272. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1273. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1274. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1275. }
  1276. function closeAddWGInterfaceModal() {
  1277. document.getElementById('wg-iface-modal').classList.add('hidden');
  1278. }
  1279. async function generateWGInterfaceKeys() {
  1280. try {
  1281. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1282. const keys = await res.json();
  1283. if (res.ok) {
  1284. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1285. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1286. }
  1287. } catch (err) {
  1288. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1289. }
  1290. }
  1291. async function onWGInterfacePrivKeyInput() {
  1292. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1293. if (!privKey) return;
  1294. try {
  1295. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1296. method: 'POST',
  1297. headers: { 'Content-Type': 'application/json' },
  1298. body: JSON.stringify({ private_key: privKey })
  1299. });
  1300. if (res.ok) {
  1301. const data = await res.json();
  1302. if (data.public_key) {
  1303. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1304. }
  1305. }
  1306. } catch (err) {
  1307. // Ignore while typing
  1308. }
  1309. }
  1310. function toggleWGPrivKeyVisibility() {
  1311. const el = document.getElementById('wg-iface-modal-privkey');
  1312. const btn = document.getElementById('btn-toggle-wg-privkey');
  1313. if (el.type === 'password') {
  1314. el.type = 'text';
  1315. btn.innerText = '🙈 Hide';
  1316. } else {
  1317. el.type = 'password';
  1318. btn.innerText = '👁️ Show';
  1319. }
  1320. }
  1321. function copyWGInterfacePubKey() {
  1322. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1323. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1324. }
  1325. async function submitSaveWGInterface(e) {
  1326. e.preventDefault();
  1327. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1328. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1329. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1330. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1331. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1332. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1333. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1334. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1335. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1336. try {
  1337. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1338. method: 'POST',
  1339. headers: { 'Content-Type': 'application/json' },
  1340. body: JSON.stringify({
  1341. orig_name: origName,
  1342. name,
  1343. listen_port: port,
  1344. address: addr,
  1345. mtu,
  1346. comment,
  1347. public_key: pub,
  1348. private_key: priv,
  1349. disabled
  1350. })
  1351. });
  1352. const data = await res.json();
  1353. if (res.ok) {
  1354. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1355. closeAddWGInterfaceModal();
  1356. loadWireGuard(false);
  1357. fetchData(false);
  1358. } else {
  1359. showToast('Error', data.error || 'Failed to save interface', 'error');
  1360. }
  1361. } catch (err) {
  1362. showToast('Error', err.message, 'error');
  1363. }
  1364. }
  1365. async function startWGInterface(name) {
  1366. try {
  1367. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1368. if (res.ok) {
  1369. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1370. loadWireGuard(false);
  1371. fetchData(false);
  1372. }
  1373. } catch (err) {
  1374. showToast('Error', err.message, 'error');
  1375. }
  1376. }
  1377. async function stopWGInterface(name) {
  1378. try {
  1379. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1380. if (res.ok) {
  1381. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1382. loadWireGuard(false);
  1383. fetchData(false);
  1384. }
  1385. } catch (err) {
  1386. showToast('Error', err.message, 'error');
  1387. }
  1388. }
  1389. async function toggleWGInterfaceState(name, enable) {
  1390. try {
  1391. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1392. method: 'POST',
  1393. headers: { 'Content-Type': 'application/json' },
  1394. body: JSON.stringify({ enabled: enable })
  1395. });
  1396. if (res.ok) {
  1397. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1398. loadWireGuard(false);
  1399. fetchData(false);
  1400. }
  1401. } catch (err) {
  1402. showToast('Error', err.message, 'error');
  1403. }
  1404. }
  1405. async function deleteWGInterface(name) {
  1406. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1407. try {
  1408. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1409. if (res.ok) {
  1410. showToast('Deleted', `Interface ${name} removed`, 'success');
  1411. loadWireGuard(false);
  1412. fetchData(false);
  1413. }
  1414. } catch (err) {
  1415. showToast('Error', err.message, 'error');
  1416. }
  1417. }
  1418. function populateWGPeerIfaceSelect(selectedIface = '') {
  1419. const sel = document.getElementById('wg-peer-modal-iface');
  1420. if (!sel) return;
  1421. sel.innerHTML = '';
  1422. (state.wgInterfaces || []).forEach(i => {
  1423. const opt = document.createElement('option');
  1424. opt.value = i.name;
  1425. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1426. if (i.name === selectedIface) opt.selected = true;
  1427. sel.appendChild(opt);
  1428. });
  1429. }
  1430. function openAddWGPeerModal() {
  1431. if ((state.wgInterfaces || []).length === 0) {
  1432. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1433. openAddWGInterfaceModal();
  1434. return;
  1435. }
  1436. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  1437. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  1438. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  1439. populateWGPeerIfaceSelect();
  1440. document.getElementById('wg-peer-modal-name').value = '';
  1441. document.getElementById('wg-peer-modal-pubkey').value = '';
  1442. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1443. document.getElementById('wg-peer-modal-endpoint').value = '';
  1444. document.getElementById('wg-peer-modal-port').value = '';
  1445. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1446. document.getElementById('wg-peer-modal-preshared').value = '';
  1447. document.getElementById('wg-peer-modal-disabled').checked = false;
  1448. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1449. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1450. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1451. }
  1452. function openEditWGPeerModal(ifaceName, pubKey) {
  1453. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  1454. if (!peer) {
  1455. showToast('Not Found', 'Peer not found', 'warning');
  1456. return;
  1457. }
  1458. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  1459. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  1460. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  1461. populateWGPeerIfaceSelect(peer.interface);
  1462. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  1463. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  1464. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  1465. document.getElementById('wg-peer-modal-endpoint').value = peer.endpoint_address || '';
  1466. document.getElementById('wg-peer-modal-port').value = peer.endpoint_port || '';
  1467. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  1468. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  1469. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  1470. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1471. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1472. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1473. }
  1474. function closeAddWGPeerModal() {
  1475. document.getElementById('wg-peer-modal').classList.add('hidden');
  1476. }
  1477. async function generatePeerKeypairHelper() {
  1478. try {
  1479. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1480. const keys = await res.json();
  1481. if (res.ok) {
  1482. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  1483. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  1484. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  1485. checkWGPeerKeyValidity();
  1486. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  1487. }
  1488. } catch (err) {
  1489. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1490. }
  1491. }
  1492. function copyGeneratedPeerPrivKey() {
  1493. const priv = document.getElementById('wg-peer-gen-privkey').value;
  1494. if (priv) copyToClipboard(priv, 'Client Private Key');
  1495. }
  1496. async function generatePeerPSK() {
  1497. try {
  1498. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1499. const keys = await res.json();
  1500. if (res.ok && keys.private_key) {
  1501. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  1502. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  1503. }
  1504. } catch (err) {
  1505. showToast('Error', err.message, 'error');
  1506. }
  1507. }
  1508. function checkWGPeerKeyValidity() {
  1509. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  1510. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1511. const warningEl = document.getElementById('wg-peer-key-warning');
  1512. if (!warningEl) return;
  1513. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  1514. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  1515. warningEl.classList.remove('hidden');
  1516. } else {
  1517. warningEl.classList.add('hidden');
  1518. }
  1519. }
  1520. async function submitSaveWGPeer(e) {
  1521. e.preventDefault();
  1522. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  1523. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  1524. const iface = document.getElementById('wg-peer-modal-iface').value;
  1525. const name = document.getElementById('wg-peer-modal-name').value.trim();
  1526. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1527. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  1528. .split(',')
  1529. .map(s => s.trim())
  1530. .filter(s => s.length > 0);
  1531. const epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  1532. const epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  1533. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  1534. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  1535. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  1536. // Validation
  1537. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  1538. if (targetIface && targetIface.public_key === pub) {
  1539. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  1540. return;
  1541. }
  1542. try {
  1543. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  1544. method: 'POST',
  1545. headers: { 'Content-Type': 'application/json' },
  1546. body: JSON.stringify({
  1547. orig_interface: origIface,
  1548. orig_public_key: origPubKey,
  1549. interface: iface,
  1550. name,
  1551. public_key: pub,
  1552. allowed_ips: allowed,
  1553. endpoint_address: epHost,
  1554. endpoint_port: epPort,
  1555. persistent_keepalive: keepalive,
  1556. preshared_key: psk,
  1557. disabled
  1558. })
  1559. });
  1560. const data = await res.json();
  1561. if (res.ok) {
  1562. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  1563. closeAddWGPeerModal();
  1564. loadWireGuard(false);
  1565. } else {
  1566. showToast('Error', data.error || 'Failed to save peer', 'error');
  1567. }
  1568. } catch (err) {
  1569. showToast('Error', err.message, 'error');
  1570. }
  1571. }
  1572. async function toggleWGPeerState(iface, pubkey, enable) {
  1573. try {
  1574. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  1575. method: 'POST',
  1576. headers: { 'Content-Type': 'application/json' },
  1577. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  1578. });
  1579. const data = await res.json();
  1580. if (res.ok) {
  1581. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  1582. loadWireGuard(false);
  1583. } else {
  1584. showToast('Error', data.error || 'Failed to update peer state', 'error');
  1585. }
  1586. } catch (err) {
  1587. showToast('Error', err.message, 'error');
  1588. }
  1589. }
  1590. async function deleteWGPeer(iface, pubkey) {
  1591. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  1592. try {
  1593. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  1594. method: 'POST',
  1595. headers: { 'Content-Type': 'application/json' },
  1596. body: JSON.stringify({ interface: iface, public_key: pubkey })
  1597. });
  1598. const data = await res.json();
  1599. if (res.ok) {
  1600. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  1601. loadWireGuard(false);
  1602. } else {
  1603. showToast('Error', data.error || 'Failed to remove peer', 'error');
  1604. }
  1605. } catch (err) {
  1606. showToast('Error', err.message, 'error');
  1607. }
  1608. }
  1609. // ======================== IPSec Multi-Tunnel ========================
  1610. async function loadIPSec(populateInputs = true) {
  1611. try {
  1612. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1613. const list = await res.json();
  1614. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1615. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1616. const badge = document.getElementById('ipsec-sas-badge');
  1617. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1618. const tbody = document.getElementById('ipsec-table-body');
  1619. const empty = document.getElementById('ipsec-empty');
  1620. if (!tbody) return;
  1621. tbody.innerHTML = '';
  1622. if (state.ipsecTunnels.length === 0) {
  1623. if (empty) empty.classList.remove('hidden');
  1624. } else {
  1625. if (empty) empty.classList.add('hidden');
  1626. state.ipsecTunnels.forEach(c => {
  1627. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1628. const tr = document.createElement('tr');
  1629. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1630. tr.innerHTML = `
  1631. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isEstablished, c.disabled)}</td>
  1632. <td class="py-2.5 px-4 font-bold text-white">${c.name}</td>
  1633. <td class="py-2.5 px-4 text-emerald-400 font-mono">${c.local_subnet || '-'}</td>
  1634. <td class="py-2.5 px-4 text-slate-300 font-mono">${c.remote_addrs || '-'}</td>
  1635. <td class="py-2.5 px-4 text-cyan-400 font-mono">${c.remote_subnet || '-'}</td>
  1636. <td class="py-2.5 px-4 font-sans">
  1637. <span class="px-2 py-0.5 rounded-full text-[10px] font-semibold ${
  1638. isEstablished ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-slate-800 text-slate-400'
  1639. }">${c.status || (isEstablished ? 'ESTABLISHED' : 'DISCONNECTED')}</span>
  1640. </td>
  1641. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  1642. ${isEstablished ? `
  1643. <button onclick="stopIPSecTunnel('${c.name}')" class="text-xs text-rose-400 hover:text-rose-300">Terminate</button>
  1644. ` : `
  1645. <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>
  1646. `}
  1647. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1648. ${c.disabled ? 'Enable' : 'Disable'}
  1649. </button>
  1650. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1651. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1652. </td>
  1653. `;
  1654. tbody.appendChild(tr);
  1655. });
  1656. }
  1657. } catch (err) {
  1658. console.error('Failed to load IPSec:', err);
  1659. }
  1660. }
  1661. function openAddIPSecModal() {
  1662. document.getElementById('ipsec-modal-title').innerText = 'Configure IPSec IKEv2 Tunnel';
  1663. document.getElementById('ipsec-modal-name').value = `ipsec-${(state.ipsecTunnels || []).length + 1}`;
  1664. document.getElementById('ipsec-modal-name').readOnly = false;
  1665. document.getElementById('ipsec-modal-localts').value = '192.168.10.0/24';
  1666. document.getElementById('ipsec-modal-remotets').value = '192.168.20.0/24';
  1667. document.getElementById('ipsec-modal-remotegw').value = '';
  1668. document.getElementById('ipsec-modal-psk').value = '';
  1669. document.getElementById('ipsec-modal-ikeprop').value = 'aes256-sha256-modp2048,default';
  1670. document.getElementById('ipsec-modal-espprop').value = 'aes256-sha256-modp2048,default';
  1671. document.getElementById('ipsec-modal-autostart').checked = true;
  1672. document.getElementById('ipsec-modal-disabled').checked = false;
  1673. document.getElementById('ipsec-modal').classList.remove('hidden');
  1674. }
  1675. function openEditIPSecModal(name) {
  1676. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  1677. if (!conn) return;
  1678. document.getElementById('ipsec-modal-title').innerText = `Edit IPSec Tunnel: ${name}`;
  1679. document.getElementById('ipsec-modal-name').value = conn.name;
  1680. document.getElementById('ipsec-modal-name').readOnly = true;
  1681. document.getElementById('ipsec-modal-localts').value = conn.local_subnet || '';
  1682. document.getElementById('ipsec-modal-remotets').value = conn.remote_subnet || '';
  1683. document.getElementById('ipsec-modal-remotegw').value = conn.remote_addrs || '';
  1684. document.getElementById('ipsec-modal-psk').value = conn.preshared_key || '';
  1685. document.getElementById('ipsec-modal-ikeprop').value = conn.ike_proposals || 'aes256-sha256-modp2048,default';
  1686. document.getElementById('ipsec-modal-espprop').value = conn.esp_proposals || 'aes256-sha256-modp2048,default';
  1687. document.getElementById('ipsec-modal-autostart').checked = conn.auto_start ?? true;
  1688. document.getElementById('ipsec-modal-disabled').checked = !!conn.disabled;
  1689. document.getElementById('ipsec-modal').classList.remove('hidden');
  1690. }
  1691. function closeAddIPSecModal() {
  1692. document.getElementById('ipsec-modal').classList.add('hidden');
  1693. }
  1694. async function submitSaveIPSec(e) {
  1695. e.preventDefault();
  1696. const name = document.getElementById('ipsec-modal-name').value.trim();
  1697. const localts = document.getElementById('ipsec-modal-localts').value.trim();
  1698. const remotets = document.getElementById('ipsec-modal-remotets').value.trim();
  1699. const remotegw = document.getElementById('ipsec-modal-remotegw').value.trim();
  1700. const psk = document.getElementById('ipsec-modal-psk').value;
  1701. const ike = document.getElementById('ipsec-modal-ikeprop').value.trim();
  1702. const esp = document.getElementById('ipsec-modal-espprop').value.trim();
  1703. const autostart = document.getElementById('ipsec-modal-autostart').checked;
  1704. const disabled = document.getElementById('ipsec-modal-disabled').checked;
  1705. try {
  1706. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  1707. method: 'POST',
  1708. headers: { 'Content-Type': 'application/json' },
  1709. body: JSON.stringify({
  1710. name,
  1711. local_addrs: '%any',
  1712. remote_addrs: remotegw,
  1713. local_subnet: localts,
  1714. remote_subnet: remotets,
  1715. preshared_key: psk,
  1716. ike_proposals: ike,
  1717. esp_proposals: esp,
  1718. auto_start: autostart,
  1719. disabled
  1720. })
  1721. });
  1722. if (res.ok) {
  1723. showToast('IPSec Saved', `Tunnel ${name} configured`, 'success');
  1724. closeAddIPSecModal();
  1725. loadIPSec(false);
  1726. fetchData(false);
  1727. }
  1728. } catch (err) {
  1729. showToast('Error', err.message, 'error');
  1730. }
  1731. }
  1732. async function startIPSecTunnel(name) {
  1733. try {
  1734. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1735. if (res.ok) {
  1736. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  1737. setTimeout(() => loadIPSec(false), 2000);
  1738. }
  1739. } catch (err) {
  1740. showToast('Error', err.message, 'error');
  1741. }
  1742. }
  1743. async function stopIPSecTunnel(name) {
  1744. try {
  1745. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1746. if (res.ok) {
  1747. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  1748. loadIPSec(false);
  1749. }
  1750. } catch (err) {
  1751. showToast('Error', err.message, 'error');
  1752. }
  1753. }
  1754. async function toggleIPSecState(name, enable) {
  1755. try {
  1756. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  1757. method: 'POST',
  1758. headers: { 'Content-Type': 'application/json' },
  1759. body: JSON.stringify({ enabled: enable })
  1760. });
  1761. if (res.ok) {
  1762. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  1763. loadIPSec(false);
  1764. }
  1765. } catch (err) {
  1766. showToast('Error', err.message, 'error');
  1767. }
  1768. }
  1769. async function deleteIPSecConn(name) {
  1770. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  1771. try {
  1772. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1773. if (res.ok) {
  1774. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  1775. loadIPSec(false);
  1776. fetchData(false);
  1777. }
  1778. } catch (err) {
  1779. showToast('Error', err.message, 'error');
  1780. }
  1781. }
  1782. // ======================== L2TP Multi-Instance ========================
  1783. async function loadL2TP(populateInputs = true) {
  1784. try {
  1785. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  1786. const list = await res.json();
  1787. state.l2tpList = Array.isArray(list) ? list : [];
  1788. const badge = document.getElementById('l2tp-count-badge');
  1789. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  1790. const tbody = document.getElementById('l2tp-table-body');
  1791. const empty = document.getElementById('l2tp-empty');
  1792. if (!tbody) return;
  1793. tbody.innerHTML = '';
  1794. if (state.l2tpList.length === 0) {
  1795. if (empty) empty.classList.remove('hidden');
  1796. } else {
  1797. if (empty) empty.classList.add('hidden');
  1798. state.l2tpList.forEach(inst => {
  1799. const tr = document.createElement('tr');
  1800. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1801. tr.innerHTML = `
  1802. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1803. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1804. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.connect_to}</td>
  1805. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1806. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1807. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1808. <td class="py-2.5 px-3 text-center">
  1809. <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'}">
  1810. ${inst.default_route ? 'Yes' : 'No'}
  1811. </span>
  1812. </td>
  1813. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1814. ${inst.running ? `
  1815. <button onclick="disconnectL2TPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1816. ` : `
  1817. <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>
  1818. `}
  1819. <button onclick="toggleL2TPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1820. ${inst.disabled ? 'Enable' : 'Disable'}
  1821. </button>
  1822. <button onclick="openEditL2TPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1823. <button onclick="deleteL2TPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1824. </td>
  1825. `;
  1826. tbody.appendChild(tr);
  1827. });
  1828. }
  1829. } catch (err) {
  1830. console.error('Failed to load L2TP:', err);
  1831. }
  1832. }
  1833. function openAddL2TPModal() {
  1834. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  1835. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  1836. document.getElementById('l2tp-modal-name').readOnly = false;
  1837. document.getElementById('l2tp-modal-server').value = '';
  1838. document.getElementById('l2tp-modal-user').value = '';
  1839. document.getElementById('l2tp-modal-pass').value = '';
  1840. document.getElementById('l2tp-modal-ipsec').value = '';
  1841. document.getElementById('l2tp-modal-defroute').checked = true;
  1842. document.getElementById('l2tp-modal-disabled').checked = false;
  1843. document.getElementById('l2tp-modal').classList.remove('hidden');
  1844. }
  1845. function openEditL2TPModal(name) {
  1846. const inst = (state.l2tpList || []).find(i => i.name === name);
  1847. if (!inst) return;
  1848. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  1849. document.getElementById('l2tp-modal-name').value = inst.name;
  1850. document.getElementById('l2tp-modal-name').readOnly = true;
  1851. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  1852. document.getElementById('l2tp-modal-user').value = inst.username || '';
  1853. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  1854. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  1855. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  1856. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  1857. document.getElementById('l2tp-modal').classList.remove('hidden');
  1858. }
  1859. function closeL2TPModal() {
  1860. document.getElementById('l2tp-modal').classList.add('hidden');
  1861. }
  1862. async function submitSaveL2TP(e) {
  1863. e.preventDefault();
  1864. const name = document.getElementById('l2tp-modal-name').value.trim();
  1865. const server = document.getElementById('l2tp-modal-server').value.trim();
  1866. const user = document.getElementById('l2tp-modal-user').value.trim();
  1867. const pass = document.getElementById('l2tp-modal-pass').value;
  1868. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  1869. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  1870. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  1871. try {
  1872. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  1873. method: 'POST',
  1874. headers: { 'Content-Type': 'application/json' },
  1875. body: JSON.stringify({
  1876. name,
  1877. connect_to: server,
  1878. username: user,
  1879. password: pass,
  1880. ipsec_secret: ipsec,
  1881. default_route: defRoute,
  1882. disabled
  1883. })
  1884. });
  1885. if (res.ok) {
  1886. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  1887. closeL2TPModal();
  1888. loadL2TP(false);
  1889. fetchData(false);
  1890. }
  1891. } catch (err) {
  1892. showToast('Error', err.message, 'error');
  1893. }
  1894. }
  1895. async function connectL2TPInstance(name) {
  1896. try {
  1897. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1898. if (res.ok) {
  1899. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  1900. setTimeout(() => loadL2TP(false), 2000);
  1901. }
  1902. } catch (err) {
  1903. showToast('Error', err.message, 'error');
  1904. }
  1905. }
  1906. async function disconnectL2TPInstance(name) {
  1907. try {
  1908. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1909. if (res.ok) {
  1910. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  1911. loadL2TP(false);
  1912. }
  1913. } catch (err) {
  1914. showToast('Error', err.message, 'error');
  1915. }
  1916. }
  1917. async function toggleL2TPState(name, enable) {
  1918. try {
  1919. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  1920. method: 'POST',
  1921. headers: { 'Content-Type': 'application/json' },
  1922. body: JSON.stringify({ enabled: enable })
  1923. });
  1924. if (res.ok) {
  1925. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1926. loadL2TP(false);
  1927. }
  1928. } catch (err) {
  1929. showToast('Error', err.message, 'error');
  1930. }
  1931. }
  1932. async function deleteL2TPInstance(name) {
  1933. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  1934. try {
  1935. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1936. if (res.ok) {
  1937. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  1938. loadL2TP(false);
  1939. fetchData(false);
  1940. }
  1941. } catch (err) {
  1942. showToast('Error', err.message, 'error');
  1943. }
  1944. }
  1945. // ======================== PPTP Multi-Instance ========================
  1946. async function loadPPTP(populateInputs = true) {
  1947. try {
  1948. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  1949. const list = await res.json();
  1950. state.pptpList = Array.isArray(list) ? list : [];
  1951. const badge = document.getElementById('pptp-count-badge');
  1952. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  1953. const tbody = document.getElementById('pptp-table-body');
  1954. const empty = document.getElementById('pptp-empty');
  1955. if (!tbody) return;
  1956. tbody.innerHTML = '';
  1957. if (state.pptpList.length === 0) {
  1958. if (empty) empty.classList.remove('hidden');
  1959. } else {
  1960. if (empty) empty.classList.add('hidden');
  1961. state.pptpList.forEach(inst => {
  1962. const tr = document.createElement('tr');
  1963. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1964. tr.innerHTML = `
  1965. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1966. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1967. <td class="py-2.5 px-3 text-purple-400 font-mono">${inst.connect_to}</td>
  1968. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1969. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1970. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1971. <td class="py-2.5 px-3 text-center">
  1972. <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'}">
  1973. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  1974. </span>
  1975. </td>
  1976. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1977. ${inst.running ? `
  1978. <button onclick="disconnectPPTPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1979. ` : `
  1980. <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>
  1981. `}
  1982. <button onclick="togglePPTPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1983. ${inst.disabled ? 'Enable' : 'Disable'}
  1984. </button>
  1985. <button onclick="openEditPPTPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1986. <button onclick="deletePPTPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1987. </td>
  1988. `;
  1989. tbody.appendChild(tr);
  1990. });
  1991. }
  1992. } catch (err) {
  1993. console.error('Failed to load PPTP:', err);
  1994. }
  1995. }
  1996. function openAddPPTPModal() {
  1997. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  1998. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  1999. document.getElementById('pptp-modal-name').readOnly = false;
  2000. document.getElementById('pptp-modal-server').value = '';
  2001. document.getElementById('pptp-modal-user').value = '';
  2002. document.getElementById('pptp-modal-pass').value = '';
  2003. document.getElementById('pptp-modal-mppe').checked = true;
  2004. document.getElementById('pptp-modal-defroute').checked = true;
  2005. document.getElementById('pptp-modal-disabled').checked = false;
  2006. document.getElementById('pptp-modal').classList.remove('hidden');
  2007. }
  2008. function openEditPPTPModal(name) {
  2009. const inst = (state.pptpList || []).find(i => i.name === name);
  2010. if (!inst) return;
  2011. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2012. document.getElementById('pptp-modal-name').value = inst.name;
  2013. document.getElementById('pptp-modal-name').readOnly = true;
  2014. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2015. document.getElementById('pptp-modal-user').value = inst.username || '';
  2016. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2017. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2018. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2019. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2020. document.getElementById('pptp-modal').classList.remove('hidden');
  2021. }
  2022. function closePPTPModal() {
  2023. document.getElementById('pptp-modal').classList.add('hidden');
  2024. }
  2025. async function submitSavePPTP(e) {
  2026. e.preventDefault();
  2027. const name = document.getElementById('pptp-modal-name').value.trim();
  2028. const server = document.getElementById('pptp-modal-server').value.trim();
  2029. const user = document.getElementById('pptp-modal-user').value.trim();
  2030. const pass = document.getElementById('pptp-modal-pass').value;
  2031. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2032. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2033. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2034. try {
  2035. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2036. method: 'POST',
  2037. headers: { 'Content-Type': 'application/json' },
  2038. body: JSON.stringify({
  2039. name,
  2040. connect_to: server,
  2041. username: user,
  2042. password: pass,
  2043. require_mppe: mppe,
  2044. default_route: defRoute,
  2045. auto_reconnect: true,
  2046. disabled
  2047. })
  2048. });
  2049. if (res.ok) {
  2050. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2051. closePPTPModal();
  2052. loadPPTP(false);
  2053. fetchData(false);
  2054. }
  2055. } catch (err) {
  2056. showToast('Error', err.message, 'error');
  2057. }
  2058. }
  2059. async function connectPPTPInstance(name) {
  2060. try {
  2061. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2062. if (res.ok) {
  2063. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2064. setTimeout(() => loadPPTP(false), 2000);
  2065. }
  2066. } catch (err) {
  2067. showToast('Error', err.message, 'error');
  2068. }
  2069. }
  2070. async function disconnectPPTPInstance(name) {
  2071. try {
  2072. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2073. if (res.ok) {
  2074. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2075. loadPPTP(false);
  2076. }
  2077. } catch (err) {
  2078. showToast('Error', err.message, 'error');
  2079. }
  2080. }
  2081. async function togglePPTPState(name, enable) {
  2082. try {
  2083. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2084. method: 'POST',
  2085. headers: { 'Content-Type': 'application/json' },
  2086. body: JSON.stringify({ enabled: enable })
  2087. });
  2088. if (res.ok) {
  2089. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2090. loadPPTP(false);
  2091. }
  2092. } catch (err) {
  2093. showToast('Error', err.message, 'error');
  2094. }
  2095. }
  2096. async function deletePPTPInstance(name) {
  2097. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2098. try {
  2099. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2100. if (res.ok) {
  2101. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2102. loadPPTP(false);
  2103. fetchData(false);
  2104. }
  2105. } catch (err) {
  2106. showToast('Error', err.message, 'error');
  2107. }
  2108. }
  2109. // ---------------- Modal & Helper Functions ----------------
  2110. function openVlanModal(defaultParent = '') {
  2111. const select = document.getElementById('vlan-parent');
  2112. select.innerHTML = '';
  2113. const allIfaces = state.interfaces || [];
  2114. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2115. if (eligible.length === 0) {
  2116. const opt = document.createElement('option');
  2117. opt.value = '';
  2118. opt.innerText = 'No VLAN-capable interfaces available';
  2119. select.appendChild(opt);
  2120. } else {
  2121. eligible.forEach(i => {
  2122. const opt = document.createElement('option');
  2123. opt.value = i.name;
  2124. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2125. if (i.name === defaultParent) opt.selected = true;
  2126. select.appendChild(opt);
  2127. });
  2128. }
  2129. document.getElementById('vlan-id').value = '';
  2130. document.getElementById('vlan-name').value = '';
  2131. document.getElementById('vlan-ip').value = '';
  2132. document.getElementById('vlan-desc').value = '';
  2133. autoSuggestVlanName();
  2134. document.getElementById('vlan-modal').classList.remove('hidden');
  2135. }
  2136. function closeVlanModal() {
  2137. document.getElementById('vlan-modal').classList.add('hidden');
  2138. }
  2139. function autoSuggestVlanName() {
  2140. const parent = document.getElementById('vlan-parent').value;
  2141. if (!parent) return;
  2142. const id = document.getElementById('vlan-id').value;
  2143. const nameInput = document.getElementById('vlan-name');
  2144. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  2145. }
  2146. function setSubnetPreset(cidr) {
  2147. const ipInput = document.getElementById('vlan-ip');
  2148. const id = document.getElementById('vlan-id').value || '10';
  2149. ipInput.value = `192.168.${id}.1${cidr}`;
  2150. }
  2151. async function submitCreateVlan(e) {
  2152. e.preventDefault();
  2153. const btn = document.getElementById('vlan-submit-btn');
  2154. btn.disabled = true;
  2155. btn.innerText = 'Creating...';
  2156. const parent = document.getElementById('vlan-parent').value;
  2157. if (!parent) {
  2158. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  2159. btn.disabled = false;
  2160. btn.innerText = 'Create VLAN';
  2161. return;
  2162. }
  2163. const id = parseInt(document.getElementById('vlan-id').value, 10);
  2164. const name = document.getElementById('vlan-name').value.trim();
  2165. const ip = document.getElementById('vlan-ip').value.trim();
  2166. const role = document.getElementById('vlan-role').value;
  2167. const desc = document.getElementById('vlan-desc').value.trim();
  2168. try {
  2169. const res = await fetch(`${API_BASE}/vlans`, {
  2170. method: 'POST',
  2171. headers: { 'Content-Type': 'application/json' },
  2172. body: JSON.stringify({
  2173. parent_name: parent,
  2174. vlan_id: id,
  2175. name: name,
  2176. ip_address: ip,
  2177. role: role,
  2178. description: desc,
  2179. mtu: 1500,
  2180. auto_up: true
  2181. })
  2182. });
  2183. const data = await res.json();
  2184. if (res.ok) {
  2185. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  2186. state.expandedParents.add(parent);
  2187. closeVlanModal();
  2188. await fetchData(true);
  2189. if (state.activeTab !== 'interfaces') navigate('interfaces');
  2190. } else {
  2191. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  2192. }
  2193. } catch (err) {
  2194. showToast('Error', err.message, 'error');
  2195. } finally {
  2196. btn.disabled = false;
  2197. btn.innerText = 'Create VLAN';
  2198. }
  2199. }
  2200. async function confirmDeleteVlan(name) {
  2201. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  2202. try {
  2203. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2204. if (res.ok) {
  2205. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  2206. closeIfaceModal();
  2207. fetchData(true);
  2208. }
  2209. } catch (err) {
  2210. showToast('Error', err.message, 'error');
  2211. }
  2212. }
  2213. function openIfaceModal(name) {
  2214. const iface = (state.interfaces || []).find(i => i.name === name);
  2215. if (!iface) return;
  2216. state.currentModalIface = iface.name;
  2217. document.getElementById('modal-iface-name').innerText = iface.name;
  2218. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  2219. document.getElementById('modal-iface-mtu').value = iface.mtu;
  2220. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  2221. document.getElementById('modal-iface-desc').value = iface.description || '';
  2222. const delBtn = document.getElementById('modal-delete-vlan-btn');
  2223. if (iface.is_vlan) {
  2224. delBtn.classList.remove('hidden');
  2225. } else {
  2226. delBtn.classList.add('hidden');
  2227. }
  2228. renderModalIPs(iface);
  2229. document.getElementById('iface-modal').classList.remove('hidden');
  2230. }
  2231. function renderModalIPs(iface) {
  2232. const container = document.getElementById('modal-ip-list');
  2233. container.innerHTML = '';
  2234. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  2235. if (addrs.length === 0) {
  2236. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  2237. return;
  2238. }
  2239. addrs.forEach(addr => {
  2240. const row = document.createElement('div');
  2241. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  2242. row.innerHTML = `
  2243. <span class="text-white">${addr}</span>
  2244. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  2245. `;
  2246. container.appendChild(row);
  2247. });
  2248. }
  2249. function closeIfaceModal() {
  2250. document.getElementById('iface-modal').classList.add('hidden');
  2251. state.currentModalIface = null;
  2252. }
  2253. async function setIfaceState(name, newState) {
  2254. await toggleInterfaceState(name, newState);
  2255. const updated = (state.interfaces || []).find(i => i.name === name);
  2256. if (updated) openIfaceModal(name);
  2257. }
  2258. async function applyMTU() {
  2259. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  2260. try {
  2261. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  2262. method: 'POST',
  2263. headers: { 'Content-Type': 'application/json' },
  2264. body: JSON.stringify({ mtu })
  2265. });
  2266. if (res.ok) {
  2267. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  2268. fetchData(false);
  2269. }
  2270. } catch (err) {
  2271. showToast('Error', err.message, 'error');
  2272. }
  2273. }
  2274. async function addInterfaceIP() {
  2275. const ip = document.getElementById('modal-new-ip').value.trim();
  2276. if (!ip) return;
  2277. try {
  2278. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2279. method: 'POST',
  2280. headers: { 'Content-Type': 'application/json' },
  2281. body: JSON.stringify({ ip })
  2282. });
  2283. if (res.ok) {
  2284. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  2285. document.getElementById('modal-new-ip').value = '';
  2286. await fetchData(false);
  2287. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2288. if (iface) renderModalIPs(iface);
  2289. } else {
  2290. const err = await res.json();
  2291. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  2292. }
  2293. } catch (err) {
  2294. showToast('Error', err.message, 'error');
  2295. }
  2296. }
  2297. async function removeInterfaceIP(ip) {
  2298. if (!confirm(`Remove IP ${ip}?`)) return;
  2299. try {
  2300. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2301. method: 'DELETE',
  2302. headers: { 'Content-Type': 'application/json' },
  2303. body: JSON.stringify({ ip })
  2304. });
  2305. if (res.ok) {
  2306. showToast('IP Removed', `Removed ${ip}`, 'success');
  2307. await fetchData(false);
  2308. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2309. if (iface) renderModalIPs(iface);
  2310. }
  2311. } catch (err) {
  2312. showToast('Error', err.message, 'error');
  2313. }
  2314. }
  2315. async function saveInterfaceMetadata() {
  2316. const role = document.getElementById('modal-iface-role').value;
  2317. const desc = document.getElementById('modal-iface-desc').value.trim();
  2318. try {
  2319. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/metadata`, {
  2320. method: 'POST',
  2321. headers: { 'Content-Type': 'application/json' },
  2322. body: JSON.stringify({ role, description: desc })
  2323. });
  2324. if (res.ok) {
  2325. showToast('Saved', 'Metadata updated', 'success');
  2326. closeIfaceModal();
  2327. fetchData(false);
  2328. }
  2329. } catch (err) {
  2330. showToast('Error', err.message, 'error');
  2331. }
  2332. }
  2333. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  2334. state.fwSubTab = 'filter';
  2335. state.routesSubTab = 'routes';
  2336. function renderRuleFlag(disabled, hasComment) {
  2337. let flags = '';
  2338. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  2339. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  2340. return flags || '<span class="text-slate-600">-</span>';
  2341. }
  2342. function renderActionBadge(action) {
  2343. const act = (action || '').toLowerCase();
  2344. let color = 'bg-slate-800 text-slate-300';
  2345. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  2346. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  2347. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  2348. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  2349. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  2350. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  2351. }
  2352. function switchFWSubTab(tab) {
  2353. state.fwSubTab = tab;
  2354. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  2355. tabs.forEach(t => {
  2356. const panel = document.getElementById(`fw-subtab-${t}`);
  2357. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  2358. if (panel) {
  2359. if (t === tab) panel.classList.remove('hidden');
  2360. else panel.classList.add('hidden');
  2361. }
  2362. if (btn) {
  2363. if (t === tab) {
  2364. 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';
  2365. } else {
  2366. 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';
  2367. }
  2368. }
  2369. });
  2370. const addBtn = document.getElementById('fw-primary-add-btn');
  2371. if (addBtn) {
  2372. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  2373. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  2374. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  2375. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  2376. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  2377. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  2378. }
  2379. if (tab === 'geo') loadGeoIP();
  2380. if (tab === 'connections') loadConnections();
  2381. setTimeout(initTableSorting, 50);
  2382. }
  2383. function openCurrentFWModal() {
  2384. if (state.fwSubTab === 'filter') openAddFilterModal();
  2385. else if (state.fwSubTab === 'nat') openAddNATModal();
  2386. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  2387. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  2388. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  2389. else if (state.fwSubTab === 'connections') loadConnections();
  2390. }
  2391. async function loadFirewall(populateDropdowns = true) {
  2392. try {
  2393. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  2394. fetch(`${API_BASE}/firewall/summary`),
  2395. fetch(`${API_BASE}/firewall/filter`),
  2396. fetch(`${API_BASE}/firewall/nat`),
  2397. fetch(`${API_BASE}/firewall/mangle`),
  2398. fetch(`${API_BASE}/firewall/address-lists`),
  2399. fetch(`${API_BASE}/firewall/geoip/status`),
  2400. fetch(`${API_BASE}/firewall/geoip/countries`)
  2401. ]);
  2402. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  2403. if (filterRes.ok) state.filterRules = await filterRes.json();
  2404. if (natRes.ok) state.natRules = await natRes.json();
  2405. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  2406. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  2407. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  2408. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  2409. // Badges
  2410. const bFilter = document.getElementById('fw-badge-filter');
  2411. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  2412. const bNat = document.getElementById('fw-badge-nat');
  2413. if (bNat) bNat.innerText = (state.natRules || []).length;
  2414. const bMangle = document.getElementById('fw-badge-mangle');
  2415. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  2416. const bAddr = document.getElementById('fw-badge-addrlist');
  2417. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  2418. const bGeo = document.getElementById('fw-badge-geo');
  2419. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  2420. renderFilterRules();
  2421. renderNATRules();
  2422. renderMangleRules();
  2423. renderAddressLists();
  2424. renderGeoCountries();
  2425. if (state.fwSubTab === 'connections') {
  2426. loadConnections();
  2427. }
  2428. } catch (err) {
  2429. console.error('Failed to load firewall:', err);
  2430. }
  2431. }
  2432. // ----------------- Filter Rules -----------------
  2433. function renderFilterRules() {
  2434. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  2435. const tbody = document.getElementById('filter-table-body');
  2436. const empty = document.getElementById('filter-empty');
  2437. if (!tbody) return;
  2438. tbody.innerHTML = '';
  2439. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2440. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2441. if (rules.length === 0) {
  2442. empty?.classList.remove('hidden');
  2443. return;
  2444. }
  2445. empty?.classList.add('hidden');
  2446. rules.forEach((r, idx) => {
  2447. const tr = document.createElement('tr');
  2448. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2449. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2450. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2451. let actionExtra = '';
  2452. if (r.action === 'reject') {
  2453. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  2454. } else if (r.action === 'jump') {
  2455. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  2456. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  2457. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  2458. } else if (r.action === 'log' && r.log_prefix) {
  2459. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  2460. }
  2461. tr.innerHTML = `
  2462. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2463. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2464. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2465. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2466. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2467. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2468. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2469. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2470. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  2471. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2472. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2473. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2474. </td>
  2475. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2476. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2477. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2478. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2479. <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>
  2480. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2481. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2482. </td>
  2483. `;
  2484. tbody.appendChild(tr);
  2485. });
  2486. }
  2487. function formatTarget(addr, list, geo) {
  2488. const parts = [];
  2489. if (addr) parts.push(`<span>${addr}</span>`);
  2490. if (list) {
  2491. const inv = list.startsWith('!') ? '!' : '';
  2492. const clean = list.replace(/^!/, '');
  2493. 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>`);
  2494. }
  2495. if (geo) {
  2496. const inv = geo.startsWith('!') ? '!' : '';
  2497. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  2498. 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>`);
  2499. }
  2500. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  2501. return parts.join(' ');
  2502. }
  2503. function populateInterfaceSelect(selectId, currentVal = '') {
  2504. const sel = document.getElementById(selectId);
  2505. if (!sel) return;
  2506. sel.innerHTML = '<option value="">(Any Interface)</option>';
  2507. (state.interfaces || []).forEach(i => {
  2508. const opt = document.createElement('option');
  2509. opt.value = i.name;
  2510. opt.innerText = `${i.name} (${i.role || i.type})`;
  2511. if (i.name === currentVal) opt.selected = true;
  2512. sel.appendChild(opt);
  2513. });
  2514. }
  2515. function populateAddressListSelect(selectId, currentVal = '') {
  2516. const sel = document.getElementById(selectId);
  2517. if (!sel) return;
  2518. sel.innerHTML = '<option value="">(None)</option>';
  2519. const cleanVal = (currentVal || '').replace(/^!/, '');
  2520. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  2521. customNames.forEach(name => {
  2522. const count = (state.addressLists || []).filter(a => a.name === name).length;
  2523. const opt = document.createElement('option');
  2524. opt.value = name;
  2525. opt.innerText = `${name} (${count} entries)`;
  2526. if (name === cleanVal) opt.selected = true;
  2527. sel.appendChild(opt);
  2528. });
  2529. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  2530. const opt = document.createElement('option');
  2531. opt.value = cleanVal;
  2532. opt.innerText = cleanVal;
  2533. opt.selected = true;
  2534. sel.appendChild(opt);
  2535. }
  2536. populateCommonAddrListDatalist();
  2537. }
  2538. function populateCommonAddrListDatalist() {
  2539. const dl = document.getElementById('fw-addrlist-datalist');
  2540. if (!dl) return;
  2541. dl.innerHTML = '';
  2542. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  2543. names.forEach(name => {
  2544. const opt = document.createElement('option');
  2545. opt.value = name;
  2546. dl.appendChild(opt);
  2547. });
  2548. }
  2549. function populateGeoIPSelect(selectId, currentVal = '') {
  2550. const sel = document.getElementById(selectId);
  2551. if (!sel) return;
  2552. sel.innerHTML = '<option value="">(None)</option>';
  2553. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  2554. // Presets optgroup
  2555. const grpPresets = document.createElement('optgroup');
  2556. grpPresets.label = '⚡ Regional Presets';
  2557. const presets = [
  2558. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  2559. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  2560. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  2561. ];
  2562. presets.forEach(p => {
  2563. const opt = document.createElement('option');
  2564. opt.value = p.code;
  2565. opt.innerText = p.label;
  2566. if (p.code === cleanVal) opt.selected = true;
  2567. grpPresets.appendChild(opt);
  2568. });
  2569. sel.appendChild(grpPresets);
  2570. // All Countries optgroup
  2571. const grpCountries = document.createElement('optgroup');
  2572. grpCountries.label = '🌍 All Countries';
  2573. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  2574. countries.forEach(c => {
  2575. const opt = document.createElement('option');
  2576. opt.value = c.code;
  2577. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  2578. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  2579. if (c.code === cleanVal) opt.selected = true;
  2580. grpCountries.appendChild(opt);
  2581. });
  2582. sel.appendChild(grpCountries);
  2583. }
  2584. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  2585. function switchFwRuleTab(tab) {
  2586. state.activeFwRuleTab = tab;
  2587. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  2588. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  2589. btn.classList.add('text-slate-400', 'border-transparent');
  2590. });
  2591. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  2592. if (activeBtn) {
  2593. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  2594. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  2595. }
  2596. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  2597. const activePane = document.getElementById(`fw-pane-${tab}`);
  2598. if (activePane) activePane.classList.remove('hidden');
  2599. if (tab === 'statistics') {
  2600. startFwStatPolling();
  2601. } else {
  2602. stopFwStatPolling();
  2603. }
  2604. }
  2605. function toggleFwField(fieldKey, expand) {
  2606. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  2607. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  2608. if (!plusBtn || !fieldBox) return;
  2609. if (expand) {
  2610. plusBtn.classList.add('hidden');
  2611. fieldBox.classList.remove('hidden');
  2612. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2613. if (valInput) valInput.focus();
  2614. } else {
  2615. fieldBox.classList.add('hidden');
  2616. plusBtn.classList.remove('hidden');
  2617. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2618. if (valInput) {
  2619. if (valInput.tagName === 'SELECT') {
  2620. valInput.selectedIndex = 0;
  2621. } else {
  2622. valInput.value = '';
  2623. }
  2624. }
  2625. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  2626. if (invInput) invInput.checked = false;
  2627. if (fieldKey === 'cs') {
  2628. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  2629. const el = document.getElementById(id);
  2630. if (el) el.checked = false;
  2631. });
  2632. }
  2633. if (fieldKey === 'natstate') {
  2634. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  2635. const el = document.getElementById(id);
  2636. if (el) el.checked = false;
  2637. });
  2638. }
  2639. if (fieldKey === 'days') {
  2640. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  2641. const el = document.getElementById(`fw-day-${d}`);
  2642. if (el) el.checked = true;
  2643. });
  2644. }
  2645. }
  2646. }
  2647. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  2648. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  2649. toggleFwField(fieldKey, true);
  2650. let strVal = String(value);
  2651. if (hasInvert) {
  2652. const inv = strVal.startsWith('!');
  2653. if (inv) strVal = strVal.slice(1);
  2654. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  2655. if (invEl) invEl.checked = inv;
  2656. }
  2657. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  2658. if (valEl) valEl.value = strVal;
  2659. } else {
  2660. toggleFwField(fieldKey, false);
  2661. }
  2662. }
  2663. function getFwFieldVal(fieldKey, hasInvert = false) {
  2664. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  2665. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  2666. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  2667. let v = valEl ? valEl.value.trim() : '';
  2668. if (!v) return '';
  2669. if (hasInvert) {
  2670. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  2671. if (invEl && invEl.checked) {
  2672. v = '!' + v.replace(/^!/, '');
  2673. }
  2674. }
  2675. return v;
  2676. }
  2677. function toggleMaximizeFilterModal() {
  2678. const win = document.getElementById('filter-modal-window');
  2679. if (!win) return;
  2680. if (win.classList.contains('max-w-[720px]')) {
  2681. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  2682. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  2683. } else {
  2684. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  2685. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  2686. }
  2687. }
  2688. function openAddFilterModal() {
  2689. switchFwRuleTab('general');
  2690. const badge = document.getElementById('fw-modal-badge');
  2691. if (badge) badge.innerText = 'New...';
  2692. document.getElementById('filter-modal-id').value = '';
  2693. document.getElementById('filter-modal-enabled').checked = true;
  2694. document.getElementById('filter-modal-comment').value = '';
  2695. document.getElementById('filter-modal-chain').value = 'forward';
  2696. document.getElementById('filter-modal-action').value = 'accept';
  2697. document.getElementById('filter-modal-log').checked = false;
  2698. populateInterfaceSelect('fw-val-iniface');
  2699. populateInterfaceSelect('fw-val-outiface');
  2700. populateAddressListSelect('fw-val-srclist');
  2701. populateAddressListSelect('fw-val-dstlist');
  2702. populateGeoIPSelect('fw-val-srcgeo');
  2703. populateGeoIPSelect('fw-val-dstgeo');
  2704. const allFieldKeys = [
  2705. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  2706. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  2707. 'routingmark', 'conntype', 'cs', 'natstate',
  2708. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  2709. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  2710. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  2711. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  2712. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  2713. ];
  2714. allFieldKeys.forEach(k => toggleFwField(k, false));
  2715. resetCurrentRuleCounters();
  2716. toggleFilterActionFields();
  2717. document.getElementById('filter-modal').classList.remove('hidden');
  2718. }
  2719. function openEditFilterModal(id) {
  2720. const r = (state.filterRules || []).find(rule => rule.id === id);
  2721. if (!r) return;
  2722. switchFwRuleTab('general');
  2723. const badge = document.getElementById('fw-modal-badge');
  2724. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  2725. document.getElementById('filter-modal-id').value = r.id;
  2726. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  2727. document.getElementById('filter-modal-comment').value = r.comment || '';
  2728. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  2729. document.getElementById('filter-modal-action').value = r.action || 'accept';
  2730. document.getElementById('filter-modal-log').checked = !!r.log;
  2731. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  2732. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  2733. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  2734. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  2735. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  2736. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  2737. setFwFieldVal('src', r.src_address, true);
  2738. setFwFieldVal('dst', r.dst_address, true);
  2739. setFwFieldVal('srclist', r.src_address_list, true);
  2740. setFwFieldVal('dstlist', r.dst_address_list, true);
  2741. setFwFieldVal('srcgeo', r.src_geoip, true);
  2742. setFwFieldVal('dstgeo', r.dst_geoip, true);
  2743. if (r.protocol && r.protocol !== 'all') {
  2744. setFwFieldVal('proto', r.protocol, true);
  2745. } else {
  2746. toggleFwField('proto', false);
  2747. }
  2748. setFwFieldVal('sport', r.src_port, true);
  2749. setFwFieldVal('dport', r.dst_port, true);
  2750. setFwFieldVal('anyport', r.any_port, true);
  2751. setFwFieldVal('iniface', r.in_interface, true);
  2752. setFwFieldVal('outiface', r.out_interface, true);
  2753. setFwFieldVal('inifacelist', r.in_interface_list, true);
  2754. setFwFieldVal('outifacelist', r.out_interface_list, true);
  2755. setFwFieldVal('pktmark', r.packet_mark, true);
  2756. setFwFieldVal('connmark', r.connection_mark, true);
  2757. setFwFieldVal('routingmark', r.routing_mark, true);
  2758. setFwFieldVal('conntype', r.connection_type, false);
  2759. const states = r.connection_state || [];
  2760. if (states.length > 0) {
  2761. toggleFwField('cs', true);
  2762. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  2763. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  2764. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  2765. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  2766. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  2767. } else {
  2768. toggleFwField('cs', false);
  2769. }
  2770. const natStates = r.connection_nat_state || [];
  2771. if (natStates.length > 0) {
  2772. toggleFwField('natstate', true);
  2773. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  2774. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  2775. } else {
  2776. toggleFwField('natstate', false);
  2777. }
  2778. // Advanced tab fields
  2779. setFwFieldVal('layer7', r.layer7_protocol, false);
  2780. setFwFieldVal('content', r.content, false);
  2781. setFwFieldVal('connbytes', r.connection_bytes, false);
  2782. setFwFieldVal('connrate', r.connection_rate, false);
  2783. setFwFieldVal('pcc', r.pcc, false);
  2784. setFwFieldVal('srcmac', r.src_mac_address, true);
  2785. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  2786. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  2787. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  2788. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  2789. setFwFieldVal('ipsec', r.ipsec_policy, false);
  2790. setFwFieldVal('tlshost', r.tls_host, false);
  2791. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  2792. setFwFieldVal('priority', r.priority, false);
  2793. setFwFieldVal('dscp', r.dscp, false);
  2794. setFwFieldVal('tcpmss', r.tcp_mss, false);
  2795. if (r.tos) {
  2796. const tosEl = document.getElementById('fw-val-tos');
  2797. if (tosEl) tosEl.value = r.tos;
  2798. }
  2799. setFwFieldVal('pktsize', r.packet_size, false);
  2800. setFwFieldVal('random', r.random, false);
  2801. setFwFieldVal('tcpflags', r.tcp_flags, false);
  2802. setFwFieldVal('icmpoptions', r.icmp_options, false);
  2803. setFwFieldVal('ipv4options', r.ipv4_options, false);
  2804. setFwFieldVal('ttl', r.ttl, false);
  2805. // Extra tab fields
  2806. setFwFieldVal('time', r.time, false);
  2807. if (r.days) {
  2808. toggleFwField('days', true);
  2809. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  2810. const chk = document.getElementById(`fw-day-${d}`);
  2811. if (chk) chk.checked = r.days.includes(d);
  2812. });
  2813. } else {
  2814. toggleFwField('days', false);
  2815. }
  2816. setFwFieldVal('limit', r.limit, false);
  2817. setFwFieldVal('dstlimit', r.dst_limit, false);
  2818. setFwFieldVal('psd', r.psd, false);
  2819. // Action fields
  2820. if (r.reject_with) {
  2821. const rwEl = document.getElementById('filter-modal-rejectwith');
  2822. if (rwEl) rwEl.value = r.reject_with;
  2823. }
  2824. if (r.jump_target) {
  2825. const jtEl = document.getElementById('filter-modal-jumptarget');
  2826. if (jtEl) jtEl.value = r.jump_target;
  2827. }
  2828. if (r.address_list) {
  2829. const alEl = document.getElementById('filter-modal-action-addrlist');
  2830. if (alEl) alEl.value = r.address_list;
  2831. }
  2832. if (r.address_list_timeout) {
  2833. const toEl = document.getElementById('filter-modal-action-timeout');
  2834. if (toEl) toEl.value = r.address_list_timeout;
  2835. }
  2836. setFwFieldVal('logprefix', r.log_prefix, false);
  2837. // Statistics
  2838. const bEl = document.getElementById('fw-stat-bytes');
  2839. const pEl = document.getElementById('fw-stat-packets');
  2840. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  2841. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  2842. state.fwLastBytes = r.bytes || 0;
  2843. state.fwLastPackets = r.packets || 0;
  2844. state.fwLastTimestamp = Date.now();
  2845. state.fwStatRateHistory = new Array(30).fill(0);
  2846. state.fwStatPktHistory = new Array(30).fill(0);
  2847. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  2848. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  2849. toggleFilterActionFields();
  2850. document.getElementById('filter-modal').classList.remove('hidden');
  2851. }
  2852. function closeFilterModal() {
  2853. stopFwStatPolling();
  2854. document.getElementById('filter-modal').classList.add('hidden');
  2855. }
  2856. function toggleFilterActionFields() {
  2857. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  2858. const rejectBox = document.getElementById('filter-action-reject-box');
  2859. const jumpBox = document.getElementById('filter-action-jump-box');
  2860. const addrBox = document.getElementById('filter-action-addrlist-box');
  2861. if (rejectBox) {
  2862. if (act === 'reject') rejectBox.classList.remove('hidden');
  2863. else rejectBox.classList.add('hidden');
  2864. }
  2865. if (jumpBox) {
  2866. if (act === 'jump') jumpBox.classList.remove('hidden');
  2867. else jumpBox.classList.add('hidden');
  2868. }
  2869. if (addrBox) {
  2870. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  2871. addrBox.classList.remove('hidden');
  2872. } else {
  2873. addrBox.classList.add('hidden');
  2874. }
  2875. }
  2876. if (act === 'log') {
  2877. const logEl = document.getElementById('filter-modal-log');
  2878. if (logEl) logEl.checked = true;
  2879. toggleFwField('logprefix', true);
  2880. }
  2881. }
  2882. function toggleFwLogPrefix() {
  2883. const isLog = document.getElementById('filter-modal-log')?.checked;
  2884. toggleFwField('logprefix', !!isLog);
  2885. }
  2886. function copyFilterRule() {
  2887. document.getElementById('filter-modal-id').value = '';
  2888. const badge = document.getElementById('fw-modal-badge');
  2889. if (badge) badge.innerText = 'New...';
  2890. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  2891. }
  2892. function resetCurrentRuleCounters() {
  2893. state.fwStatRateHistory = new Array(30).fill(0);
  2894. state.fwStatPktHistory = new Array(30).fill(0);
  2895. state.fwLastBytes = 0;
  2896. state.fwLastPackets = 0;
  2897. state.fwLastTimestamp = Date.now();
  2898. const bEl = document.getElementById('fw-stat-bytes');
  2899. const pEl = document.getElementById('fw-stat-packets');
  2900. const rEl = document.getElementById('fw-stat-rate');
  2901. const prEl = document.getElementById('fw-stat-pktrate');
  2902. if (bEl) bEl.value = '0 B';
  2903. if (pEl) pEl.value = '0';
  2904. if (rEl) rEl.value = '0 bps';
  2905. if (prEl) prEl.value = '0 p/s';
  2906. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  2907. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  2908. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  2909. }
  2910. async function resetAllFwCounters() {
  2911. try {
  2912. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  2913. if (res.ok) {
  2914. resetCurrentRuleCounters();
  2915. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  2916. loadFirewall(false);
  2917. }
  2918. } catch (err) {
  2919. showToast('Error', err.message, 'error');
  2920. }
  2921. }
  2922. async function applyFilterRule(closeAfter = false) {
  2923. const id = document.getElementById('filter-modal-id').value;
  2924. const chain = document.getElementById('filter-modal-chain').value;
  2925. const action = document.getElementById('filter-modal-action').value;
  2926. const comment = document.getElementById('filter-modal-comment').value.trim();
  2927. const enabled = document.getElementById('filter-modal-enabled').checked;
  2928. const src = getFwFieldVal('src', true);
  2929. const dst = getFwFieldVal('dst', true);
  2930. const srclist = getFwFieldVal('srclist', true);
  2931. const dstlist = getFwFieldVal('dstlist', true);
  2932. const srcgeo = getFwFieldVal('srcgeo', true);
  2933. const dstgeo = getFwFieldVal('dstgeo', true);
  2934. const proto = getFwFieldVal('proto', true);
  2935. const sport = getFwFieldVal('sport', true);
  2936. const dport = getFwFieldVal('dport', true);
  2937. const anyport = getFwFieldVal('anyport', true);
  2938. const iniface = getFwFieldVal('iniface', true);
  2939. const outiface = getFwFieldVal('outiface', true);
  2940. const inifacelist = getFwFieldVal('inifacelist', true);
  2941. const outifacelist = getFwFieldVal('outifacelist', true);
  2942. const pktmark = getFwFieldVal('pktmark', true);
  2943. const connmark = getFwFieldVal('connmark', true);
  2944. const routingmark = getFwFieldVal('routingmark', true);
  2945. const conntype = getFwFieldVal('conntype', false);
  2946. const states = [];
  2947. const csBox = document.getElementById('fw-field-cs');
  2948. if (csBox && !csBox.classList.contains('hidden')) {
  2949. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  2950. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  2951. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  2952. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  2953. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  2954. }
  2955. const natStates = [];
  2956. const natBox = document.getElementById('fw-field-natstate');
  2957. if (natBox && !natBox.classList.contains('hidden')) {
  2958. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  2959. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  2960. }
  2961. const payload = {
  2962. id,
  2963. chain,
  2964. action,
  2965. protocol: proto || 'all',
  2966. src_address: src,
  2967. dst_address: dst,
  2968. src_port: sport,
  2969. dst_port: dport,
  2970. any_port: anyport,
  2971. in_interface: iniface,
  2972. out_interface: outiface,
  2973. in_interface_list: inifacelist,
  2974. out_interface_list: outifacelist,
  2975. packet_mark: pktmark,
  2976. connection_mark: connmark,
  2977. routing_mark: routingmark,
  2978. connection_type: conntype,
  2979. connection_state: states,
  2980. connection_nat_state: natStates,
  2981. src_address_list: srclist,
  2982. dst_address_list: dstlist,
  2983. src_geoip: srcgeo,
  2984. dst_geoip: dstgeo,
  2985. comment,
  2986. disabled: !enabled,
  2987. // Advanced tab
  2988. layer7_protocol: getFwFieldVal('layer7', false),
  2989. content: getFwFieldVal('content', false),
  2990. connection_bytes: getFwFieldVal('connbytes', false),
  2991. connection_rate: getFwFieldVal('connrate', false),
  2992. pcc: getFwFieldVal('pcc', false),
  2993. src_mac_address: getFwFieldVal('srcmac', true),
  2994. out_bridge_port: getFwFieldVal('outbridgeport', false),
  2995. in_bridge_port: getFwFieldVal('inbridgeport', false),
  2996. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  2997. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  2998. ipsec_policy: getFwFieldVal('ipsec', false),
  2999. tls_host: getFwFieldVal('tlshost', false),
  3000. ingress_priority: getFwFieldVal('ingresspriority', false),
  3001. priority: getFwFieldVal('priority', false),
  3002. dscp: getFwFieldVal('dscp', false),
  3003. tcp_mss: getFwFieldVal('tcpmss', false),
  3004. tos: document.getElementById('fw-val-tos')?.value || '',
  3005. packet_size: getFwFieldVal('pktsize', false),
  3006. random: getFwFieldVal('random', false),
  3007. tcp_flags: getFwFieldVal('tcpflags', false),
  3008. icmp_options: getFwFieldVal('icmpoptions', false),
  3009. ipv4_options: getFwFieldVal('ipv4options', false),
  3010. ttl: getFwFieldVal('ttl', false),
  3011. // Extra tab
  3012. time: getFwFieldVal('time', false),
  3013. limit: getFwFieldVal('limit', false),
  3014. dst_limit: getFwFieldVal('dstlimit', false),
  3015. psd: getFwFieldVal('psd', false),
  3016. // Action tab
  3017. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  3018. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  3019. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  3020. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  3021. log: document.getElementById('filter-modal-log')?.checked || false,
  3022. log_prefix: getFwFieldVal('logprefix', false)
  3023. };
  3024. try {
  3025. const res = await fetch(`${API_BASE}/firewall/filter`, {
  3026. method: 'POST',
  3027. headers: { 'Content-Type': 'application/json' },
  3028. body: JSON.stringify(payload)
  3029. });
  3030. if (res.ok) {
  3031. const data = await res.json();
  3032. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  3033. loadFirewall(false);
  3034. if (closeAfter) {
  3035. closeFilterModal();
  3036. } else {
  3037. if (data.id) {
  3038. document.getElementById('filter-modal-id').value = data.id;
  3039. const badge = document.getElementById('fw-modal-badge');
  3040. if (badge) badge.innerText = `#${data.id}`;
  3041. }
  3042. }
  3043. } else {
  3044. const err = await res.json();
  3045. showToast('Error', err.message || 'Failed to save rule', 'error');
  3046. }
  3047. } catch (err) {
  3048. showToast('Error', err.message, 'error');
  3049. }
  3050. }
  3051. function submitSaveFilterRule(e) {
  3052. if (e && e.preventDefault) e.preventDefault();
  3053. return applyFilterRule(true);
  3054. }
  3055. function startFwStatPolling() {
  3056. stopFwStatPolling();
  3057. pollRuleStats();
  3058. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  3059. }
  3060. function stopFwStatPolling() {
  3061. if (state.fwStatInterval) {
  3062. clearInterval(state.fwStatInterval);
  3063. state.fwStatInterval = null;
  3064. }
  3065. }
  3066. async function pollRuleStats() {
  3067. const id = document.getElementById('filter-modal-id')?.value;
  3068. if (!id) {
  3069. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  3070. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  3071. return;
  3072. }
  3073. try {
  3074. const res = await fetch(`${API_BASE}/firewall/filter`);
  3075. if (!res.ok) return;
  3076. const rules = await res.json();
  3077. const r = rules.find(x => x.id === id);
  3078. if (!r) return;
  3079. const now = Date.now();
  3080. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  3081. state.fwLastTimestamp = now;
  3082. const curBytes = r.bytes || 0;
  3083. const curPackets = r.packets || 0;
  3084. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  3085. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  3086. state.fwLastBytes = curBytes;
  3087. state.fwLastPackets = curPackets;
  3088. const rateBps = Math.round((deltaBytes * 8) / dt);
  3089. const ratePkt = Math.round(deltaPkts / dt);
  3090. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  3091. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  3092. state.fwStatRateHistory.push(rateBps);
  3093. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  3094. state.fwStatPktHistory.push(ratePkt);
  3095. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  3096. const bEl = document.getElementById('fw-stat-bytes');
  3097. const pEl = document.getElementById('fw-stat-packets');
  3098. const rEl = document.getElementById('fw-stat-rate');
  3099. const prEl = document.getElementById('fw-stat-pktrate');
  3100. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  3101. if (pEl) pEl.value = curPackets.toLocaleString();
  3102. if (rEl) rEl.value = formatBps(rateBps);
  3103. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  3104. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3105. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3106. } catch (e) {
  3107. console.error('Error polling rule stats', e);
  3108. }
  3109. }
  3110. function formatBps(bps) {
  3111. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  3112. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  3113. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  3114. return bps + ' bps';
  3115. }
  3116. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  3117. const svg = document.getElementById(svgId);
  3118. if (!svg) return;
  3119. const w = 500;
  3120. const h = 100;
  3121. const paddingRight = 45;
  3122. const graphWidth = w - paddingRight;
  3123. const maxVal = Math.max(5, ...dataArray);
  3124. const currentVal = dataArray[dataArray.length - 1] || 0;
  3125. const leg = document.getElementById(legendId);
  3126. if (leg) {
  3127. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  3128. }
  3129. let gridLines = '';
  3130. for (let i = 0; i <= 5; i++) {
  3131. const y = 8 + (i * (h - 18) / 5);
  3132. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  3133. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  3134. gridLines += `
  3135. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  3136. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  3137. `;
  3138. }
  3139. const step = graphWidth / (dataArray.length - 1);
  3140. const points = dataArray.map((val, idx) => {
  3141. const x = idx * step;
  3142. const y = (h - 10) - (val / maxVal) * (h - 20);
  3143. return `${x.toFixed(1)},${y.toFixed(1)}`;
  3144. });
  3145. const polylineStr = points.join(' ');
  3146. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  3147. svg.innerHTML = `
  3148. ${gridLines}
  3149. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  3150. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  3151. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  3152. `;
  3153. }
  3154. async function moveFilterRule(id, dir) {
  3155. try {
  3156. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  3157. method: 'POST',
  3158. headers: { 'Content-Type': 'application/json' },
  3159. body: JSON.stringify({ direction: dir })
  3160. });
  3161. if (res.ok) loadFirewall(false);
  3162. } catch (err) {
  3163. showToast('Error', err.message, 'error');
  3164. }
  3165. }
  3166. async function toggleFilterRuleState(id, disabled) {
  3167. try {
  3168. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  3169. method: 'POST',
  3170. headers: { 'Content-Type': 'application/json' },
  3171. body: JSON.stringify({ disabled })
  3172. });
  3173. if (res.ok) loadFirewall(false);
  3174. } catch (err) {
  3175. showToast('Error', err.message, 'error');
  3176. }
  3177. }
  3178. async function deleteFilterRule(id) {
  3179. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  3180. try {
  3181. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3182. if (res.ok) {
  3183. showToast('Deleted', 'Filter rule removed', 'success');
  3184. loadFirewall(false);
  3185. }
  3186. } catch (err) {
  3187. showToast('Error', err.message, 'error');
  3188. }
  3189. }
  3190. // ----------------- NAT Rules -----------------
  3191. function renderNATRules() {
  3192. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  3193. const tbody = document.getElementById('nat-table-body');
  3194. const empty = document.getElementById('nat-empty');
  3195. if (!tbody) return;
  3196. tbody.innerHTML = '';
  3197. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3198. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  3199. if (rules.length === 0) {
  3200. empty?.classList.remove('hidden');
  3201. return;
  3202. }
  3203. empty?.classList.add('hidden');
  3204. rules.forEach((r, idx) => {
  3205. const tr = document.createElement('tr');
  3206. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3207. let toTarget = '-';
  3208. if (r.action === 'jump') {
  3209. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  3210. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3211. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  3212. } else if (r.action === 'redirect') {
  3213. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  3214. } else if (r.action === 'masquerade') {
  3215. toTarget = r.to_ports ? `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports}</span>` : `<span class="text-slate-500 font-mono">-</span>`;
  3216. } else if (r.action === 'log') {
  3217. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  3218. } else {
  3219. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  3220. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  3221. }
  3222. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  3223. tr.innerHTML = `
  3224. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3225. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3226. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  3227. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3228. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3229. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  3230. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3231. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  3232. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  3233. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3234. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3235. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3236. </td>
  3237. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3238. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3239. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3240. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3241. <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>
  3242. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3243. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3244. </td>
  3245. `;
  3246. tbody.appendChild(tr);
  3247. });
  3248. }
  3249. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3250. function switchNATRuleTab(tab) {
  3251. state.activeNATRuleTab = tab;
  3252. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  3253. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3254. btn.classList.add('text-slate-400', 'border-transparent');
  3255. });
  3256. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  3257. if (activeBtn) {
  3258. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3259. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3260. }
  3261. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  3262. const activePane = document.getElementById(`nat-pane-${tab}`);
  3263. if (activePane) activePane.classList.remove('hidden');
  3264. if (tab === 'statistics') {
  3265. startNATStatPolling();
  3266. } else {
  3267. stopNATStatPolling();
  3268. }
  3269. }
  3270. function toggleNATField(fieldKey, expand) {
  3271. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  3272. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3273. if (!plusBtn || !fieldBox) return;
  3274. if (expand) {
  3275. plusBtn.classList.add('hidden');
  3276. fieldBox.classList.remove('hidden');
  3277. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3278. if (valInput) valInput.focus();
  3279. } else {
  3280. fieldBox.classList.add('hidden');
  3281. plusBtn.classList.remove('hidden');
  3282. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3283. if (valInput) {
  3284. if (valInput.tagName === 'SELECT') {
  3285. valInput.selectedIndex = 0;
  3286. } else {
  3287. valInput.value = '';
  3288. }
  3289. }
  3290. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  3291. if (invInput) invInput.checked = false;
  3292. if (fieldKey === 'days') {
  3293. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3294. const el = document.getElementById(`nat-day-${d}`);
  3295. if (el) el.checked = true;
  3296. });
  3297. }
  3298. }
  3299. }
  3300. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  3301. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3302. toggleNATField(fieldKey, true);
  3303. let strVal = String(value);
  3304. if (hasInvert) {
  3305. const inv = strVal.startsWith('!');
  3306. if (inv) strVal = strVal.slice(1);
  3307. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3308. if (invEl) invEl.checked = inv;
  3309. }
  3310. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3311. if (valEl) valEl.value = strVal;
  3312. } else {
  3313. toggleNATField(fieldKey, false);
  3314. }
  3315. }
  3316. function getNATFieldVal(fieldKey, hasInvert = false) {
  3317. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3318. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3319. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3320. let v = valEl ? valEl.value.trim() : '';
  3321. if (!v) return '';
  3322. if (hasInvert) {
  3323. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3324. if (invEl && invEl.checked) {
  3325. v = '!' + v.replace(/^!/, '');
  3326. }
  3327. }
  3328. return v;
  3329. }
  3330. function toggleMaximizeNATModal() {
  3331. const win = document.getElementById('nat-modal-window');
  3332. if (!win) return;
  3333. if (win.classList.contains('max-w-[720px]')) {
  3334. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3335. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3336. } else {
  3337. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3338. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3339. }
  3340. }
  3341. function handleNATChainChange() {
  3342. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  3343. const actSel = document.getElementById('nat-modal-action');
  3344. if (actSel) {
  3345. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  3346. actSel.value = 'masquerade';
  3347. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  3348. actSel.value = 'dst-nat';
  3349. }
  3350. }
  3351. toggleNATActionFields();
  3352. }
  3353. function toggleNATActionFields() {
  3354. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  3355. const rowAddr = document.getElementById('nat-row-toaddr');
  3356. const rowPort = document.getElementById('nat-row-toport');
  3357. const jumpBox = document.getElementById('nat-action-jump-box');
  3358. const addrBox = document.getElementById('nat-action-addrlist-box');
  3359. // Hide all dynamic rows first
  3360. if (rowAddr) rowAddr.classList.add('hidden');
  3361. if (rowPort) rowPort.classList.add('hidden');
  3362. if (jumpBox) jumpBox.classList.add('hidden');
  3363. if (addrBox) addrBox.classList.add('hidden');
  3364. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  3365. if (rowAddr) rowAddr.classList.remove('hidden');
  3366. if (rowPort) rowPort.classList.remove('hidden');
  3367. } else if (act === 'redirect' || act === 'masquerade') {
  3368. if (rowPort) rowPort.classList.remove('hidden');
  3369. } else if (act === 'jump') {
  3370. if (jumpBox) jumpBox.classList.remove('hidden');
  3371. } else if (act.includes('address-list') || act.includes('address list')) {
  3372. if (addrBox) addrBox.classList.remove('hidden');
  3373. }
  3374. if (act === 'log') {
  3375. const logEl = document.getElementById('nat-modal-log');
  3376. if (logEl) logEl.checked = true;
  3377. toggleNATField('logprefix', true);
  3378. }
  3379. }
  3380. function toggleNATLogPrefix() {
  3381. const isLog = document.getElementById('nat-modal-log')?.checked;
  3382. toggleNATField('logprefix', !!isLog);
  3383. }
  3384. function openAddNATModal() {
  3385. switchNATRuleTab('general');
  3386. const badge = document.getElementById('nat-modal-badge');
  3387. if (badge) badge.innerText = 'New...';
  3388. document.getElementById('nat-modal-id').value = '';
  3389. document.getElementById('nat-modal-enabled').checked = true;
  3390. document.getElementById('nat-modal-comment').value = '';
  3391. document.getElementById('nat-modal-chain').value = 'srcnat';
  3392. document.getElementById('nat-modal-action').value = 'masquerade';
  3393. document.getElementById('nat-modal-toaddr').value = '';
  3394. document.getElementById('nat-modal-toport').value = '';
  3395. document.getElementById('nat-modal-log').checked = false;
  3396. populateInterfaceSelect('nat-val-iniface');
  3397. populateInterfaceSelect('nat-val-outiface');
  3398. populateAddressListSelect('nat-val-srclist');
  3399. populateAddressListSelect('nat-val-dstlist');
  3400. populateGeoIPSelect('nat-val-srcgeo');
  3401. populateGeoIPSelect('nat-val-dstgeo');
  3402. const allFieldKeys = [
  3403. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3404. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3405. 'routingmark', 'conntype',
  3406. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3407. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3408. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3409. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  3410. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3411. ];
  3412. allFieldKeys.forEach(k => toggleNATField(k, false));
  3413. resetCurrentNATRuleCounters();
  3414. toggleNATActionFields();
  3415. document.getElementById('nat-modal').classList.remove('hidden');
  3416. }
  3417. function openEditNATModal(id) {
  3418. const r = (state.natRules || []).find(rule => rule.id === id);
  3419. if (!r) return;
  3420. switchNATRuleTab('general');
  3421. const badge = document.getElementById('nat-modal-badge');
  3422. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3423. document.getElementById('nat-modal-id').value = r.id;
  3424. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  3425. document.getElementById('nat-modal-comment').value = r.comment || '';
  3426. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  3427. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  3428. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  3429. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  3430. document.getElementById('nat-modal-log').checked = !!r.log;
  3431. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3432. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3433. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3434. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3435. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  3436. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  3437. setNATFieldVal('src', r.src_address, true);
  3438. setNATFieldVal('dst', r.dst_address, true);
  3439. setNATFieldVal('srclist', r.src_address_list, true);
  3440. setNATFieldVal('dstlist', r.dst_address_list, true);
  3441. setNATFieldVal('srcgeo', r.src_geoip, true);
  3442. setNATFieldVal('dstgeo', r.dst_geoip, true);
  3443. if (r.protocol && r.protocol !== 'all') {
  3444. setNATFieldVal('proto', r.protocol, true);
  3445. } else {
  3446. toggleNATField('proto', false);
  3447. }
  3448. setNATFieldVal('sport', r.src_port, true);
  3449. setNATFieldVal('dport', r.dst_port, true);
  3450. setNATFieldVal('anyport', r.any_port, true);
  3451. setNATFieldVal('iniface', r.in_interface, true);
  3452. setNATFieldVal('outiface', r.out_interface, true);
  3453. setNATFieldVal('inifacelist', r.in_interface_list, true);
  3454. setNATFieldVal('outifacelist', r.out_interface_list, true);
  3455. setNATFieldVal('pktmark', r.packet_mark, true);
  3456. setNATFieldVal('connmark', r.connection_mark, true);
  3457. setNATFieldVal('routingmark', r.routing_mark, true);
  3458. setNATFieldVal('conntype', r.connection_type, false);
  3459. // Advanced tab fields
  3460. setNATFieldVal('layer7', r.layer7_protocol, false);
  3461. setNATFieldVal('content', r.content, false);
  3462. setNATFieldVal('connbytes', r.connection_bytes, false);
  3463. setNATFieldVal('connrate', r.connection_rate, false);
  3464. setNATFieldVal('pcc', r.pcc, false);
  3465. setNATFieldVal('srcmac', r.src_mac_address, true);
  3466. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  3467. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  3468. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3469. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3470. setNATFieldVal('ipsec', r.ipsec_policy, false);
  3471. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  3472. setNATFieldVal('priority', r.priority, false);
  3473. setNATFieldVal('dscp', r.dscp, false);
  3474. setNATFieldVal('tcpmss', r.tcp_mss, false);
  3475. if (r.tos) {
  3476. const tosEl = document.getElementById('nat-val-tos');
  3477. if (tosEl) tosEl.value = r.tos;
  3478. }
  3479. setNATFieldVal('pktsize', r.packet_size, false);
  3480. setNATFieldVal('random', r.random, false);
  3481. setNATFieldVal('icmpoptions', r.icmp_options, false);
  3482. setNATFieldVal('ipv4options', r.ipv4_options, false);
  3483. setNATFieldVal('ttl', r.ttl, false);
  3484. // Extra tab fields
  3485. setNATFieldVal('time', r.time, false);
  3486. if (r.days) {
  3487. toggleNATField('days', true);
  3488. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3489. const chk = document.getElementById(`nat-day-${d}`);
  3490. if (chk) chk.checked = r.days.includes(d);
  3491. });
  3492. } else {
  3493. toggleNATField('days', false);
  3494. }
  3495. setNATFieldVal('limit', r.limit, false);
  3496. setNATFieldVal('dstlimit', r.dst_limit, false);
  3497. setNATFieldVal('psd', r.psd, false);
  3498. // Action fields
  3499. if (r.jump_target) {
  3500. const jtEl = document.getElementById('nat-modal-jumptarget');
  3501. if (jtEl) jtEl.value = r.jump_target;
  3502. }
  3503. if (r.address_list) {
  3504. const alEl = document.getElementById('nat-modal-action-addrlist');
  3505. if (alEl) alEl.value = r.address_list;
  3506. }
  3507. if (r.address_list_timeout) {
  3508. const toEl = document.getElementById('nat-modal-action-timeout');
  3509. if (toEl) toEl.value = r.address_list_timeout;
  3510. }
  3511. setNATFieldVal('logprefix', r.log_prefix, false);
  3512. // Statistics
  3513. const bEl = document.getElementById('nat-stat-bytes');
  3514. const pEl = document.getElementById('nat-stat-packets');
  3515. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3516. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3517. state.natLastBytes = r.bytes || 0;
  3518. state.natLastPackets = r.packets || 0;
  3519. state.natLastTimestamp = Date.now();
  3520. state.natStatRateHistory = new Array(30).fill(0);
  3521. state.natStatPktHistory = new Array(30).fill(0);
  3522. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3523. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3524. toggleNATActionFields();
  3525. document.getElementById('nat-modal').classList.remove('hidden');
  3526. }
  3527. function closeNATModal() {
  3528. stopNATStatPolling();
  3529. document.getElementById('nat-modal').classList.add('hidden');
  3530. }
  3531. function copyNATRule() {
  3532. document.getElementById('nat-modal-id').value = '';
  3533. const badge = document.getElementById('nat-modal-badge');
  3534. if (badge) badge.innerText = 'New...';
  3535. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  3536. }
  3537. function resetCurrentNATRuleCounters() {
  3538. state.natStatRateHistory = new Array(30).fill(0);
  3539. state.natStatPktHistory = new Array(30).fill(0);
  3540. state.natLastBytes = 0;
  3541. state.natLastPackets = 0;
  3542. state.natLastTimestamp = Date.now();
  3543. const bEl = document.getElementById('nat-stat-bytes');
  3544. const pEl = document.getElementById('nat-stat-packets');
  3545. const rEl = document.getElementById('nat-stat-rate');
  3546. const prEl = document.getElementById('nat-stat-pktrate');
  3547. if (bEl) bEl.value = '0 B';
  3548. if (pEl) pEl.value = '0';
  3549. if (rEl) rEl.value = '0 bps';
  3550. if (prEl) prEl.value = '0 p/s';
  3551. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3552. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3553. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  3554. }
  3555. async function applyNATRule(closeAfter = false) {
  3556. const id = document.getElementById('nat-modal-id').value;
  3557. const chain = document.getElementById('nat-modal-chain').value;
  3558. const action = document.getElementById('nat-modal-action').value;
  3559. const comment = document.getElementById('nat-modal-comment').value.trim();
  3560. const enabled = document.getElementById('nat-modal-enabled').checked;
  3561. const src = getNATFieldVal('src', true);
  3562. const dst = getNATFieldVal('dst', true);
  3563. const srclist = getNATFieldVal('srclist', true);
  3564. const dstlist = getNATFieldVal('dstlist', true);
  3565. const srcgeo = getNATFieldVal('srcgeo', true);
  3566. const dstgeo = getNATFieldVal('dstgeo', true);
  3567. const proto = getNATFieldVal('proto', true);
  3568. const sport = getNATFieldVal('sport', true);
  3569. const dport = getNATFieldVal('dport', true);
  3570. const anyport = getNATFieldVal('anyport', true);
  3571. const iniface = getNATFieldVal('iniface', true);
  3572. const outiface = getNATFieldVal('outiface', true);
  3573. const inifacelist = getNATFieldVal('inifacelist', true);
  3574. const outifacelist = getNATFieldVal('outifacelist', true);
  3575. const pktmark = getNATFieldVal('pktmark', true);
  3576. const connmark = getNATFieldVal('connmark', true);
  3577. const routingmark = getNATFieldVal('routingmark', true);
  3578. const conntype = getNATFieldVal('conntype', false);
  3579. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  3580. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  3581. const payload = {
  3582. id,
  3583. chain,
  3584. action,
  3585. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  3586. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  3587. protocol: proto || 'all',
  3588. src_address: src,
  3589. dst_address: dst,
  3590. src_port: sport,
  3591. dst_port: dport,
  3592. any_port: anyport,
  3593. in_interface: iniface,
  3594. out_interface: outiface,
  3595. in_interface_list: inifacelist,
  3596. out_interface_list: outifacelist,
  3597. packet_mark: pktmark,
  3598. connection_mark: connmark,
  3599. routing_mark: routingmark,
  3600. connection_type: conntype,
  3601. src_address_list: srclist,
  3602. dst_address_list: dstlist,
  3603. src_geoip: srcgeo,
  3604. dst_geoip: dstgeo,
  3605. comment,
  3606. disabled: !enabled,
  3607. // Advanced tab
  3608. layer7_protocol: getNATFieldVal('layer7', false),
  3609. content: getNATFieldVal('content', false),
  3610. connection_bytes: getNATFieldVal('connbytes', false),
  3611. connection_rate: getNATFieldVal('connrate', false),
  3612. pcc: getNATFieldVal('pcc', false),
  3613. src_mac_address: getNATFieldVal('srcmac', true),
  3614. out_bridge_port: getNATFieldVal('outbridgeport', false),
  3615. in_bridge_port: getNATFieldVal('inbridgeport', false),
  3616. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  3617. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  3618. ipsec_policy: getNATFieldVal('ipsec', false),
  3619. ingress_priority: getNATFieldVal('ingresspriority', false),
  3620. priority: getNATFieldVal('priority', false),
  3621. dscp: getNATFieldVal('dscp', false),
  3622. tcp_mss: getNATFieldVal('tcpmss', false),
  3623. tos: document.getElementById('nat-val-tos')?.value || '',
  3624. packet_size: getNATFieldVal('pktsize', false),
  3625. random: getNATFieldVal('random', false),
  3626. icmp_options: getNATFieldVal('icmpoptions', false),
  3627. ipv4_options: getNATFieldVal('ipv4options', false),
  3628. ttl: getNATFieldVal('ttl', false),
  3629. // Extra tab
  3630. time: getNATFieldVal('time', false),
  3631. limit: getNATFieldVal('limit', false),
  3632. dst_limit: getNATFieldVal('dstlimit', false),
  3633. psd: getNATFieldVal('psd', false),
  3634. // Action tab
  3635. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  3636. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  3637. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  3638. log: document.getElementById('nat-modal-log')?.checked || false,
  3639. log_prefix: getNATFieldVal('logprefix', false)
  3640. };
  3641. try {
  3642. const res = await fetch(`${API_BASE}/firewall/nat`, {
  3643. method: 'POST',
  3644. headers: { 'Content-Type': 'application/json' },
  3645. body: JSON.stringify(payload)
  3646. });
  3647. if (res.ok) {
  3648. const data = await res.json();
  3649. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  3650. loadFirewall(false);
  3651. if (closeAfter) {
  3652. closeNATModal();
  3653. } else {
  3654. if (data.id) {
  3655. document.getElementById('nat-modal-id').value = data.id;
  3656. const badge = document.getElementById('nat-modal-badge');
  3657. if (badge) badge.innerText = `#${data.id}`;
  3658. }
  3659. }
  3660. } else {
  3661. const err = await res.json();
  3662. showToast('Error', err.message || 'Failed to save rule', 'error');
  3663. }
  3664. } catch (err) {
  3665. showToast('Error', err.message, 'error');
  3666. }
  3667. }
  3668. function submitSaveNATRule(e) {
  3669. if (e && e.preventDefault) e.preventDefault();
  3670. return applyNATRule(true);
  3671. }
  3672. function startNATStatPolling() {
  3673. stopNATStatPolling();
  3674. pollNATRuleStats();
  3675. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  3676. }
  3677. function stopNATStatPolling() {
  3678. if (state.natStatInterval) {
  3679. clearInterval(state.natStatInterval);
  3680. state.natStatInterval = null;
  3681. }
  3682. }
  3683. async function pollNATRuleStats() {
  3684. const id = document.getElementById('nat-modal-id')?.value;
  3685. if (!id) {
  3686. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  3687. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  3688. return;
  3689. }
  3690. try {
  3691. const res = await fetch(`${API_BASE}/firewall/nat`);
  3692. if (!res.ok) return;
  3693. const rules = await res.json();
  3694. const r = rules.find(x => x.id === id);
  3695. if (!r) return;
  3696. const now = Date.now();
  3697. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  3698. state.natLastTimestamp = now;
  3699. const curBytes = r.bytes || 0;
  3700. const curPackets = r.packets || 0;
  3701. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  3702. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  3703. state.natLastBytes = curBytes;
  3704. state.natLastPackets = curPackets;
  3705. const rateBps = Math.round((deltaBytes * 8) / dt);
  3706. const ratePkt = Math.round(deltaPkts / dt);
  3707. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  3708. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  3709. state.natStatRateHistory.push(rateBps);
  3710. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  3711. state.natStatPktHistory.push(ratePkt);
  3712. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  3713. const bEl = document.getElementById('nat-stat-bytes');
  3714. const pEl = document.getElementById('nat-stat-packets');
  3715. const rEl = document.getElementById('nat-stat-rate');
  3716. const prEl = document.getElementById('nat-stat-pktrate');
  3717. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  3718. if (pEl) pEl.value = curPackets.toLocaleString();
  3719. if (rEl) rEl.value = formatBps(rateBps);
  3720. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  3721. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3722. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3723. } catch (e) {
  3724. console.error('Error polling NAT rule stats', e);
  3725. }
  3726. }
  3727. async function moveNATRule(id, dir) {
  3728. try {
  3729. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  3730. method: 'POST',
  3731. headers: { 'Content-Type': 'application/json' },
  3732. body: JSON.stringify({ direction: dir })
  3733. });
  3734. if (res.ok) loadFirewall(false);
  3735. } catch (err) {
  3736. showToast('Error', err.message, 'error');
  3737. }
  3738. }
  3739. async function toggleNATRuleState(id, disabled) {
  3740. try {
  3741. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  3742. method: 'POST',
  3743. headers: { 'Content-Type': 'application/json' },
  3744. body: JSON.stringify({ disabled })
  3745. });
  3746. if (res.ok) loadFirewall(false);
  3747. } catch (err) {
  3748. showToast('Error', err.message, 'error');
  3749. }
  3750. }
  3751. async function deleteNATRule(id) {
  3752. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  3753. try {
  3754. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3755. if (res.ok) {
  3756. showToast('Deleted', 'NAT rule removed', 'success');
  3757. loadFirewall(false);
  3758. }
  3759. } catch (err) {
  3760. showToast('Error', err.message, 'error');
  3761. }
  3762. }
  3763. // ----------------- Mangle Rules -----------------
  3764. function renderMangleRules() {
  3765. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  3766. const tbody = document.getElementById('mangle-table-body');
  3767. const empty = document.getElementById('mangle-empty');
  3768. if (!tbody) return;
  3769. tbody.innerHTML = '';
  3770. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3771. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  3772. if (rules.length === 0) {
  3773. empty?.classList.remove('hidden');
  3774. return;
  3775. }
  3776. empty?.classList.add('hidden');
  3777. rules.forEach((r, idx) => {
  3778. const tr = document.createElement('tr');
  3779. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3780. let markVal = '<span class="text-slate-500">-</span>';
  3781. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  3782. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  3783. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  3784. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  3785. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  3786. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  3787. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  3788. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  3789. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  3790. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  3791. else if (r.action.includes('address-list') || r.action.includes('address list')) markVal = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  3792. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  3793. tr.innerHTML = `
  3794. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3795. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3796. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  3797. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3798. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3799. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  3800. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  3801. <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>
  3802. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3803. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3804. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3805. </td>
  3806. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3807. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3808. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3809. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3810. <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>
  3811. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3812. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3813. </td>
  3814. `;
  3815. tbody.appendChild(tr);
  3816. });
  3817. }
  3818. // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3819. function switchMangleRuleTab(tab) {
  3820. state.activeMangleRuleTab = tab;
  3821. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  3822. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3823. btn.classList.add('text-slate-400', 'border-transparent');
  3824. });
  3825. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  3826. if (activeBtn) {
  3827. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3828. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3829. }
  3830. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  3831. const activePane = document.getElementById(`mangle-pane-${tab}`);
  3832. if (activePane) activePane.classList.remove('hidden');
  3833. if (tab === 'statistics') {
  3834. startMangleStatPolling();
  3835. } else {
  3836. stopMangleStatPolling();
  3837. }
  3838. }
  3839. function toggleMangleField(fieldKey, expand) {
  3840. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  3841. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  3842. if (!plusBtn || !fieldBox) return;
  3843. if (expand) {
  3844. plusBtn.classList.add('hidden');
  3845. fieldBox.classList.remove('hidden');
  3846. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  3847. if (valInput) valInput.focus();
  3848. } else {
  3849. fieldBox.classList.add('hidden');
  3850. plusBtn.classList.remove('hidden');
  3851. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  3852. if (valInput) {
  3853. if (valInput.tagName === 'SELECT') {
  3854. valInput.selectedIndex = 0;
  3855. } else {
  3856. valInput.value = '';
  3857. }
  3858. }
  3859. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  3860. if (invInput) invInput.checked = false;
  3861. if (fieldKey === 'cs') {
  3862. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  3863. const el = document.getElementById(id);
  3864. if (el) el.checked = false;
  3865. });
  3866. }
  3867. if (fieldKey === 'natstate') {
  3868. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  3869. const el = document.getElementById(id);
  3870. if (el) el.checked = false;
  3871. });
  3872. }
  3873. }
  3874. }
  3875. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  3876. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3877. toggleMangleField(fieldKey, true);
  3878. let strVal = String(value);
  3879. if (hasInvert) {
  3880. const inv = strVal.startsWith('!');
  3881. if (inv) strVal = strVal.slice(1);
  3882. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  3883. if (invEl) invEl.checked = inv;
  3884. }
  3885. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  3886. if (valEl) valEl.value = strVal;
  3887. } else {
  3888. toggleMangleField(fieldKey, false);
  3889. }
  3890. }
  3891. function getMangleFieldVal(fieldKey, hasInvert = false) {
  3892. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  3893. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3894. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  3895. let v = valEl ? valEl.value.trim() : '';
  3896. if (!v) return '';
  3897. if (hasInvert) {
  3898. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  3899. if (invEl && invEl.checked) {
  3900. v = '!' + v.replace(/^!/, '');
  3901. }
  3902. }
  3903. return v;
  3904. }
  3905. function toggleMaximizeMangleModal() {
  3906. const win = document.getElementById('mangle-modal-window');
  3907. if (!win) return;
  3908. if (win.classList.contains('max-w-[720px]')) {
  3909. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3910. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3911. } else {
  3912. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3913. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3914. }
  3915. }
  3916. function toggleMangleActionFields() {
  3917. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  3918. // Hide all dynamic rows first
  3919. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  3920. const el = document.getElementById(`mangle-row-${id}`);
  3921. if (el) el.classList.add('hidden');
  3922. });
  3923. const jumpBox = document.getElementById('mangle-action-jump-box');
  3924. const addrBox = document.getElementById('mangle-action-addrlist-box');
  3925. if (jumpBox) jumpBox.classList.add('hidden');
  3926. if (addrBox) addrBox.classList.add('hidden');
  3927. // Activate matching rows
  3928. if (act === 'mark-connection') {
  3929. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  3930. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3931. } else if (act === 'mark-routing') {
  3932. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  3933. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3934. } else if (act === 'mark-packet') {
  3935. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  3936. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3937. } else if (act === 'change-mss') {
  3938. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  3939. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3940. } else if (act === 'change-dscp') {
  3941. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  3942. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3943. } else if (act === 'change-ttl') {
  3944. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  3945. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3946. } else if (act === 'set-priority') {
  3947. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  3948. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3949. } else if (act === 'route') {
  3950. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  3951. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3952. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  3953. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  3954. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3955. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  3956. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3957. } else if (act === 'jump') {
  3958. if (jumpBox) jumpBox.classList.remove('hidden');
  3959. } else if (act.includes('address-list') || act.includes('address list')) {
  3960. if (addrBox) addrBox.classList.remove('hidden');
  3961. }
  3962. if (act === 'log') {
  3963. const logEl = document.getElementById('mangle-modal-log');
  3964. if (logEl) logEl.checked = true;
  3965. toggleMangleField('logprefix', true);
  3966. }
  3967. }
  3968. function toggleMangleLogPrefix() {
  3969. const isLog = document.getElementById('mangle-modal-log')?.checked;
  3970. toggleMangleField('logprefix', !!isLog);
  3971. }
  3972. const allMangleFieldKeys = [
  3973. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3974. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3975. 'routingmark', 'conntype', 'cs', 'natstate',
  3976. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3977. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3978. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3979. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3980. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  3981. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  3982. ];
  3983. function openAddMangleModal() {
  3984. switchMangleRuleTab('general');
  3985. const badge = document.getElementById('mangle-modal-badge');
  3986. if (badge) badge.innerText = 'New...';
  3987. document.getElementById('mangle-modal-id').value = '';
  3988. document.getElementById('mangle-modal-enabled').checked = true;
  3989. document.getElementById('mangle-modal-comment').value = '';
  3990. document.getElementById('mangle-modal-chain').value = 'prerouting';
  3991. document.getElementById('mangle-modal-action').value = 'mark-connection';
  3992. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  3993. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  3994. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  3995. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  3996. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  3997. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  3998. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  3999. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  4000. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  4001. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  4002. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  4003. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  4004. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  4005. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  4006. populateInterfaceSelect('mangle-val-iniface');
  4007. populateInterfaceSelect('mangle-val-outiface');
  4008. populateAddressListSelect('mangle-val-srclist');
  4009. populateAddressListSelect('mangle-val-dstlist');
  4010. populateGeoIPSelect('mangle-val-srcgeo');
  4011. populateGeoIPSelect('mangle-val-dstgeo');
  4012. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  4013. resetCurrentMangleRuleCounters();
  4014. toggleMangleActionFields();
  4015. document.getElementById('mangle-modal').classList.remove('hidden');
  4016. }
  4017. function openEditMangleModal(id) {
  4018. const r = (state.mangleRules || []).find(rule => rule.id === id);
  4019. if (!r) return;
  4020. switchMangleRuleTab('general');
  4021. const badge = document.getElementById('mangle-modal-badge');
  4022. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4023. document.getElementById('mangle-modal-id').value = r.id;
  4024. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  4025. document.getElementById('mangle-modal-comment').value = r.comment || '';
  4026. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  4027. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  4028. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  4029. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  4030. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  4031. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  4032. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  4033. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  4034. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  4035. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  4036. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  4037. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  4038. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  4039. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  4040. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  4041. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  4042. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4043. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4044. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4045. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4046. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  4047. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  4048. setMangleFieldVal('src', r.src_address, true);
  4049. setMangleFieldVal('dst', r.dst_address, true);
  4050. setMangleFieldVal('srclist', r.src_address_list, true);
  4051. setMangleFieldVal('dstlist', r.dst_address_list, true);
  4052. setMangleFieldVal('srcgeo', r.src_geoip, true);
  4053. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  4054. if (r.protocol && r.protocol !== 'all') {
  4055. setMangleFieldVal('proto', r.protocol, true);
  4056. } else {
  4057. toggleMangleField('proto', false);
  4058. }
  4059. setMangleFieldVal('sport', r.src_port, true);
  4060. setMangleFieldVal('dport', r.dst_port, true);
  4061. setMangleFieldVal('anyport', r.any_port, true);
  4062. setMangleFieldVal('iniface', r.in_interface, true);
  4063. setMangleFieldVal('outiface', r.out_interface, true);
  4064. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  4065. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  4066. setMangleFieldVal('pktmark', r.packet_mark, true);
  4067. setMangleFieldVal('connmark', r.connection_mark, true);
  4068. setMangleFieldVal('routingmark', r.routing_mark, true);
  4069. setMangleFieldVal('conntype', r.connection_type, false);
  4070. // Connection State
  4071. const states = r.connection_state || [];
  4072. if (states.length > 0) {
  4073. toggleMangleField('cs', true);
  4074. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4075. const el = document.getElementById(`mangle-modal-cs-${s}`);
  4076. if (el) el.checked = states.includes(s);
  4077. });
  4078. } else {
  4079. toggleMangleField('cs', false);
  4080. }
  4081. // Connection NAT State
  4082. const natStates = r.connection_nat_state || [];
  4083. if (natStates.length > 0) {
  4084. toggleMangleField('natstate', true);
  4085. ['srcnat', 'dstnat'].forEach(s => {
  4086. const el = document.getElementById(`mangle-modal-nat-${s}`);
  4087. if (el) el.checked = natStates.includes(s);
  4088. });
  4089. } else {
  4090. toggleMangleField('natstate', false);
  4091. }
  4092. // Advanced tab fields
  4093. setMangleFieldVal('layer7', r.layer7_protocol, false);
  4094. setMangleFieldVal('content', r.content, false);
  4095. setMangleFieldVal('connbytes', r.connection_bytes, false);
  4096. setMangleFieldVal('connrate', r.connection_rate, false);
  4097. setMangleFieldVal('pcc', r.pcc, false);
  4098. setMangleFieldVal('srcmac', r.src_mac_address, true);
  4099. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  4100. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  4101. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4102. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4103. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  4104. setMangleFieldVal('tlshost', r.tls_host, false);
  4105. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  4106. setMangleFieldVal('priority', r.priority, false);
  4107. setMangleFieldVal('dscp', r.dscp, false);
  4108. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  4109. if (r.tos) {
  4110. const tosEl = document.getElementById('mangle-val-tos');
  4111. if (tosEl) tosEl.value = r.tos;
  4112. }
  4113. setMangleFieldVal('pktsize', r.packet_size, false);
  4114. setMangleFieldVal('random', r.random, false);
  4115. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  4116. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  4117. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  4118. setMangleFieldVal('ttl', r.ttl, false);
  4119. // Extra tab fields
  4120. setMangleFieldVal('nth', r.nth, false);
  4121. setMangleFieldVal('connlimit', r.connection_limit, false);
  4122. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  4123. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  4124. setMangleFieldVal('hotspot', r.hotspot, false);
  4125. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  4126. setMangleFieldVal('limit', r.limit, false);
  4127. setMangleFieldVal('dstlimit', r.dst_limit, false);
  4128. setMangleFieldVal('time', r.time, false);
  4129. setMangleFieldVal('psd', r.psd, false);
  4130. // Action fields
  4131. if (r.jump_target) {
  4132. const jtEl = document.getElementById('mangle-modal-jumptarget');
  4133. if (jtEl) jtEl.value = r.jump_target;
  4134. }
  4135. if (r.address_list) {
  4136. const alEl = document.getElementById('mangle-modal-action-addrlist');
  4137. if (alEl) alEl.value = r.address_list;
  4138. }
  4139. if (r.address_list_timeout) {
  4140. const toEl = document.getElementById('mangle-modal-action-timeout');
  4141. if (toEl) toEl.value = r.address_list_timeout;
  4142. }
  4143. setMangleFieldVal('logprefix', r.log_prefix, false);
  4144. // Statistics
  4145. const bEl = document.getElementById('mangle-stat-bytes');
  4146. const pEl = document.getElementById('mangle-stat-packets');
  4147. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4148. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4149. state.mangleLastBytes = r.bytes || 0;
  4150. state.mangleLastPackets = r.packets || 0;
  4151. state.mangleLastTimestamp = Date.now();
  4152. state.mangleStatRateHistory = new Array(30).fill(0);
  4153. state.mangleStatPktHistory = new Array(30).fill(0);
  4154. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4155. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4156. toggleMangleActionFields();
  4157. document.getElementById('mangle-modal').classList.remove('hidden');
  4158. }
  4159. function closeMangleModal() {
  4160. stopMangleStatPolling();
  4161. document.getElementById('mangle-modal').classList.add('hidden');
  4162. }
  4163. function copyMangleRule() {
  4164. document.getElementById('mangle-modal-id').value = '';
  4165. const badge = document.getElementById('mangle-modal-badge');
  4166. if (badge) badge.innerText = 'New...';
  4167. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  4168. }
  4169. function resetCurrentMangleRuleCounters() {
  4170. state.mangleStatRateHistory = new Array(30).fill(0);
  4171. state.mangleStatPktHistory = new Array(30).fill(0);
  4172. state.mangleLastBytes = 0;
  4173. state.mangleLastPackets = 0;
  4174. state.mangleLastTimestamp = Date.now();
  4175. const bEl = document.getElementById('mangle-stat-bytes');
  4176. const pEl = document.getElementById('mangle-stat-packets');
  4177. const rEl = document.getElementById('mangle-stat-rate');
  4178. const prEl = document.getElementById('mangle-stat-pktrate');
  4179. if (bEl) bEl.value = '0 B';
  4180. if (pEl) pEl.value = '0';
  4181. if (rEl) rEl.value = '0 bps';
  4182. if (prEl) prEl.value = '0 p/s';
  4183. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4184. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4185. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  4186. }
  4187. async function applyMangleRule(closeAfter = false) {
  4188. const id = document.getElementById('mangle-modal-id').value;
  4189. const chain = document.getElementById('mangle-modal-chain').value;
  4190. const action = document.getElementById('mangle-modal-action').value;
  4191. const comment = document.getElementById('mangle-modal-comment').value.trim();
  4192. const enabled = document.getElementById('mangle-modal-enabled').checked;
  4193. const src = getMangleFieldVal('src', true);
  4194. const dst = getMangleFieldVal('dst', true);
  4195. const srclist = getMangleFieldVal('srclist', true);
  4196. const dstlist = getMangleFieldVal('dstlist', true);
  4197. const srcgeo = getMangleFieldVal('srcgeo', true);
  4198. const dstgeo = getMangleFieldVal('dstgeo', true);
  4199. const proto = getMangleFieldVal('proto', true);
  4200. const sport = getMangleFieldVal('sport', true);
  4201. const dport = getMangleFieldVal('dport', true);
  4202. const anyport = getMangleFieldVal('anyport', true);
  4203. const iniface = getMangleFieldVal('iniface', true);
  4204. const outiface = getMangleFieldVal('outiface', true);
  4205. const inifacelist = getMangleFieldVal('inifacelist', true);
  4206. const outifacelist = getMangleFieldVal('outifacelist', true);
  4207. const pktmark = getMangleFieldVal('pktmark', true);
  4208. const connmark = getMangleFieldVal('connmark', true);
  4209. const routingmark = getMangleFieldVal('routingmark', true);
  4210. const conntype = getMangleFieldVal('conntype', false);
  4211. const states = [];
  4212. const csBox = document.getElementById('mangle-field-cs');
  4213. if (csBox && !csBox.classList.contains('hidden')) {
  4214. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4215. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  4216. });
  4217. }
  4218. const natStates = [];
  4219. const natBox = document.getElementById('mangle-field-natstate');
  4220. if (natBox && !natBox.classList.contains('hidden')) {
  4221. ['srcnat', 'dstnat'].forEach(s => {
  4222. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  4223. });
  4224. }
  4225. const payload = {
  4226. id,
  4227. chain,
  4228. action,
  4229. protocol: proto || 'all',
  4230. src_address: src,
  4231. dst_address: dst,
  4232. src_port: sport,
  4233. dst_port: dport,
  4234. any_port: anyport,
  4235. in_interface: iniface,
  4236. out_interface: outiface,
  4237. in_interface_list: inifacelist,
  4238. out_interface_list: outifacelist,
  4239. packet_mark: pktmark,
  4240. connection_mark: connmark,
  4241. routing_mark: routingmark,
  4242. connection_type: conntype,
  4243. connection_state: states,
  4244. connection_nat_state: natStates,
  4245. src_address_list: srclist,
  4246. dst_address_list: dstlist,
  4247. src_geoip: srcgeo,
  4248. dst_geoip: dstgeo,
  4249. comment,
  4250. disabled: !enabled,
  4251. // Advanced tab
  4252. layer7_protocol: getMangleFieldVal('layer7', false),
  4253. content: getMangleFieldVal('content', false),
  4254. connection_bytes: getMangleFieldVal('connbytes', false),
  4255. connection_rate: getMangleFieldVal('connrate', false),
  4256. pcc: getMangleFieldVal('pcc', false),
  4257. src_mac_address: getMangleFieldVal('srcmac', true),
  4258. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  4259. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  4260. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  4261. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  4262. ipsec_policy: getMangleFieldVal('ipsec', false),
  4263. tls_host: getMangleFieldVal('tlshost', false),
  4264. ingress_priority: getMangleFieldVal('ingresspriority', false),
  4265. priority: getMangleFieldVal('priority', false),
  4266. dscp: getMangleFieldVal('dscp', false),
  4267. tcp_mss: getMangleFieldVal('tcpmss', false),
  4268. tos: document.getElementById('mangle-val-tos')?.value || '',
  4269. packet_size: getMangleFieldVal('pktsize', false),
  4270. random: getMangleFieldVal('random', false),
  4271. tcp_flags: getMangleFieldVal('tcpflags', false),
  4272. icmp_options: getMangleFieldVal('icmpoptions', false),
  4273. ipv4_options: getMangleFieldVal('ipv4options', false),
  4274. ttl: getMangleFieldVal('ttl', false),
  4275. // Extra tab
  4276. nth: getMangleFieldVal('nth', false),
  4277. connection_limit: getMangleFieldVal('connlimit', false),
  4278. src_address_type: getMangleFieldVal('srcaddrtype', false),
  4279. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  4280. hotspot: getMangleFieldVal('hotspot', false),
  4281. ip_fragment: getMangleFieldVal('ipfragment', false),
  4282. limit: getMangleFieldVal('limit', false),
  4283. dst_limit: getMangleFieldVal('dstlimit', false),
  4284. time: getMangleFieldVal('time', false),
  4285. psd: getMangleFieldVal('psd', false),
  4286. // Action tab
  4287. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  4288. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  4289. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  4290. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  4291. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  4292. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  4293. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  4294. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  4295. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  4296. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  4297. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  4298. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  4299. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  4300. log: document.getElementById('mangle-modal-log')?.checked || false,
  4301. log_prefix: getMangleFieldVal('logprefix', false)
  4302. };
  4303. try {
  4304. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  4305. method: 'POST',
  4306. headers: { 'Content-Type': 'application/json' },
  4307. body: JSON.stringify(payload)
  4308. });
  4309. if (res.ok) {
  4310. const data = await res.json();
  4311. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  4312. loadFirewall(false);
  4313. if (closeAfter) {
  4314. closeMangleModal();
  4315. } else {
  4316. if (data.id) {
  4317. document.getElementById('mangle-modal-id').value = data.id;
  4318. const badge = document.getElementById('mangle-modal-badge');
  4319. if (badge) badge.innerText = `#${data.id}`;
  4320. }
  4321. }
  4322. } else {
  4323. const err = await res.json();
  4324. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  4325. }
  4326. } catch (err) {
  4327. showToast('Error', err.message, 'error');
  4328. }
  4329. }
  4330. function submitSaveMangleRule(e) {
  4331. if (e && e.preventDefault) e.preventDefault();
  4332. return applyMangleRule(true);
  4333. }
  4334. function startMangleStatPolling() {
  4335. stopMangleStatPolling();
  4336. pollMangleRuleStats();
  4337. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  4338. }
  4339. function stopMangleStatPolling() {
  4340. if (state.mangleStatInterval) {
  4341. clearInterval(state.mangleStatInterval);
  4342. state.mangleStatInterval = null;
  4343. }
  4344. }
  4345. async function pollMangleRuleStats() {
  4346. const id = document.getElementById('mangle-modal-id')?.value;
  4347. if (!id) {
  4348. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  4349. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  4350. return;
  4351. }
  4352. try {
  4353. const res = await fetch(`${API_BASE}/firewall/mangle`);
  4354. if (!res.ok) return;
  4355. const rules = await res.json();
  4356. const r = rules.find(x => x.id === id);
  4357. if (!r) return;
  4358. const now = Date.now();
  4359. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  4360. state.mangleLastTimestamp = now;
  4361. const curBytes = r.bytes || 0;
  4362. const curPackets = r.packets || 0;
  4363. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  4364. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  4365. state.mangleLastBytes = curBytes;
  4366. state.mangleLastPackets = curPackets;
  4367. const rateBps = Math.round((deltaBytes * 8) / dt);
  4368. const ratePkt = Math.round(deltaPkts / dt);
  4369. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  4370. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  4371. state.mangleStatRateHistory.push(rateBps);
  4372. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  4373. state.mangleStatPktHistory.push(ratePkt);
  4374. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  4375. const bEl = document.getElementById('mangle-stat-bytes');
  4376. const pEl = document.getElementById('mangle-stat-packets');
  4377. const rEl = document.getElementById('mangle-stat-rate');
  4378. const prEl = document.getElementById('mangle-stat-pktrate');
  4379. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4380. if (pEl) pEl.value = curPackets.toLocaleString();
  4381. if (rEl) rEl.value = formatBps(rateBps);
  4382. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4383. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4384. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4385. } catch (e) {
  4386. console.error('Error polling Mangle rule stats', e);
  4387. }
  4388. }
  4389. async function moveMangleRule(id, dir) {
  4390. try {
  4391. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  4392. method: 'POST',
  4393. headers: { 'Content-Type': 'application/json' },
  4394. body: JSON.stringify({ direction: dir })
  4395. });
  4396. if (res.ok) loadFirewall(false);
  4397. } catch (err) {
  4398. showToast('Error', err.message, 'error');
  4399. }
  4400. }
  4401. async function toggleMangleRuleState(id, disabled) {
  4402. try {
  4403. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  4404. method: 'POST',
  4405. headers: { 'Content-Type': 'application/json' },
  4406. body: JSON.stringify({ disabled })
  4407. });
  4408. if (res.ok) loadFirewall(false);
  4409. } catch (err) {
  4410. showToast('Error', err.message, 'error');
  4411. }
  4412. }
  4413. async function deleteMangleRule(id) {
  4414. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  4415. try {
  4416. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4417. if (res.ok) {
  4418. showToast('Deleted', 'Mangle rule removed', 'success');
  4419. loadFirewall(false);
  4420. }
  4421. } catch (err) {
  4422. showToast('Error', err.message, 'error');
  4423. }
  4424. }
  4425. // ----------------- Address Lists -----------------
  4426. function renderAddressLists() {
  4427. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  4428. const tbody = document.getElementById('addrlist-table-body');
  4429. const empty = document.getElementById('addrlist-empty');
  4430. if (!tbody) return;
  4431. tbody.innerHTML = '';
  4432. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  4433. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  4434. // Update filter select
  4435. const sel = document.getElementById('addrlist-filter-name');
  4436. if (sel) {
  4437. const cur = sel.value;
  4438. sel.innerHTML = '<option value="">All Lists</option>';
  4439. const set = new Set((state.addressLists || []).map(a => a.name));
  4440. set.forEach(n => {
  4441. const opt = document.createElement('option');
  4442. opt.value = n;
  4443. opt.innerText = n;
  4444. if (n === cur) opt.selected = true;
  4445. sel.appendChild(opt);
  4446. });
  4447. }
  4448. if (entries.length === 0) {
  4449. empty?.classList.remove('hidden');
  4450. return;
  4451. }
  4452. empty?.classList.add('hidden');
  4453. entries.forEach((e, idx) => {
  4454. const tr = document.createElement('tr');
  4455. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  4456. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  4457. tr.innerHTML = `
  4458. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  4459. <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>
  4460. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  4461. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  4462. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  4463. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4464. <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>
  4465. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  4466. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4467. </td>
  4468. `;
  4469. tbody.appendChild(tr);
  4470. });
  4471. populateCommonAddrListDatalist();
  4472. }
  4473. function openAddAddrListModal() {
  4474. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  4475. document.getElementById('addrlist-modal-id').value = '';
  4476. document.getElementById('addrlist-modal-name').value = '';
  4477. document.getElementById('addrlist-modal-addr').value = '';
  4478. document.getElementById('addrlist-modal-comment').value = '';
  4479. document.getElementById('addrlist-modal-disabled').checked = false;
  4480. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4481. if (submitBtn) submitBtn.innerText = 'Add to List';
  4482. document.getElementById('addrlist-modal').classList.remove('hidden');
  4483. }
  4484. function openEditAddrListModal(id) {
  4485. const e = (state.addressLists || []).find(item => item.id === id);
  4486. if (!e) return;
  4487. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  4488. document.getElementById('addrlist-modal-id').value = e.id;
  4489. document.getElementById('addrlist-modal-name').value = e.name;
  4490. document.getElementById('addrlist-modal-addr').value = e.address;
  4491. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  4492. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  4493. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4494. if (submitBtn) submitBtn.innerText = 'Save Changes';
  4495. document.getElementById('addrlist-modal').classList.remove('hidden');
  4496. }
  4497. function closeAddrListModal() {
  4498. document.getElementById('addrlist-modal').classList.add('hidden');
  4499. }
  4500. async function submitSaveAddrList(e) {
  4501. e.preventDefault();
  4502. const id = document.getElementById('addrlist-modal-id').value;
  4503. const name = document.getElementById('addrlist-modal-name').value.trim();
  4504. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  4505. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  4506. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  4507. try {
  4508. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  4509. method: 'POST',
  4510. headers: { 'Content-Type': 'application/json' },
  4511. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  4512. });
  4513. if (res.ok) {
  4514. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  4515. closeAddrListModal();
  4516. loadFirewall(false);
  4517. } else {
  4518. const err = await res.json();
  4519. showToast('Error', err.message || 'Failed to save address list', 'error');
  4520. }
  4521. } catch (err) {
  4522. showToast('Error', err.message, 'error');
  4523. }
  4524. }
  4525. async function toggleAddrListState(id, disabled) {
  4526. try {
  4527. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  4528. method: 'POST',
  4529. headers: { 'Content-Type': 'application/json' },
  4530. body: JSON.stringify({ disabled })
  4531. });
  4532. if (res.ok) {
  4533. loadFirewall(false);
  4534. }
  4535. } catch (err) {
  4536. showToast('Error', err.message, 'error');
  4537. }
  4538. }
  4539. async function deleteAddrList(id) {
  4540. if (!confirm('Are you sure you want to delete this address list item?')) return;
  4541. try {
  4542. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4543. if (res.ok) {
  4544. showToast('Deleted', 'Address list item removed', 'info');
  4545. loadFirewall(false);
  4546. }
  4547. } catch (err) {
  4548. showToast('Error', err.message, 'error');
  4549. }
  4550. }
  4551. // ----------------- Geo-Location IP Management -----------------
  4552. async function loadGeoIP() {
  4553. try {
  4554. const [statusRes, countriesRes] = await Promise.all([
  4555. fetch(`${API_BASE}/firewall/geoip/status`),
  4556. fetch(`${API_BASE}/firewall/geoip/countries`)
  4557. ]);
  4558. if (statusRes.ok) state.geoStatus = await statusRes.json();
  4559. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  4560. updateGeoHeader();
  4561. renderGeoCountries();
  4562. } catch (err) {
  4563. console.error('Failed to load GeoIP:', err);
  4564. }
  4565. }
  4566. function getGeoUsageMap() {
  4567. const usage = {};
  4568. const checkRule = (r, type) => {
  4569. ['src_geoip', 'dst_geoip'].forEach(field => {
  4570. let val = (r && r[field]) || '';
  4571. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  4572. if (code) {
  4573. if (!usage[code]) usage[code] = [];
  4574. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  4575. if (!usage[code].includes(label)) usage[code].push(label);
  4576. }
  4577. });
  4578. };
  4579. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  4580. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  4581. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  4582. return usage;
  4583. }
  4584. function updateGeoHeader() {
  4585. const s = state.geoStatus || {};
  4586. const statusBadge = document.getElementById('geo-status-badge');
  4587. if (statusBadge) {
  4588. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  4589. statusBadge.className = s.auto_update
  4590. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  4591. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  4592. }
  4593. const intervalLabel = document.getElementById('geo-interval-label');
  4594. if (intervalLabel) {
  4595. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  4596. }
  4597. const usageMap = getGeoUsageMap();
  4598. const inUseCount = Object.keys(usageMap).length;
  4599. const activeCountEl = document.getElementById('geo-stat-active-countries');
  4600. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  4601. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  4602. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  4603. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  4604. if (lastSyncEl) {
  4605. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  4606. const d = new Date(s.last_updated);
  4607. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4608. } else {
  4609. lastSyncEl.innerText = 'Never (Sync Pending)';
  4610. }
  4611. }
  4612. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  4613. if (nextSyncEl) {
  4614. if (s.next_update && !s.next_update.startsWith('0001')) {
  4615. const d = new Date(s.next_update);
  4616. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4617. } else {
  4618. nextSyncEl.innerText = '-';
  4619. }
  4620. }
  4621. const badge = document.getElementById('fw-badge-geo');
  4622. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  4623. }
  4624. function renderGeoCountries() {
  4625. const tbody = document.getElementById('geo-table-body');
  4626. const empty = document.getElementById('geo-empty');
  4627. if (!tbody) return;
  4628. tbody.innerHTML = '';
  4629. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  4630. const continent = document.getElementById('geo-continent-filter')?.value || '';
  4631. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  4632. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  4633. const usageMap = getGeoUsageMap();
  4634. const countries = (state.geoCountries || []).filter(c => {
  4635. const isUsed = !!usageMap[c.code];
  4636. if (inUseOnly && !isUsed) return false;
  4637. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  4638. if (continent && c.continent !== continent) return false;
  4639. if (q) {
  4640. const matchCode = c.code.toLowerCase().includes(q);
  4641. const matchName = c.name.toLowerCase().includes(q);
  4642. if (!matchCode && !matchName) return false;
  4643. }
  4644. return true;
  4645. });
  4646. if (countries.length === 0) {
  4647. empty?.classList.remove('hidden');
  4648. return;
  4649. }
  4650. empty?.classList.add('hidden');
  4651. countries.forEach(c => {
  4652. const tr = document.createElement('tr');
  4653. const isUsed = !!usageMap[c.code];
  4654. const rulesUsing = usageMap[c.code] || [];
  4655. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  4656. let statusHtml = '';
  4657. if (isUsed) {
  4658. 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>`;
  4659. } else if (c.subnet_count > 0) {
  4660. 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>';
  4661. } else {
  4662. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  4663. }
  4664. tr.innerHTML = `
  4665. <td class="py-2.5 px-3 text-center">
  4666. <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'}">
  4667. ${c.code}
  4668. </span>
  4669. </td>
  4670. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  4671. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  4672. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  4673. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  4674. </td>
  4675. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  4676. <td class="py-2.5 px-3">
  4677. ${statusHtml}
  4678. </td>
  4679. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4680. <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>
  4681. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  4682. </td>
  4683. `;
  4684. tbody.appendChild(tr);
  4685. });
  4686. }
  4687. function quickFilterGeo(preset) {
  4688. const searchInput = document.getElementById('geo-search-input');
  4689. const continentSel = document.getElementById('geo-continent-filter');
  4690. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  4691. const cachedCheck = document.getElementById('geo-filter-cached-only');
  4692. if (searchInput) searchInput.value = '';
  4693. if (continentSel) continentSel.value = '';
  4694. if (inUseCheck) inUseCheck.checked = false;
  4695. if (cachedCheck) cachedCheck.checked = false;
  4696. if (preset === 'GR') {
  4697. if (searchInput) searchInput.value = 'Greece';
  4698. } else if (preset === 'Europe') {
  4699. if (continentSel) continentSel.value = 'Europe';
  4700. } else if (preset === 'HIGHRISK') {
  4701. if (searchInput) searchInput.value = 'China';
  4702. }
  4703. renderGeoCountries();
  4704. }
  4705. async function toggleGeoCountry(code, enabled) {
  4706. try {
  4707. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  4708. method: 'POST',
  4709. headers: { 'Content-Type': 'application/json' },
  4710. body: JSON.stringify({ enabled })
  4711. });
  4712. if (res.ok) {
  4713. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  4714. loadGeoIP();
  4715. } else {
  4716. const err = await res.json();
  4717. showToast('Error', err.message || 'Failed to toggle country', 'error');
  4718. }
  4719. } catch (err) {
  4720. showToast('Error', err.message, 'error');
  4721. }
  4722. }
  4723. async function updateGeoCountry(code) {
  4724. try {
  4725. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  4726. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  4727. if (res.ok) {
  4728. const data = await res.json();
  4729. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  4730. loadGeoIP();
  4731. } else {
  4732. const err = await res.json();
  4733. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  4734. }
  4735. } catch (err) {
  4736. showToast('Error', err.message, 'error');
  4737. }
  4738. }
  4739. async function triggerGeoUpdateNow() {
  4740. const spinner = document.getElementById('geo-update-spinner');
  4741. if (spinner) spinner.classList.remove('hidden');
  4742. try {
  4743. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  4744. if (res.ok) {
  4745. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  4746. setTimeout(() => {
  4747. loadGeoIP();
  4748. if (spinner) spinner.classList.add('hidden');
  4749. }, 2500);
  4750. } else {
  4751. const err = await res.json();
  4752. showToast('Notice', err.message || 'Update in progress', 'info');
  4753. if (spinner) spinner.classList.add('hidden');
  4754. }
  4755. } catch (err) {
  4756. showToast('Error', err.message, 'error');
  4757. if (spinner) spinner.classList.add('hidden');
  4758. }
  4759. }
  4760. async function applyGeoPreset(preset) {
  4761. try {
  4762. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  4763. method: 'POST',
  4764. headers: { 'Content-Type': 'application/json' },
  4765. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  4766. });
  4767. if (res.ok) {
  4768. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  4769. loadGeoIP();
  4770. }
  4771. } catch (err) {
  4772. showToast('Error', err.message, 'error');
  4773. }
  4774. }
  4775. function openGeoIntervalModal() {
  4776. const s = state.geoStatus || {};
  4777. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  4778. const sel = document.getElementById('geo-cfg-interval');
  4779. const customBox = document.getElementById('geo-cfg-custom-box');
  4780. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  4781. const curHours = s.interval_hours || 24;
  4782. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  4783. if (matchOption) {
  4784. sel.value = String(curHours);
  4785. customBox.classList.add('hidden');
  4786. } else {
  4787. sel.value = 'custom';
  4788. customHoursInput.value = curHours;
  4789. customBox.classList.remove('hidden');
  4790. }
  4791. document.getElementById('geo-interval-modal').classList.remove('hidden');
  4792. }
  4793. function closeGeoIntervalModal() {
  4794. document.getElementById('geo-interval-modal').classList.add('hidden');
  4795. }
  4796. function toggleCustomGeoInterval() {
  4797. const val = document.getElementById('geo-cfg-interval').value;
  4798. const customBox = document.getElementById('geo-cfg-custom-box');
  4799. if (val === 'custom') {
  4800. customBox.classList.remove('hidden');
  4801. } else {
  4802. customBox.classList.add('hidden');
  4803. }
  4804. }
  4805. async function submitGeoIntervalSettings(e) {
  4806. e.preventDefault();
  4807. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  4808. const intervalVal = document.getElementById('geo-cfg-interval').value;
  4809. let hours = 24;
  4810. if (intervalVal === 'custom') {
  4811. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  4812. } else {
  4813. hours = parseInt(intervalVal, 10) || 24;
  4814. }
  4815. try {
  4816. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  4817. method: 'POST',
  4818. headers: { 'Content-Type': 'application/json' },
  4819. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  4820. });
  4821. if (res.ok) {
  4822. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  4823. closeGeoIntervalModal();
  4824. loadGeoIP();
  4825. } else {
  4826. const err = await res.json();
  4827. showToast('Error', err.message || 'Failed to save schedule', 'error');
  4828. }
  4829. } catch (err) {
  4830. showToast('Error', err.message, 'error');
  4831. }
  4832. }
  4833. async function viewGeoSubnets(code, name) {
  4834. if (!name) {
  4835. const found = (state.geoCountries || []).find(x => x.code === code);
  4836. name = found ? found.name : code;
  4837. }
  4838. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  4839. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  4840. const listEl = document.getElementById('geo-subnets-list');
  4841. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  4842. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  4843. try {
  4844. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  4845. if (res.ok) {
  4846. const data = await res.json();
  4847. const subnets = data.subnets || [];
  4848. if (subnets.length === 0) {
  4849. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  4850. } else {
  4851. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  4852. }
  4853. } else {
  4854. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  4855. }
  4856. } catch (err) {
  4857. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  4858. }
  4859. }
  4860. function closeGeoSubnetsModal() {
  4861. document.getElementById('geo-subnets-modal').classList.add('hidden');
  4862. }
  4863. // ----------------- Active Connections Tracking -----------------
  4864. async function loadConnections() {
  4865. try {
  4866. const res = await fetch(`${API_BASE}/firewall/connections`);
  4867. const data = await res.json();
  4868. state.connections = Array.isArray(data) ? data : [];
  4869. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  4870. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  4871. renderConnections();
  4872. } catch (err) {
  4873. console.error('Failed to load connections:', err);
  4874. }
  4875. }
  4876. function renderConnections() {
  4877. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  4878. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  4879. const tbody = document.getElementById('conns-table-body');
  4880. const empty = document.getElementById('conns-empty');
  4881. if (!tbody) return;
  4882. tbody.innerHTML = '';
  4883. const conns = (state.connections || []).filter(c => {
  4884. if (protoFilter && c.protocol !== protoFilter) return false;
  4885. if (search) {
  4886. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  4887. if (!line.includes(search)) return false;
  4888. }
  4889. return true;
  4890. });
  4891. if (conns.length === 0) {
  4892. empty?.classList.remove('hidden');
  4893. return;
  4894. }
  4895. empty?.classList.add('hidden');
  4896. conns.slice(0, 150).forEach(c => {
  4897. const tr = document.createElement('tr');
  4898. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  4899. let stateColor = 'text-slate-400';
  4900. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  4901. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  4902. tr.innerHTML = `
  4903. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  4904. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  4905. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  4906. <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>
  4907. <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>
  4908. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  4909. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  4910. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  4911. <td class="py-2.5 px-3 text-right font-sans">
  4912. <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>
  4913. </td>
  4914. `;
  4915. tbody.appendChild(tr);
  4916. });
  4917. }
  4918. async function killConnection(protocol, src, sport, dst, dport) {
  4919. try {
  4920. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  4921. method: 'POST',
  4922. headers: { 'Content-Type': 'application/json' },
  4923. body: JSON.stringify({ protocol, src, sport, dst, dport })
  4924. });
  4925. if (res.ok) {
  4926. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  4927. loadConnections();
  4928. }
  4929. } catch (err) {
  4930. showToast('Error', err.message, 'error');
  4931. }
  4932. }
  4933. async function resetFirewallCounters() {
  4934. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  4935. try {
  4936. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  4937. if (res.ok) {
  4938. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  4939. loadFirewall(false);
  4940. }
  4941. } catch (err) {
  4942. showToast('Error', err.message, 'error');
  4943. }
  4944. }
  4945. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  4946. function switchRoutesSubTab(tab) {
  4947. state.routesSubTab = tab;
  4948. const tabs = ['routes', 'rules', 'tables'];
  4949. tabs.forEach(t => {
  4950. const panel = document.getElementById(`routes-subtab-${t}`);
  4951. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  4952. if (panel) {
  4953. if (t === tab) panel.classList.remove('hidden');
  4954. else panel.classList.add('hidden');
  4955. }
  4956. if (btn) {
  4957. if (t === tab) {
  4958. 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';
  4959. } else {
  4960. 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';
  4961. }
  4962. }
  4963. });
  4964. setTimeout(initTableSorting, 50);
  4965. }
  4966. async function loadRoutes() {
  4967. try {
  4968. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  4969. fetch(`${API_BASE}/routes`),
  4970. fetch(`${API_BASE}/routing/rules`),
  4971. fetch(`${API_BASE}/routing/tables`)
  4972. ]);
  4973. if (routesRes.ok) state.routes = await routesRes.json();
  4974. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  4975. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  4976. const bRoutes = document.getElementById('routes-badge-routes');
  4977. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  4978. const bRules = document.getElementById('routes-badge-rules');
  4979. if (bRules) bRules.innerText = (state.policyRules || []).length;
  4980. const bTables = document.getElementById('routes-badge-tables');
  4981. if (bTables) bTables.innerText = (state.routingTables || []).length;
  4982. const bRoutesCount = document.getElementById('badge-routes-count');
  4983. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  4984. renderRoutesList();
  4985. renderPolicyRules();
  4986. renderRoutingTables();
  4987. } catch (err) {
  4988. console.error('Failed to load routing:', err);
  4989. }
  4990. }
  4991. function renderRoutesList() {
  4992. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  4993. const tbody = document.getElementById('routes-table-body');
  4994. const empty = document.getElementById('routes-empty');
  4995. if (!tbody) return;
  4996. tbody.innerHTML = '';
  4997. // Update table filter select
  4998. const sel = document.getElementById('routes-filter-table');
  4999. if (sel) {
  5000. const cur = sel.value;
  5001. sel.innerHTML = '<option value="">All Tables</option>';
  5002. (state.routingTables || []).forEach(t => {
  5003. const opt = document.createElement('option');
  5004. opt.value = t.name;
  5005. opt.innerText = t.name;
  5006. if (t.name === cur) opt.selected = true;
  5007. sel.appendChild(opt);
  5008. });
  5009. }
  5010. const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
  5011. document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
  5012. if (routes.length === 0) {
  5013. empty?.classList.remove('hidden');
  5014. return;
  5015. }
  5016. empty?.classList.add('hidden');
  5017. routes.forEach(r => {
  5018. const tr = document.createElement('tr');
  5019. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  5020. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  5021. // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
  5022. let flags = '';
  5023. if (r.dynamic) flags += 'D';
  5024. if (r.active) flags += 'A';
  5025. if (r.connect) flags += 'C';
  5026. if (r.static) flags += 'S';
  5027. if (r.disabled) flags += 'X';
  5028. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  5029. tr.innerHTML = `
  5030. <td class="py-2.5 px-3 text-center">
  5031. <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'}">
  5032. ${flags || '-'}
  5033. </span>
  5034. </td>
  5035. <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
  5036. <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>
  5037. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  5038. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  5039. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  5040. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  5041. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5042. ${r.static ? `
  5043. <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>
  5044. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  5045. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5046. ` : `
  5047. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  5048. `}
  5049. </td>
  5050. `;
  5051. tbody.appendChild(tr);
  5052. });
  5053. }
  5054. function openAddRouteModal() {
  5055. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  5056. document.getElementById('route-modal-id').value = '';
  5057. document.getElementById('route-modal-old-dst').value = '';
  5058. document.getElementById('route-modal-old-gw').value = '';
  5059. document.getElementById('route-modal-old-distance').value = '';
  5060. document.getElementById('route-modal-old-table').value = '';
  5061. document.getElementById('route-modal-old-iface').value = '';
  5062. const dstInput = document.getElementById('route-modal-dst');
  5063. const gwInput = document.getElementById('route-modal-gw');
  5064. const distInput = document.getElementById('route-modal-distance');
  5065. const ifaceSelect = document.getElementById('route-modal-iface');
  5066. const tableSelect = document.getElementById('route-modal-table');
  5067. const commentInput = document.getElementById('route-modal-comment');
  5068. const disCheck = document.getElementById('route-modal-disabled');
  5069. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5070. dstInput.disabled = false;
  5071. dstInput.value = '0.0.0.0/0';
  5072. gwInput.disabled = false;
  5073. gwInput.value = '';
  5074. distInput.disabled = false;
  5075. distInput.value = '1';
  5076. ifaceSelect.disabled = false;
  5077. tableSelect.disabled = false;
  5078. commentInput.disabled = false;
  5079. commentInput.value = '';
  5080. disCheck.disabled = false;
  5081. disCheck.checked = false;
  5082. if (saveBtn) saveBtn.classList.remove('hidden');
  5083. populateInterfaceSelect('route-modal-iface');
  5084. // Populate tables
  5085. tableSelect.innerHTML = '';
  5086. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5087. const opt = document.createElement('option');
  5088. opt.value = t.name;
  5089. opt.innerText = t.name;
  5090. if (t.name === 'main') opt.selected = true;
  5091. tableSelect.appendChild(opt);
  5092. });
  5093. document.getElementById('route-modal').classList.remove('hidden');
  5094. }
  5095. function openEditRouteModal(id) {
  5096. const r = (state.routes || []).find(route => route.id === id);
  5097. if (!r) return;
  5098. const isStatic = !!r.static;
  5099. document.getElementById('route-modal-title').innerText = isStatic
  5100. ? `Edit Route: ${r.dst_address}`
  5101. : `Route Properties (Read Only): ${r.dst_address}`;
  5102. document.getElementById('route-modal-id').value = r.id;
  5103. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  5104. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  5105. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  5106. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  5107. document.getElementById('route-modal-old-iface').value = r.interface || '';
  5108. const dstInput = document.getElementById('route-modal-dst');
  5109. const gwInput = document.getElementById('route-modal-gw');
  5110. const distInput = document.getElementById('route-modal-distance');
  5111. const ifaceSelect = document.getElementById('route-modal-iface');
  5112. const tableSelect = document.getElementById('route-modal-table');
  5113. const commentInput = document.getElementById('route-modal-comment');
  5114. const disCheck = document.getElementById('route-modal-disabled');
  5115. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5116. dstInput.value = r.dst_address;
  5117. gwInput.value = r.gateway || '';
  5118. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  5119. commentInput.value = r.comment || '';
  5120. disCheck.checked = !!r.disabled;
  5121. dstInput.disabled = !isStatic;
  5122. gwInput.disabled = !isStatic;
  5123. distInput.disabled = !isStatic;
  5124. ifaceSelect.disabled = !isStatic;
  5125. tableSelect.disabled = !isStatic;
  5126. commentInput.disabled = !isStatic;
  5127. disCheck.disabled = !isStatic;
  5128. if (saveBtn) {
  5129. if (isStatic) {
  5130. saveBtn.classList.remove('hidden');
  5131. } else {
  5132. saveBtn.classList.add('hidden');
  5133. }
  5134. }
  5135. populateInterfaceSelect('route-modal-iface', r.interface);
  5136. tableSelect.innerHTML = '';
  5137. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5138. const opt = document.createElement('option');
  5139. opt.value = t.name;
  5140. opt.innerText = t.name;
  5141. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  5142. tableSelect.appendChild(opt);
  5143. });
  5144. document.getElementById('route-modal').classList.remove('hidden');
  5145. }
  5146. function closeRouteModal() {
  5147. document.getElementById('route-modal').classList.add('hidden');
  5148. }
  5149. async function submitSaveRoute(e) {
  5150. e.preventDefault();
  5151. const id = document.getElementById('route-modal-id').value;
  5152. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  5153. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  5154. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  5155. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  5156. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  5157. const dst = document.getElementById('route-modal-dst').value.trim();
  5158. const gw = document.getElementById('route-modal-gw').value.trim();
  5159. const table = document.getElementById('route-modal-table').value;
  5160. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  5161. const iface = document.getElementById('route-modal-iface').value;
  5162. const comment = document.getElementById('route-modal-comment').value.trim();
  5163. const disabled = document.getElementById('route-modal-disabled').checked;
  5164. if (!dst) {
  5165. showToast('Error', 'Destination address is required', 'error');
  5166. return;
  5167. }
  5168. if (!gw && !iface) {
  5169. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  5170. return;
  5171. }
  5172. const payload = {
  5173. id,
  5174. old_dst_address: oldDst,
  5175. old_gateway: oldGw,
  5176. old_routing_table: oldTable,
  5177. old_interface: oldIface,
  5178. dst_address: dst,
  5179. gateway: gw || iface,
  5180. routing_table: table,
  5181. distance,
  5182. interface: iface,
  5183. comment,
  5184. disabled
  5185. };
  5186. if (oldDistStr !== undefined && oldDistStr !== '') {
  5187. payload.old_distance = parseInt(oldDistStr, 10);
  5188. }
  5189. try {
  5190. const res = await fetch(`${API_BASE}/routes`, {
  5191. method: 'POST',
  5192. headers: { 'Content-Type': 'application/json' },
  5193. body: JSON.stringify(payload)
  5194. });
  5195. if (res.ok) {
  5196. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  5197. closeRouteModal();
  5198. loadRoutes();
  5199. } else {
  5200. const err = await res.json();
  5201. showToast('Error', err.message || 'Failed to save route', 'error');
  5202. }
  5203. } catch (err) {
  5204. showToast('Error', err.message, 'error');
  5205. }
  5206. }
  5207. async function toggleRouteState(id, disabled) {
  5208. try {
  5209. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  5210. method: 'POST',
  5211. headers: { 'Content-Type': 'application/json' },
  5212. body: JSON.stringify({ disabled })
  5213. });
  5214. if (res.ok) loadRoutes();
  5215. } catch (err) {
  5216. showToast('Error', err.message, 'error');
  5217. }
  5218. }
  5219. async function deleteRoute(id) {
  5220. if (!confirm('Are you sure you want to delete this route?')) return;
  5221. try {
  5222. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5223. if (res.ok) {
  5224. showToast('Deleted', 'Route removed', 'success');
  5225. loadRoutes();
  5226. }
  5227. } catch (err) {
  5228. showToast('Error', err.message, 'error');
  5229. }
  5230. }
  5231. // ----------------- Policy Rules (/ip route rule) -----------------
  5232. function renderPolicyRules() {
  5233. const tbody = document.getElementById('rules-table-body');
  5234. const empty = document.getElementById('rules-empty');
  5235. if (!tbody) return;
  5236. tbody.innerHTML = '';
  5237. const rules = state.policyRules || [];
  5238. document.getElementById('rules-count-badge').innerText = `${rules.length} Rules`;
  5239. if (rules.length === 0) {
  5240. empty?.classList.remove('hidden');
  5241. return;
  5242. }
  5243. empty?.classList.add('hidden');
  5244. rules.forEach(pr => {
  5245. const tr = document.createElement('tr');
  5246. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5247. tr.innerHTML = `
  5248. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  5249. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  5250. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  5251. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  5252. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  5253. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  5254. <td class="py-2.5 px-3 text-right font-sans">
  5255. ${pr.priority < 32766 && pr.priority > 0 ? `
  5256. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5257. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  5258. </td>
  5259. `;
  5260. tbody.appendChild(tr);
  5261. });
  5262. }
  5263. function openAddPolicyRuleModal() {
  5264. document.getElementById('prule-modal-pref').value = (state.policyRules || []).length * 10 + 1000;
  5265. document.getElementById('prule-modal-mark').value = '';
  5266. document.getElementById('prule-modal-src').value = '';
  5267. document.getElementById('prule-modal-dst').value = '';
  5268. const sel = document.getElementById('prule-modal-table');
  5269. sel.innerHTML = '';
  5270. (state.routingTables || []).forEach(t => {
  5271. const opt = document.createElement('option');
  5272. opt.value = t.name;
  5273. opt.innerText = t.name;
  5274. sel.appendChild(opt);
  5275. });
  5276. document.getElementById('prule-modal').classList.remove('hidden');
  5277. }
  5278. function closePolicyRuleModal() {
  5279. document.getElementById('prule-modal').classList.add('hidden');
  5280. }
  5281. async function submitSavePolicyRule(e) {
  5282. e.preventDefault();
  5283. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  5284. const mark = document.getElementById('prule-modal-mark').value.trim();
  5285. const src = document.getElementById('prule-modal-src').value.trim();
  5286. const dst = document.getElementById('prule-modal-dst').value.trim();
  5287. const table = document.getElementById('prule-modal-table').value;
  5288. const action = document.getElementById('prule-modal-action').value;
  5289. try {
  5290. const res = await fetch(`${API_BASE}/routing/rules`, {
  5291. method: 'POST',
  5292. headers: { 'Content-Type': 'application/json' },
  5293. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  5294. });
  5295. if (res.ok) {
  5296. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  5297. closePolicyRuleModal();
  5298. loadRoutes();
  5299. } else {
  5300. const err = await res.json();
  5301. showToast('Error', err.message, 'error');
  5302. }
  5303. } catch (err) {
  5304. showToast('Error', err.message, 'error');
  5305. }
  5306. }
  5307. async function deletePolicyRule(id) {
  5308. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  5309. try {
  5310. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5311. if (res.ok) {
  5312. showToast('Rule Removed', 'Policy rule deleted', 'success');
  5313. loadRoutes();
  5314. }
  5315. } catch (err) {
  5316. showToast('Error', err.message, 'error');
  5317. }
  5318. }
  5319. // ----------------- Routing Tables -----------------
  5320. function renderRoutingTables() {
  5321. const tbody = document.getElementById('tables-table-body');
  5322. if (!tbody) return;
  5323. tbody.innerHTML = '';
  5324. (state.routingTables || []).forEach(t => {
  5325. const tr = document.createElement('tr');
  5326. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5327. tr.innerHTML = `
  5328. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  5329. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  5330. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  5331. `;
  5332. tbody.appendChild(tr);
  5333. });
  5334. }
  5335. function openAddTableModal() {
  5336. document.getElementById('table-modal-name').value = '';
  5337. document.getElementById('table-modal-id').value = '';
  5338. document.getElementById('table-modal-comment').value = '';
  5339. document.getElementById('table-modal').classList.remove('hidden');
  5340. }
  5341. function closeTableModal() {
  5342. document.getElementById('table-modal').classList.add('hidden');
  5343. }
  5344. async function submitSaveTable(e) {
  5345. e.preventDefault();
  5346. const name = document.getElementById('table-modal-name').value.trim();
  5347. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  5348. const comment = document.getElementById('table-modal-comment').value.trim();
  5349. try {
  5350. const res = await fetch(`${API_BASE}/routing/tables`, {
  5351. method: 'POST',
  5352. headers: { 'Content-Type': 'application/json' },
  5353. body: JSON.stringify({ name, table_id: id, comment })
  5354. });
  5355. if (res.ok) {
  5356. showToast('Table Created', `Routing table ${name} registered`, 'success');
  5357. closeTableModal();
  5358. loadRoutes();
  5359. } else {
  5360. const err = await res.json();
  5361. showToast('Error', err.message, 'error');
  5362. }
  5363. } catch (err) {
  5364. showToast('Error', err.message, 'error');
  5365. }
  5366. }
  5367. async function loadDebianConfig() {
  5368. const view = document.getElementById('debian-config-view');
  5369. view.innerText = 'Generating live configuration...';
  5370. try {
  5371. const res = await fetch(`${API_BASE}/debian/config`);
  5372. const data = await res.json();
  5373. view.innerText = data.content || '# Empty config';
  5374. } catch (err) {
  5375. view.innerText = 'Failed to generate Debian network config.';
  5376. }
  5377. }
  5378. async function saveDebianConfig() {
  5379. try {
  5380. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  5381. const data = await res.json();
  5382. if (res.ok) {
  5383. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  5384. loadDebianConfig();
  5385. }
  5386. } catch (err) {
  5387. showToast('Error', err.message, 'error');
  5388. }
  5389. }
  5390. function showToast(title, message, type = 'info') {
  5391. const container = document.getElementById('toast-container');
  5392. const toast = document.createElement('div');
  5393. const borderColors = {
  5394. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  5395. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  5396. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  5397. };
  5398. 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}`;
  5399. toast.innerHTML = `
  5400. <div class="flex-1">
  5401. <div class="font-bold text-xs text-white">${title}</div>
  5402. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  5403. </div>
  5404. `;
  5405. container.appendChild(toast);
  5406. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  5407. setTimeout(() => {
  5408. toast.classList.add('opacity-0', 'translate-y-2');
  5409. setTimeout(() => toast.remove(), 300);
  5410. }, 4000);
  5411. }
  5412. function formatTraffic(bytesPerSec) {
  5413. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  5414. const kb = bytesPerSec / 1024;
  5415. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  5416. const mb = kb / 1024;
  5417. return `${mb.toFixed(2)} MB/s`;
  5418. }
  5419. function toggleSidebar() {
  5420. const sb = document.getElementById('sidebar');
  5421. sb.classList.toggle('-translate-x-full');
  5422. }
  5423. // ======================== EoIP (Ethernet over IP) ========================
  5424. async function loadEoIP(populate = true) {
  5425. try {
  5426. const res = await fetch(`${API_BASE}/vpn/eoip`);
  5427. const data = await res.json();
  5428. state.eoipTunnels = Array.isArray(data) ? data : [];
  5429. const badge = document.getElementById('eoip-count-badge');
  5430. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  5431. const sideBadge = document.getElementById('badge-eoip-count');
  5432. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  5433. renderEoIPTunnels();
  5434. } catch (err) {
  5435. console.error('Failed to load EoIP:', err);
  5436. }
  5437. }
  5438. function renderEoIPTunnels() {
  5439. const tbody = document.getElementById('eoip-table-body');
  5440. const empty = document.getElementById('eoip-empty');
  5441. if (!tbody) return;
  5442. tbody.innerHTML = '';
  5443. const tunnels = state.eoipTunnels || [];
  5444. if (tunnels.length === 0) {
  5445. empty?.classList.remove('hidden');
  5446. return;
  5447. }
  5448. empty?.classList.add('hidden');
  5449. tunnels.forEach(t => {
  5450. const tr = document.createElement('tr');
  5451. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  5452. tr.innerHTML = `
  5453. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  5454. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  5455. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  5456. <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>
  5457. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  5458. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  5459. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  5460. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  5461. <td class="py-2.5 px-3 font-mono text-[11px]">
  5462. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  5463. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  5464. </td>
  5465. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  5466. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5467. <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>
  5468. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5469. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  5470. </td>
  5471. `;
  5472. tbody.appendChild(tr);
  5473. });
  5474. }
  5475. function openAddEoIPModal() {
  5476. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  5477. document.getElementById('eoip-modal-id').value = '';
  5478. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  5479. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  5480. document.getElementById('eoip-modal-remote').value = '';
  5481. document.getElementById('eoip-modal-ip').value = '';
  5482. document.getElementById('eoip-modal-local').value = '';
  5483. document.getElementById('eoip-modal-mac').value = '';
  5484. document.getElementById('eoip-modal-mtu').value = '1500';
  5485. document.getElementById('eoip-modal-comment').value = '';
  5486. document.getElementById('eoip-modal-clampmss').checked = true;
  5487. document.getElementById('eoip-modal-disabled').checked = false;
  5488. document.getElementById('eoip-modal').classList.remove('hidden');
  5489. }
  5490. function openEditEoIPModal(id) {
  5491. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  5492. if (!t) return;
  5493. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  5494. document.getElementById('eoip-modal-id').value = t.id;
  5495. document.getElementById('eoip-modal-name').value = t.name;
  5496. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  5497. document.getElementById('eoip-modal-remote').value = t.remote_address;
  5498. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  5499. document.getElementById('eoip-modal-local').value = t.local_address || '';
  5500. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  5501. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  5502. document.getElementById('eoip-modal-comment').value = t.comment || '';
  5503. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  5504. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  5505. document.getElementById('eoip-modal').classList.remove('hidden');
  5506. }
  5507. function closeEoIPModal() {
  5508. document.getElementById('eoip-modal').classList.add('hidden');
  5509. }
  5510. async function submitSaveEoIP(e) {
  5511. e.preventDefault();
  5512. const id = document.getElementById('eoip-modal-id').value;
  5513. const name = document.getElementById('eoip-modal-name').value.trim();
  5514. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  5515. const remote = document.getElementById('eoip-modal-remote').value.trim();
  5516. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  5517. const local = document.getElementById('eoip-modal-local').value.trim();
  5518. const mac = document.getElementById('eoip-modal-mac').value.trim();
  5519. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  5520. const comment = document.getElementById('eoip-modal-comment').value.trim();
  5521. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  5522. const disabled = document.getElementById('eoip-modal-disabled').checked;
  5523. try {
  5524. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  5525. method: 'POST',
  5526. headers: { 'Content-Type': 'application/json' },
  5527. body: JSON.stringify({
  5528. id,
  5529. name,
  5530. tunnel_id: tunnelId,
  5531. remote_address: remote,
  5532. ip_address: ipAddress,
  5533. local_address: local,
  5534. mac_address: mac,
  5535. mtu,
  5536. clamp_mss: clampMss,
  5537. comment,
  5538. disabled
  5539. })
  5540. });
  5541. if (res.ok) {
  5542. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  5543. closeEoIPModal();
  5544. loadEoIP(false);
  5545. fetchData(false);
  5546. } else {
  5547. const err = await res.json();
  5548. showToast('Error', err.message, 'error');
  5549. }
  5550. } catch (err) {
  5551. showToast('Error', err.message, 'error');
  5552. }
  5553. }
  5554. async function toggleEoIPState(id, disabled) {
  5555. try {
  5556. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  5557. method: 'POST',
  5558. headers: { 'Content-Type': 'application/json' },
  5559. body: JSON.stringify({ disabled })
  5560. });
  5561. if (res.ok) {
  5562. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  5563. loadEoIP(false);
  5564. fetchData(false);
  5565. }
  5566. } catch (err) {
  5567. showToast('Error', err.message, 'error');
  5568. }
  5569. }
  5570. async function deleteEoIP(id) {
  5571. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  5572. try {
  5573. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5574. if (res.ok) {
  5575. showToast('Deleted', 'EoIP tunnel removed', 'success');
  5576. loadEoIP(false);
  5577. fetchData(false);
  5578. }
  5579. } catch (err) {
  5580. showToast('Error', err.message, 'error');
  5581. }
  5582. }
  5583. // ======================== PPP Central Hub & Servers ========================
  5584. function switchPPPSubTab(tab) {
  5585. state.pppSubTab = tab;
  5586. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  5587. tabs.forEach(t => {
  5588. const panel = document.getElementById(`ppp-subtab-${t}`);
  5589. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  5590. if (panel) {
  5591. if (t === tab) panel.classList.remove('hidden');
  5592. else panel.classList.add('hidden');
  5593. }
  5594. if (btn) {
  5595. if (t === tab) {
  5596. 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';
  5597. } else {
  5598. 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';
  5599. }
  5600. }
  5601. });
  5602. const addBtn = document.getElementById('ppp-primary-add-btn');
  5603. if (addBtn) {
  5604. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  5605. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  5606. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  5607. else addBtn.innerHTML = '<span>Save Config</span>';
  5608. }
  5609. if (tab === 'active') loadPPPSessions();
  5610. }
  5611. function openCurrentPPPModal() {
  5612. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  5613. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  5614. else if (state.pppSubTab === 'active') loadPPPSessions();
  5615. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  5616. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  5617. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  5618. }
  5619. async function loadPPP(populateDropdowns = true) {
  5620. await Promise.all([
  5621. loadPPPSecrets(),
  5622. loadPPPProfiles(),
  5623. loadPPPServers(),
  5624. loadPPPSessions()
  5625. ]);
  5626. }
  5627. async function loadPPPSecrets() {
  5628. try {
  5629. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  5630. const data = await res.json();
  5631. state.pppSecrets = Array.isArray(data) ? data : [];
  5632. const b = document.getElementById('ppp-badge-secrets');
  5633. if (b) b.innerText = state.pppSecrets.length;
  5634. const b2 = document.getElementById('secrets-count-badge');
  5635. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  5636. renderPPPSecrets();
  5637. } catch (err) {
  5638. console.error('Failed to load PPP secrets:', err);
  5639. }
  5640. }
  5641. function renderPPPSecrets() {
  5642. const tbody = document.getElementById('secrets-table-body');
  5643. const empty = document.getElementById('secrets-empty');
  5644. if (!tbody) return;
  5645. tbody.innerHTML = '';
  5646. const secrets = state.pppSecrets || [];
  5647. if (secrets.length === 0) {
  5648. empty?.classList.remove('hidden');
  5649. return;
  5650. }
  5651. empty?.classList.add('hidden');
  5652. secrets.forEach(s => {
  5653. const tr = document.createElement('tr');
  5654. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  5655. tr.innerHTML = `
  5656. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  5657. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  5658. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  5659. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  5660. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  5661. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  5662. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  5663. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5664. <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>
  5665. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5666. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  5667. </td>
  5668. `;
  5669. tbody.appendChild(tr);
  5670. });
  5671. }
  5672. async function loadPPPProfiles() {
  5673. try {
  5674. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  5675. const data = await res.json();
  5676. state.pppProfiles = Array.isArray(data) ? data : [];
  5677. const b = document.getElementById('ppp-badge-profiles');
  5678. if (b) b.innerText = state.pppProfiles.length;
  5679. const b2 = document.getElementById('profiles-count-badge');
  5680. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  5681. // Populate profile selects across modals
  5682. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  5683. selects.forEach(sid => {
  5684. const el = document.getElementById(sid);
  5685. if (!el) return;
  5686. const cur = el.value;
  5687. el.innerHTML = '';
  5688. state.pppProfiles.forEach(p => {
  5689. const opt = document.createElement('option');
  5690. opt.value = p.name;
  5691. opt.innerText = `${p.name} (${p.remote_address})`;
  5692. if (p.name === cur) opt.selected = true;
  5693. el.appendChild(opt);
  5694. });
  5695. });
  5696. renderPPPProfiles();
  5697. } catch (err) {
  5698. console.error('Failed to load PPP profiles:', err);
  5699. }
  5700. }
  5701. function renderPPPProfiles() {
  5702. const tbody = document.getElementById('profiles-table-body');
  5703. if (!tbody) return;
  5704. tbody.innerHTML = '';
  5705. (state.pppProfiles || []).forEach(p => {
  5706. const isDefault = p.name.startsWith('default');
  5707. const tr = document.createElement('tr');
  5708. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5709. tr.innerHTML = `
  5710. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  5711. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  5712. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  5713. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  5714. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  5715. <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>
  5716. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  5717. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  5718. ${!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>`}
  5719. </td>
  5720. `;
  5721. tbody.appendChild(tr);
  5722. });
  5723. }
  5724. async function loadPPPServers() {
  5725. try {
  5726. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  5727. fetch(`${API_BASE}/vpn/servers/pppoe`),
  5728. fetch(`${API_BASE}/vpn/servers/pptp`),
  5729. fetch(`${API_BASE}/vpn/servers/l2tp`),
  5730. fetch(`${API_BASE}/vpn/servers/ipsec`)
  5731. ]);
  5732. if (pppoeRes.ok) {
  5733. state.pppoeServer = await pppoeRes.json();
  5734. const s = state.pppoeServer;
  5735. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  5736. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  5737. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  5738. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  5739. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  5740. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  5741. const pill = document.getElementById('pppoe-server-status-pill');
  5742. if (pill) {
  5743. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  5744. 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';
  5745. }
  5746. setDotBadge('ppp-badge-pppoe-state', s.running);
  5747. }
  5748. if (pptpRes.ok) {
  5749. state.pptpServer = await pptpRes.json();
  5750. const s = state.pptpServer;
  5751. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  5752. document.getElementById('pptp-server-port').value = s.port || 1723;
  5753. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  5754. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  5755. const pill = document.getElementById('pptp-server-status-pill');
  5756. if (pill) {
  5757. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  5758. 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';
  5759. }
  5760. setDotBadge('ppp-badge-pptp-state', s.running);
  5761. }
  5762. if (l2tpRes.ok) {
  5763. state.l2tpServer = await l2tpRes.json();
  5764. const s = state.l2tpServer;
  5765. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  5766. document.getElementById('l2tp-server-port').value = s.port || 1701;
  5767. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  5768. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  5769. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  5770. const pill = document.getElementById('l2tp-server-status-pill');
  5771. if (pill) {
  5772. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  5773. 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';
  5774. }
  5775. setDotBadge('ppp-badge-l2tp-state', s.running);
  5776. }
  5777. if (ipsecRes.ok) {
  5778. state.ipsecServer = await ipsecRes.json();
  5779. const s = state.ipsecServer;
  5780. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  5781. if (modalEn) modalEn.checked = !!s.enabled;
  5782. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  5783. if (modalPsk) modalPsk.value = s.preshared_key || '';
  5784. const modalPool = document.getElementById('modal-ipsec-server-pool');
  5785. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  5786. const modalDns = document.getElementById('modal-ipsec-server-dns');
  5787. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  5788. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  5789. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  5790. const pill = document.getElementById('modal-ipsec-server-status');
  5791. if (pill) {
  5792. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  5793. 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';
  5794. }
  5795. }
  5796. } catch (err) {
  5797. console.error('Failed to load VPN servers:', err);
  5798. }
  5799. }
  5800. async function loadPPPSessions() {
  5801. try {
  5802. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  5803. const data = await res.json();
  5804. state.pppActiveSessions = Array.isArray(data) ? data : [];
  5805. const b = document.getElementById('ppp-badge-active');
  5806. if (b) b.innerText = state.pppActiveSessions.length;
  5807. const sideB = document.getElementById('badge-ppp-sessions');
  5808. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  5809. renderPPPSessions();
  5810. } catch (err) {
  5811. console.error('Failed to load active PPP sessions:', err);
  5812. }
  5813. }
  5814. function renderPPPSessions() {
  5815. const tbody = document.getElementById('active-ppp-table-body');
  5816. const empty = document.getElementById('active-ppp-empty');
  5817. if (!tbody) return;
  5818. tbody.innerHTML = '';
  5819. const list = state.pppActiveSessions || [];
  5820. if (list.length === 0) {
  5821. empty?.classList.remove('hidden');
  5822. return;
  5823. }
  5824. empty?.classList.add('hidden');
  5825. list.forEach(s => {
  5826. const tr = document.createElement('tr');
  5827. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5828. tr.innerHTML = `
  5829. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  5830. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  5831. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  5832. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  5833. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  5834. <td class="py-2.5 px-3 text-[11px]">
  5835. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  5836. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  5837. </td>
  5838. <td class="py-2.5 px-3 text-right font-sans">
  5839. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  5840. </td>
  5841. `;
  5842. tbody.appendChild(tr);
  5843. });
  5844. }
  5845. async function disconnectPPPSession(iface) {
  5846. if (!confirm(`Disconnect session ${iface}?`)) return;
  5847. try {
  5848. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  5849. if (res.ok) {
  5850. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  5851. loadPPPSessions();
  5852. }
  5853. } catch (err) {
  5854. showToast('Error', err.message, 'error');
  5855. }
  5856. }
  5857. // PPP Secret Modal handlers
  5858. function openAddPPPSecretModal() {
  5859. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  5860. document.getElementById('secret-modal-id').value = '';
  5861. document.getElementById('secret-modal-name').value = '';
  5862. document.getElementById('secret-modal-password').value = '';
  5863. document.getElementById('secret-modal-service').value = 'any';
  5864. document.getElementById('secret-modal-profile').value = 'default';
  5865. document.getElementById('secret-modal-local').value = '';
  5866. document.getElementById('secret-modal-remote').value = '';
  5867. document.getElementById('secret-modal-comment').value = '';
  5868. document.getElementById('secret-modal-disabled').checked = false;
  5869. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  5870. }
  5871. function openEditPPPSecretModal(id) {
  5872. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  5873. if (!s) return;
  5874. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  5875. document.getElementById('secret-modal-id').value = s.id;
  5876. document.getElementById('secret-modal-name').value = s.name;
  5877. document.getElementById('secret-modal-password').value = s.password;
  5878. document.getElementById('secret-modal-service').value = s.service || 'any';
  5879. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  5880. document.getElementById('secret-modal-local').value = s.local_address || '';
  5881. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  5882. document.getElementById('secret-modal-comment').value = s.comment || '';
  5883. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  5884. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  5885. }
  5886. function closePPPSecretModal() {
  5887. document.getElementById('ppp-secret-modal').classList.add('hidden');
  5888. }
  5889. async function submitSavePPPSecret(e) {
  5890. e.preventDefault();
  5891. const id = document.getElementById('secret-modal-id').value;
  5892. const name = document.getElementById('secret-modal-name').value.trim();
  5893. const password = document.getElementById('secret-modal-password').value.trim();
  5894. const service = document.getElementById('secret-modal-service').value;
  5895. const profile = document.getElementById('secret-modal-profile').value;
  5896. const local = document.getElementById('secret-modal-local').value.trim();
  5897. const remote = document.getElementById('secret-modal-remote').value.trim();
  5898. const comment = document.getElementById('secret-modal-comment').value.trim();
  5899. const disabled = document.getElementById('secret-modal-disabled').checked;
  5900. try {
  5901. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  5902. method: 'POST',
  5903. headers: { 'Content-Type': 'application/json' },
  5904. body: JSON.stringify({
  5905. id,
  5906. name,
  5907. password,
  5908. service,
  5909. profile,
  5910. local_address: local,
  5911. remote_address: remote,
  5912. comment,
  5913. disabled
  5914. })
  5915. });
  5916. if (res.ok) {
  5917. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  5918. closePPPSecretModal();
  5919. loadPPPSecrets();
  5920. } else {
  5921. const err = await res.json();
  5922. showToast('Error', err.message, 'error');
  5923. }
  5924. } catch (err) {
  5925. showToast('Error', err.message, 'error');
  5926. }
  5927. }
  5928. async function togglePPPSecretState(id, disabled) {
  5929. try {
  5930. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  5931. method: 'POST',
  5932. headers: { 'Content-Type': 'application/json' },
  5933. body: JSON.stringify({ disabled })
  5934. });
  5935. if (res.ok) {
  5936. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  5937. loadPPPSecrets();
  5938. }
  5939. } catch (err) {
  5940. showToast('Error', err.message, 'error');
  5941. }
  5942. }
  5943. async function deletePPPSecret(id) {
  5944. if (!confirm('Are you sure you want to delete this secret account?')) return;
  5945. try {
  5946. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5947. if (res.ok) {
  5948. showToast('Deleted', 'Secret account removed', 'success');
  5949. loadPPPSecrets();
  5950. }
  5951. } catch (err) {
  5952. showToast('Error', err.message, 'error');
  5953. }
  5954. }
  5955. // PPP Profile Modal handlers
  5956. function openAddPPPProfileModal() {
  5957. document.getElementById('profile-modal-name').value = '';
  5958. document.getElementById('profile-modal-local').value = '10.10.10.1';
  5959. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  5960. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  5961. document.getElementById('profile-modal-encryption').value = 'required';
  5962. document.getElementById('profile-modal-onlyone').checked = true;
  5963. document.getElementById('profile-modal-comment').value = '';
  5964. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  5965. }
  5966. function closePPPProfileModal() {
  5967. document.getElementById('ppp-profile-modal').classList.add('hidden');
  5968. }
  5969. async function submitSavePPPProfile(e) {
  5970. e.preventDefault();
  5971. const name = document.getElementById('profile-modal-name').value.trim();
  5972. const local = document.getElementById('profile-modal-local').value.trim();
  5973. const remote = document.getElementById('profile-modal-remote').value.trim();
  5974. const dns = document.getElementById('profile-modal-dns').value.trim();
  5975. const enc = document.getElementById('profile-modal-encryption').value;
  5976. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  5977. const comment = document.getElementById('profile-modal-comment').value.trim();
  5978. try {
  5979. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  5980. method: 'POST',
  5981. headers: { 'Content-Type': 'application/json' },
  5982. body: JSON.stringify({
  5983. id: name,
  5984. name,
  5985. local_address: local,
  5986. remote_address: remote,
  5987. dns_servers: dns,
  5988. use_encryption: enc,
  5989. only_one: onlyone,
  5990. comment
  5991. })
  5992. });
  5993. if (res.ok) {
  5994. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  5995. closePPPProfileModal();
  5996. loadPPPProfiles();
  5997. } else {
  5998. const err = await res.json();
  5999. showToast('Error', err.message, 'error');
  6000. }
  6001. } catch (err) {
  6002. showToast('Error', err.message, 'error');
  6003. }
  6004. }
  6005. async function deletePPPProfile(name) {
  6006. if (!confirm(`Delete PPP profile ${name}?`)) return;
  6007. try {
  6008. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  6009. if (res.ok) {
  6010. showToast('Deleted', 'Profile removed', 'success');
  6011. loadPPPProfiles();
  6012. } else {
  6013. const err = await res.json();
  6014. showToast('Error', err.message, 'error');
  6015. }
  6016. } catch (err) {
  6017. showToast('Error', err.message, 'error');
  6018. }
  6019. }
  6020. // Server Config submissions
  6021. async function savePPPoEServerConfig(e) {
  6022. e.preventDefault();
  6023. const enabled = document.getElementById('pppoe-server-enabled').checked;
  6024. const name = document.getElementById('pppoe-server-name').value.trim();
  6025. const iface = document.getElementById('pppoe-server-iface').value;
  6026. const profile = document.getElementById('pppoe-server-profile').value;
  6027. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  6028. const onesession = document.getElementById('pppoe-server-onesession').checked;
  6029. try {
  6030. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  6031. method: 'POST',
  6032. headers: { 'Content-Type': 'application/json' },
  6033. body: JSON.stringify({
  6034. enabled,
  6035. service_name: name,
  6036. interface: iface,
  6037. default_profile: profile,
  6038. max_mtu: mtu,
  6039. max_mru: mtu,
  6040. one_session_per_host: onesession
  6041. })
  6042. });
  6043. if (res.ok) {
  6044. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  6045. loadPPPServers();
  6046. fetchData(false);
  6047. } else {
  6048. const err = await res.json();
  6049. showToast('Error', err.message, 'error');
  6050. }
  6051. } catch (err) {
  6052. showToast('Error', err.message, 'error');
  6053. }
  6054. }
  6055. async function savePPTPServerConfig(e) {
  6056. e.preventDefault();
  6057. const enabled = document.getElementById('pptp-server-enabled').checked;
  6058. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  6059. const profile = document.getElementById('pptp-server-profile').value;
  6060. const mppe = document.getElementById('pptp-server-mppe').checked;
  6061. try {
  6062. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  6063. method: 'POST',
  6064. headers: { 'Content-Type': 'application/json' },
  6065. body: JSON.stringify({
  6066. enabled,
  6067. port,
  6068. default_profile: profile,
  6069. require_mppe: mppe
  6070. })
  6071. });
  6072. if (res.ok) {
  6073. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  6074. loadPPPServers();
  6075. fetchData(false);
  6076. } else {
  6077. const err = await res.json();
  6078. showToast('Error', err.message, 'error');
  6079. }
  6080. } catch (err) {
  6081. showToast('Error', err.message, 'error');
  6082. }
  6083. }
  6084. async function saveL2TPServerConfig(e) {
  6085. e.preventDefault();
  6086. const enabled = document.getElementById('l2tp-server-enabled').checked;
  6087. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  6088. const profile = document.getElementById('l2tp-server-profile').value;
  6089. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  6090. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  6091. try {
  6092. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  6093. method: 'POST',
  6094. headers: { 'Content-Type': 'application/json' },
  6095. body: JSON.stringify({
  6096. enabled,
  6097. port,
  6098. default_profile: profile,
  6099. use_ipsec: useipsec,
  6100. ipsec_secret: psk
  6101. })
  6102. });
  6103. if (res.ok) {
  6104. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  6105. loadPPPServers();
  6106. fetchData(false);
  6107. } else {
  6108. const err = await res.json();
  6109. showToast('Error', err.message, 'error');
  6110. }
  6111. } catch (err) {
  6112. showToast('Error', err.message, 'error');
  6113. }
  6114. }
  6115. // IPSec Server Modal
  6116. function openIPSecServerModal() {
  6117. loadPPPServers();
  6118. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  6119. }
  6120. function closeIPSecServerModal() {
  6121. document.getElementById('ipsec-server-modal').classList.add('hidden');
  6122. }
  6123. async function submitSaveIPSecServer(e) {
  6124. e.preventDefault();
  6125. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  6126. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  6127. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  6128. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  6129. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  6130. try {
  6131. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  6132. method: 'POST',
  6133. headers: { 'Content-Type': 'application/json' },
  6134. body: JSON.stringify({
  6135. enabled,
  6136. preshared_key: psk,
  6137. pool_address: pool,
  6138. dns_servers: dns,
  6139. local_subnet: subnet
  6140. })
  6141. });
  6142. if (res.ok) {
  6143. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  6144. closeIPSecServerModal();
  6145. loadPPPServers();
  6146. fetchData(false);
  6147. } else {
  6148. const err = await res.json();
  6149. showToast('Error', err.message, 'error');
  6150. }
  6151. } catch (err) {
  6152. showToast('Error', err.message, 'error');
  6153. }
  6154. }
  6155. // WireGuard Client Config Viewer
  6156. let currentWGClientConf = '';
  6157. async function openWGClientConfModal(iface, clientIP) {
  6158. try {
  6159. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  6160. method: 'POST',
  6161. headers: { 'Content-Type': 'application/json' },
  6162. body: JSON.stringify({
  6163. interface: iface,
  6164. address: clientIP || '10.10.0.2/32',
  6165. dns: '1.1.1.1, 8.8.8.8'
  6166. })
  6167. });
  6168. if (res.ok) {
  6169. const data = await res.json();
  6170. currentWGClientConf = data.config;
  6171. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  6172. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  6173. } else {
  6174. const err = await res.json();
  6175. showToast('Error', err.message, 'error');
  6176. }
  6177. } catch (err) {
  6178. showToast('Error', err.message, 'error');
  6179. }
  6180. }
  6181. function closeWGClientConfModal() {
  6182. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  6183. }
  6184. function copyWGClientConf() {
  6185. if (!currentWGClientConf) return;
  6186. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  6187. }
  6188. function downloadWGClientConf() {
  6189. if (!currentWGClientConf) return;
  6190. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  6191. const a = document.createElement('a');
  6192. a.href = URL.createObjectURL(blob);
  6193. a.download = 'wireguard-client.conf';
  6194. document.body.appendChild(a);
  6195. a.click();
  6196. document.body.removeChild(a);
  6197. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  6198. }
  6199. // =========================================================================
  6200. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  6201. // =========================================================================
  6202. state.activeDynSubTab = 'bgp-peers';
  6203. state.activeBgpSubTab = 'bgp-peers';
  6204. state.activeOspfSubTab = 'ospf-ifaces';
  6205. state.bgpInstance = null;
  6206. state.bgpPeers = [];
  6207. state.bgpNets = [];
  6208. state.bgpRoutes = [];
  6209. state.ospfInstance = null;
  6210. state.ospfInterfaces = [];
  6211. state.ospfAreas = [];
  6212. state.ospfNeighbors = [];
  6213. state.ospfRoutes = [];
  6214. function switchBgpSubTab(subTab) {
  6215. state.activeBgpSubTab = subTab;
  6216. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  6217. tabs.forEach(t => {
  6218. const el = document.getElementById(`dyn-subtab-${t}`);
  6219. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  6220. if (el) el.classList.toggle('hidden', t !== subTab);
  6221. if (btn) {
  6222. if (t === subTab) {
  6223. 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';
  6224. } else {
  6225. 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';
  6226. }
  6227. }
  6228. });
  6229. }
  6230. function switchOspfSubTab(subTab) {
  6231. state.activeOspfSubTab = subTab;
  6232. const tabs = ['ospf-ifaces', 'ospf-areas', 'ospf-nbrs', 'ospf-routes'];
  6233. tabs.forEach(t => {
  6234. const el = document.getElementById(`dyn-subtab-${t}`);
  6235. const btn = document.getElementById(`ospf-subtab-btn-${t}`);
  6236. if (el) el.classList.toggle('hidden', t !== subTab);
  6237. if (btn) {
  6238. if (t === subTab) {
  6239. 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';
  6240. } else {
  6241. 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';
  6242. }
  6243. }
  6244. });
  6245. }
  6246. function switchDynSubTab(subTab) {
  6247. if (subTab.startsWith('bgp')) {
  6248. if (state.activeTab !== 'bgp') navigate('bgp');
  6249. switchBgpSubTab(subTab);
  6250. } else if (subTab.startsWith('ospf')) {
  6251. if (state.activeTab !== 'ospf') navigate('ospf');
  6252. switchOspfSubTab(subTab);
  6253. }
  6254. }
  6255. async function loadDynamicRouting(showToastMsg = false) {
  6256. try {
  6257. const fetchSafeJson = async (url) => {
  6258. try {
  6259. const r = await fetch(url);
  6260. return r.ok ? await r.json() : null;
  6261. } catch (e) {
  6262. return null;
  6263. }
  6264. };
  6265. const [sum, bgpInst, bgpPeers, bgpNets, bgpRoutes, ospfInst, ospfIfaces, ospfAreas, ospfNbrs, ospfRoutes, filters] = await Promise.all([
  6266. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  6267. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  6268. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  6269. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  6270. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  6271. fetchSafeJson(`${API_BASE}/routing/ospf/instance`),
  6272. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces`),
  6273. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  6274. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  6275. fetchSafeJson(`${API_BASE}/routing/ospf/routes`),
  6276. fetchSafeJson(`${API_BASE}/routing/filters`)
  6277. ]);
  6278. if (sum) state.dynSummary = sum;
  6279. if (bgpInst) state.bgpInstance = bgpInst;
  6280. if (bgpPeers) state.bgpPeers = bgpPeers;
  6281. if (bgpNets) state.bgpNets = bgpNets;
  6282. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  6283. if (ospfInst) state.ospfInstance = ospfInst;
  6284. if (ospfIfaces) state.ospfInterfaces = ospfIfaces;
  6285. if (ospfAreas) state.ospfAreas = ospfAreas;
  6286. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  6287. if (ospfRoutes) state.ospfRoutes = ospfRoutes;
  6288. if (filters) state.routingFilters = filters;
  6289. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  6290. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  6291. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  6292. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  6293. try { renderOspfStatusPill(); } catch(e) { console.error('renderOspfStatusPill error:', e); }
  6294. try { renderOspfInterfaces(); } catch(e) { console.error('renderOspfInterfaces error:', e); }
  6295. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  6296. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  6297. try { renderOspfRoutes(); } catch(e) { console.error('renderOspfRoutes error:', e); }
  6298. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  6299. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  6300. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  6301. } catch (err) {
  6302. console.error('Failed to load dynamic routing:', err);
  6303. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  6304. }
  6305. }
  6306. function renderBgpStatusPill() {
  6307. const pill = document.getElementById('bgp-live-status-pill');
  6308. if (!pill) return;
  6309. const inst = state.bgpInstance;
  6310. if (!inst || !inst.enabled) {
  6311. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  6312. pill.innerText = 'BGP DISABLED';
  6313. } else if (inst.running) {
  6314. 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';
  6315. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  6316. } else {
  6317. 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';
  6318. pill.innerText = 'BGP STARTING...';
  6319. }
  6320. }
  6321. function renderBgpPeers() {
  6322. const tbody = document.getElementById('bgp-peers-table-body');
  6323. if (!tbody) return;
  6324. const empty = document.getElementById('bgp-peers-empty');
  6325. const countBadge = document.getElementById('bgp-peers-count-badge');
  6326. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  6327. const peers = state.bgpPeers || [];
  6328. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  6329. if (navBadge) navBadge.innerText = peers.length;
  6330. if (peers.length === 0) {
  6331. tbody.innerHTML = '';
  6332. if (empty) empty.classList.remove('hidden');
  6333. return;
  6334. }
  6335. if (empty) empty.classList.add('hidden');
  6336. tbody.innerHTML = peers.map(p => {
  6337. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  6338. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  6339. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  6340. let stateBadge = '';
  6341. if (p.disabled) {
  6342. 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>';
  6343. } else if (p.state === 'Established') {
  6344. 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>';
  6345. } else if (p.state === 'Connect' || p.state === 'Active') {
  6346. 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>`;
  6347. } else {
  6348. 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>`;
  6349. }
  6350. return `
  6351. <tr class="hover:bg-slate-800/40 transition">
  6352. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  6353. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  6354. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  6355. <td class="py-2.5 px-3 font-bold text-slate-200">AS ${p.remote_as}</td>
  6356. <td class="py-2.5 px-3">${stateBadge}</td>
  6357. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  6358. <td class="py-2.5 px-3 text-slate-300">
  6359. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  6360. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  6361. </td>
  6362. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  6363. ${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> ` : ''}
  6364. ${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>` : ''}
  6365. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  6366. </td>
  6367. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  6368. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  6369. <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'}">
  6370. ${p.disabled ? 'Enable' : 'Disable'}
  6371. </button>
  6372. <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">
  6373. Edit
  6374. </button>
  6375. <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">
  6376. Delete
  6377. </button>
  6378. </td>
  6379. </tr>
  6380. `;
  6381. }).join('');
  6382. }
  6383. function renderBgpNetworks() {
  6384. const tbody = document.getElementById('bgp-nets-table-body');
  6385. if (!tbody) return;
  6386. const empty = document.getElementById('bgp-nets-empty');
  6387. const countBadge = document.getElementById('bgp-nets-count-badge');
  6388. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  6389. const nets = state.bgpNets || [];
  6390. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  6391. if (navBadge) navBadge.innerText = nets.length;
  6392. if (nets.length === 0) {
  6393. tbody.innerHTML = '';
  6394. if (empty) empty.classList.remove('hidden');
  6395. return;
  6396. }
  6397. if (empty) empty.classList.add('hidden');
  6398. tbody.innerHTML = nets.map(n => `
  6399. <tr class="hover:bg-slate-800/40 transition">
  6400. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  6401. <td class="py-2.5 px-3">
  6402. ${n.disabled
  6403. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  6404. : '<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>'}
  6405. </td>
  6406. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  6407. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  6408. <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">
  6409. Delete
  6410. </button>
  6411. </td>
  6412. </tr>
  6413. `).join('');
  6414. }
  6415. function renderBgpRoutes() {
  6416. const tbody = document.getElementById('bgp-routes-table-body');
  6417. if (!tbody) return;
  6418. const empty = document.getElementById('bgp-routes-empty');
  6419. const countBadge = document.getElementById('bgp-routes-count-badge');
  6420. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  6421. const routes = state.bgpRoutes || [];
  6422. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  6423. if (navBadge) navBadge.innerText = routes.length;
  6424. if (routes.length === 0) {
  6425. tbody.innerHTML = '';
  6426. if (empty) empty.classList.remove('hidden');
  6427. return;
  6428. }
  6429. if (empty) empty.classList.add('hidden');
  6430. tbody.innerHTML = routes.map(r => `
  6431. <tr class="hover:bg-slate-800/40 transition">
  6432. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  6433. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  6434. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  6435. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  6436. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  6437. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  6438. </tr>
  6439. `).join('');
  6440. }
  6441. function renderOspfStatusPill() {
  6442. const pill = document.getElementById('ospf-live-status-pill');
  6443. if (!pill) return;
  6444. const inst = state.ospfInstance;
  6445. if (!inst || !inst.enabled) {
  6446. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  6447. pill.innerText = 'OSPF DISABLED';
  6448. } else if (inst.running) {
  6449. 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';
  6450. pill.innerText = `OSPF ACTIVE (ID: ${inst.router_id || 'Auto'})`;
  6451. } else {
  6452. 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';
  6453. pill.innerText = 'OSPF STARTING...';
  6454. }
  6455. }
  6456. function renderOspfInterfaces() {
  6457. const tbody = document.getElementById('ospf-ifaces-table-body');
  6458. if (!tbody) return;
  6459. const empty = document.getElementById('ospf-ifaces-empty');
  6460. const countBadge = document.getElementById('ospf-ifaces-count-badge');
  6461. const navBadge = document.getElementById('dyn-badge-ospf-ifaces');
  6462. const ifaces = state.ospfInterfaces || [];
  6463. if (countBadge) countBadge.innerText = `${ifaces.length} Interfaces`;
  6464. if (navBadge) navBadge.innerText = ifaces.length;
  6465. if (ifaces.length === 0) {
  6466. tbody.innerHTML = '';
  6467. if (empty) empty.classList.remove('hidden');
  6468. return;
  6469. }
  6470. if (empty) empty.classList.add('hidden');
  6471. tbody.innerHTML = ifaces.map(i => {
  6472. let flagA = !i.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  6473. let flagP = i.passive ? '<span class="text-amber-400 font-bold ml-1" title="Passive">P</span>' : '';
  6474. let flagX = i.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  6475. return `
  6476. <tr class="hover:bg-slate-800/40 transition">
  6477. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagP}${flagX}</td>
  6478. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(i.network)}</td>
  6479. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(i.area)}</td>
  6480. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(i.interface || 'Any')}</td>
  6481. <td class="py-2.5 px-3 text-slate-300">${i.cost}</td>
  6482. <td class="py-2.5 px-3 text-slate-300">${i.priority}</td>
  6483. <td class="py-2.5 px-3 text-slate-400">${i.hello_interval}s / ${i.dead_interval}s</td>
  6484. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(i.auth_type || 'none')}</td>
  6485. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(i.comment || '')}</td>
  6486. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  6487. <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'}">
  6488. ${i.disabled ? 'Enable' : 'Disable'}
  6489. </button>
  6490. <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">
  6491. Edit
  6492. </button>
  6493. <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">
  6494. Delete
  6495. </button>
  6496. </td>
  6497. </tr>
  6498. `;
  6499. }).join('');
  6500. }
  6501. function renderOspfAreas() {
  6502. const tbody = document.getElementById('ospf-areas-table-body');
  6503. if (!tbody) return;
  6504. const countBadge = document.getElementById('ospf-areas-count-badge');
  6505. const navBadge = document.getElementById('dyn-badge-ospf-areas');
  6506. const areas = state.ospfAreas || [];
  6507. if (countBadge) countBadge.innerText = `${areas.length} Areas`;
  6508. if (navBadge) navBadge.innerText = areas.length;
  6509. tbody.innerHTML = areas.map(a => `
  6510. <tr class="hover:bg-slate-800/40 transition">
  6511. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(a.name)}</td>
  6512. <td class="py-2.5 px-3 font-bold text-indigo-300">${escapeHtml(a.area_id)}</td>
  6513. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(a.area_type || 'default')}</td>
  6514. <td class="py-2.5 px-3 text-slate-400 font-sans">${escapeHtml(a.comment || '')}</td>
  6515. <td class="py-2.5 px-3 text-right font-sans">
  6516. <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">
  6517. Delete
  6518. </button>
  6519. </td>
  6520. </tr>
  6521. `).join('');
  6522. }
  6523. function renderOspfNeighbors() {
  6524. const tbody = document.getElementById('ospf-nbrs-table-body');
  6525. if (!tbody) return;
  6526. const empty = document.getElementById('ospf-nbrs-empty');
  6527. const countBadge = document.getElementById('ospf-nbrs-count-badge');
  6528. const navBadge = document.getElementById('dyn-badge-ospf-nbrs');
  6529. const nbrs = state.ospfNeighbors || [];
  6530. if (countBadge) countBadge.innerText = `${nbrs.length} Neighbors`;
  6531. if (navBadge) navBadge.innerText = nbrs.length;
  6532. if (nbrs.length === 0) {
  6533. tbody.innerHTML = '';
  6534. if (empty) empty.classList.remove('hidden');
  6535. return;
  6536. }
  6537. if (empty) empty.classList.add('hidden');
  6538. tbody.innerHTML = nbrs.map(n => {
  6539. let stateBadge = '';
  6540. if (n.state && (n.state.startsWith('Full') || n.state.includes('DR') || n.state.includes('Backup'))) {
  6541. 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>`;
  6542. } else {
  6543. 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>`;
  6544. }
  6545. return `
  6546. <tr class="hover:bg-slate-800/40 transition">
  6547. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(n.neighbor_id)}</td>
  6548. <td class="py-2.5 px-3 text-indigo-300 font-bold">${escapeHtml(n.address)}</td>
  6549. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(n.interface)}</td>
  6550. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.area || '0.0.0.0')}</td>
  6551. <td class="py-2.5 px-3">${stateBadge}</td>
  6552. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.dead_timer || '-')}</td>
  6553. </tr>
  6554. `;
  6555. }).join('');
  6556. }
  6557. function renderOspfRoutes() {
  6558. const tbody = document.getElementById('ospf-routes-table-body');
  6559. if (!tbody) return;
  6560. const empty = document.getElementById('ospf-routes-empty');
  6561. const countBadge = document.getElementById('ospf-routes-count-badge');
  6562. const navBadge = document.getElementById('dyn-badge-ospf-routes');
  6563. const routes = state.ospfRoutes || [];
  6564. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  6565. if (navBadge) navBadge.innerText = routes.length;
  6566. if (routes.length === 0) {
  6567. tbody.innerHTML = '';
  6568. if (empty) empty.classList.remove('hidden');
  6569. return;
  6570. }
  6571. if (empty) empty.classList.add('hidden');
  6572. tbody.innerHTML = routes.map(r => `
  6573. <tr class="hover:bg-slate-800/40 transition">
  6574. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(r.prefix)}</td>
  6575. <td class="py-2.5 px-3 text-slate-300">${escapeHtml(r.route_type || 'Network')}</td>
  6576. <td class="py-2.5 px-3 text-slate-300">${r.cost}</td>
  6577. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(r.area || '0.0.0.0')}</td>
  6578. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(r.next_hop || r.interface || '-')}</td>
  6579. </tr>
  6580. `).join('');
  6581. }
  6582. // BGP Modals & Actions
  6583. function openBgpInstanceModal() {
  6584. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  6585. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  6586. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  6587. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  6588. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  6589. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  6590. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  6591. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  6592. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  6593. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  6594. }
  6595. function closeBgpInstanceModal() {
  6596. document.getElementById('bgp-instance-modal').classList.add('hidden');
  6597. }
  6598. async function submitBgpInstance(e) {
  6599. e.preventDefault();
  6600. const payload = {
  6601. enabled: document.getElementById('modal-bgp-enabled').checked,
  6602. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  6603. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  6604. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  6605. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  6606. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  6607. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  6608. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  6609. };
  6610. try {
  6611. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  6612. method: 'POST',
  6613. headers: { 'Content-Type': 'application/json' },
  6614. body: JSON.stringify(payload)
  6615. });
  6616. if (res.ok) {
  6617. closeBgpInstanceModal();
  6618. showToast('Success', 'BGP instance configuration updated', 'success');
  6619. loadDynamicRouting();
  6620. } else {
  6621. const err = await res.json();
  6622. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  6623. }
  6624. } catch (err) {
  6625. showToast('Error', err.message, 'error');
  6626. }
  6627. }
  6628. function openAddBgpPeerModal() {
  6629. document.getElementById('bgp-peer-form').reset();
  6630. document.getElementById('modal-bgp-peer-id').value = '';
  6631. document.getElementById('bgp-peer-modal-title').innerText = 'Add BGP Peer Connection';
  6632. document.getElementById('modal-bgp-peer-nexthop-self').checked = true;
  6633. const inFilterEl = document.getElementById('modal-bgp-peer-in-filter');
  6634. if (inFilterEl) inFilterEl.value = '';
  6635. const outFilterEl = document.getElementById('modal-bgp-peer-out-filter');
  6636. if (outFilterEl) outFilterEl.value = '';
  6637. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  6638. }
  6639. function openEditBgpPeerModal(id) {
  6640. const p = (state.bgpPeers || []).find(item => item.id === id);
  6641. if (!p) return;
  6642. document.getElementById('modal-bgp-peer-id').value = p.id;
  6643. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  6644. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  6645. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  6646. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  6647. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  6648. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  6649. document.getElementById('modal-bgp-peer-nexthop-self').checked = !!p.nexthop_self;
  6650. document.getElementById('modal-bgp-peer-passive').checked = !!p.passive;
  6651. document.getElementById('modal-bgp-peer-disabled').checked = !!p.disabled;
  6652. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  6653. const inFilterEl = document.getElementById('modal-bgp-peer-in-filter');
  6654. if (inFilterEl) inFilterEl.value = p.in_filter || '';
  6655. const outFilterEl = document.getElementById('modal-bgp-peer-out-filter');
  6656. if (outFilterEl) outFilterEl.value = p.out_filter || '';
  6657. document.getElementById('bgp-peer-modal-title').innerText = 'Edit BGP Peer Connection';
  6658. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  6659. }
  6660. function closeBgpPeerModal() {
  6661. document.getElementById('bgp-peer-modal').classList.add('hidden');
  6662. }
  6663. async function submitBgpPeer(e) {
  6664. e.preventDefault();
  6665. const payload = {
  6666. id: document.getElementById('modal-bgp-peer-id').value,
  6667. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  6668. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  6669. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10),
  6670. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  6671. password: document.getElementById('modal-bgp-peer-password').value,
  6672. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  6673. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-self').checked,
  6674. passive: document.getElementById('modal-bgp-peer-passive').checked,
  6675. disabled: document.getElementById('modal-bgp-peer-disabled').checked,
  6676. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  6677. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  6678. comment: document.getElementById('modal-bgp-peer-comment').value.trim()
  6679. };
  6680. try {
  6681. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  6682. method: 'POST',
  6683. headers: { 'Content-Type': 'application/json' },
  6684. body: JSON.stringify(payload)
  6685. });
  6686. if (res.ok) {
  6687. closeBgpPeerModal();
  6688. showToast('Success', 'BGP Peer saved', 'success');
  6689. loadDynamicRouting();
  6690. } else {
  6691. const err = await res.json();
  6692. showToast('Error', err.error || 'Failed to save peer', 'error');
  6693. }
  6694. } catch (err) {
  6695. showToast('Error', err.message, 'error');
  6696. }
  6697. }
  6698. async function deleteBgpPeer(id) {
  6699. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  6700. try {
  6701. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6702. if (res.ok) {
  6703. showToast('Deleted', 'BGP peer removed', 'success');
  6704. loadDynamicRouting();
  6705. }
  6706. } catch (err) {
  6707. showToast('Error', err.message, 'error');
  6708. }
  6709. }
  6710. async function toggleBgpPeerState(id, disabled) {
  6711. try {
  6712. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  6713. method: 'POST',
  6714. headers: { 'Content-Type': 'application/json' },
  6715. body: JSON.stringify({ disabled })
  6716. });
  6717. if (res.ok) {
  6718. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  6719. loadDynamicRouting();
  6720. }
  6721. } catch (err) {
  6722. showToast('Error', err.message, 'error');
  6723. }
  6724. }
  6725. function openAddBgpNetworkModal() {
  6726. document.getElementById('bgp-network-form').reset();
  6727. document.getElementById('modal-bgp-net-id').value = '';
  6728. document.getElementById('bgp-network-modal').classList.remove('hidden');
  6729. }
  6730. function closeBgpNetworkModal() {
  6731. document.getElementById('bgp-network-modal').classList.add('hidden');
  6732. }
  6733. async function submitBgpNetwork(e) {
  6734. e.preventDefault();
  6735. const payload = {
  6736. id: document.getElementById('modal-bgp-net-id').value,
  6737. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  6738. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  6739. disabled: document.getElementById('modal-bgp-net-disabled').checked
  6740. };
  6741. try {
  6742. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  6743. method: 'POST',
  6744. headers: { 'Content-Type': 'application/json' },
  6745. body: JSON.stringify(payload)
  6746. });
  6747. if (res.ok) {
  6748. closeBgpNetworkModal();
  6749. showToast('Success', 'BGP network advertisement saved', 'success');
  6750. loadDynamicRouting();
  6751. } else {
  6752. const err = await res.json();
  6753. showToast('Error', err.error || 'Failed to save network', 'error');
  6754. }
  6755. } catch (err) {
  6756. showToast('Error', err.message, 'error');
  6757. }
  6758. }
  6759. async function deleteBgpNetwork(id) {
  6760. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  6761. try {
  6762. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6763. if (res.ok) {
  6764. showToast('Deleted', 'Network advertisement removed', 'success');
  6765. loadDynamicRouting();
  6766. }
  6767. } catch (err) {
  6768. showToast('Error', err.message, 'error');
  6769. }
  6770. }
  6771. // OSPF Modals & Actions
  6772. function openOspfInstanceModal() {
  6773. const inst = state.ospfInstance || { enabled: false, router_id: '192.168.131.56', default_metric: 10 };
  6774. document.getElementById('modal-ospf-enabled').checked = !!inst.enabled;
  6775. document.getElementById('modal-ospf-router-id').value = inst.router_id || '';
  6776. document.getElementById('modal-ospf-metric').value = inst.default_metric || 10;
  6777. document.getElementById('modal-ospf-redist-conn').checked = !!inst.redistribute_connected;
  6778. document.getElementById('modal-ospf-redist-static').checked = !!inst.redistribute_static;
  6779. document.getElementById('modal-ospf-redist-bgp').checked = !!inst.redistribute_bgp;
  6780. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  6781. }
  6782. function closeOspfInstanceModal() {
  6783. document.getElementById('ospf-instance-modal').classList.add('hidden');
  6784. }
  6785. async function submitOspfInstance(e) {
  6786. e.preventDefault();
  6787. const payload = {
  6788. enabled: document.getElementById('modal-ospf-enabled').checked,
  6789. router_id: document.getElementById('modal-ospf-router-id').value.trim(),
  6790. default_metric: parseInt(document.getElementById('modal-ospf-metric').value, 10),
  6791. redistribute_connected: document.getElementById('modal-ospf-redist-conn').checked,
  6792. redistribute_static: document.getElementById('modal-ospf-redist-static').checked,
  6793. redistribute_bgp: document.getElementById('modal-ospf-redist-bgp').checked
  6794. };
  6795. try {
  6796. const res = await fetch(`${API_BASE}/routing/ospf/instance`, {
  6797. method: 'POST',
  6798. headers: { 'Content-Type': 'application/json' },
  6799. body: JSON.stringify(payload)
  6800. });
  6801. if (res.ok) {
  6802. closeOspfInstanceModal();
  6803. showToast('Success', 'OSPF instance configuration updated', 'success');
  6804. loadDynamicRouting();
  6805. } else {
  6806. const err = await res.json();
  6807. showToast('Error', err.error || 'Failed to update OSPF instance', 'error');
  6808. }
  6809. } catch (err) {
  6810. showToast('Error', err.message, 'error');
  6811. }
  6812. }
  6813. function openAddOspfAreaModal() {
  6814. document.getElementById('ospf-area-form').reset();
  6815. document.getElementById('modal-ospf-area-id').value = '';
  6816. document.getElementById('modal-ospf-area-areaid').value = '0.0.0.0';
  6817. document.getElementById('ospf-area-modal').classList.remove('hidden');
  6818. }
  6819. function closeOspfAreaModal() {
  6820. document.getElementById('ospf-area-modal').classList.add('hidden');
  6821. }
  6822. async function submitOspfArea(e) {
  6823. e.preventDefault();
  6824. const payload = {
  6825. id: document.getElementById('modal-ospf-area-id').value,
  6826. name: document.getElementById('modal-ospf-area-name').value.trim(),
  6827. area_id: document.getElementById('modal-ospf-area-areaid').value.trim(),
  6828. area_type: document.getElementById('modal-ospf-area-type').value,
  6829. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  6830. };
  6831. try {
  6832. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  6833. method: 'POST',
  6834. headers: { 'Content-Type': 'application/json' },
  6835. body: JSON.stringify(payload)
  6836. });
  6837. if (res.ok) {
  6838. closeOspfAreaModal();
  6839. showToast('Success', 'OSPF area saved', 'success');
  6840. loadDynamicRouting();
  6841. } else {
  6842. const err = await res.json();
  6843. showToast('Error', err.error || 'Failed to save area', 'error');
  6844. }
  6845. } catch (err) {
  6846. showToast('Error', err.message, 'error');
  6847. }
  6848. }
  6849. async function deleteOspfArea(id) {
  6850. if (!confirm('Are you sure you want to delete this OSPF area?')) return;
  6851. try {
  6852. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6853. if (res.ok) {
  6854. showToast('Deleted', 'OSPF area removed', 'success');
  6855. loadDynamicRouting();
  6856. }
  6857. } catch (err) {
  6858. showToast('Error', err.message, 'error');
  6859. }
  6860. }
  6861. function populateOspfInterfaceDevices() {
  6862. const select = document.getElementById('modal-ospf-iface-device');
  6863. if (!select) return;
  6864. const current = select.value;
  6865. select.innerHTML = '<option value="">Any matching interface</option>';
  6866. (state.interfaces || []).forEach(iface => {
  6867. select.innerHTML += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)} (${iface.type})</option>`;
  6868. });
  6869. if (current) select.value = current;
  6870. }
  6871. function openAddOspfInterfaceModal() {
  6872. document.getElementById('ospf-interface-form').reset();
  6873. document.getElementById('modal-ospf-iface-id').value = '';
  6874. document.getElementById('modal-ospf-iface-area').value = '0.0.0.0';
  6875. document.getElementById('modal-ospf-iface-cost').value = '10';
  6876. document.getElementById('modal-ospf-iface-priority').value = '1';
  6877. document.getElementById('modal-ospf-iface-hello').value = '10';
  6878. document.getElementById('modal-ospf-iface-dead').value = '40';
  6879. document.getElementById('ospf-interface-modal-title').innerText = 'Add OSPF Interface';
  6880. populateOspfInterfaceDevices();
  6881. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  6882. }
  6883. function openEditOspfInterfaceModal(id) {
  6884. const item = (state.ospfInterfaces || []).find(i => i.id === id);
  6885. if (!item) return;
  6886. populateOspfInterfaceDevices();
  6887. document.getElementById('modal-ospf-iface-id').value = item.id;
  6888. document.getElementById('modal-ospf-iface-net').value = item.network || '';
  6889. document.getElementById('modal-ospf-iface-area').value = item.area || '0.0.0.0';
  6890. document.getElementById('modal-ospf-iface-device').value = item.interface || '';
  6891. document.getElementById('modal-ospf-iface-cost').value = item.cost || 10;
  6892. document.getElementById('modal-ospf-iface-priority').value = item.priority || 1;
  6893. document.getElementById('modal-ospf-iface-hello').value = item.hello_interval || 10;
  6894. document.getElementById('modal-ospf-iface-dead').value = item.dead_interval || 40;
  6895. document.getElementById('modal-ospf-iface-auth-type').value = item.auth_type || 'none';
  6896. document.getElementById('modal-ospf-iface-auth-key').value = item.auth_key || '';
  6897. document.getElementById('modal-ospf-iface-passive').checked = !!item.passive;
  6898. document.getElementById('modal-ospf-iface-disabled').checked = !!item.disabled;
  6899. document.getElementById('modal-ospf-iface-comment').value = item.comment || '';
  6900. document.getElementById('ospf-interface-modal-title').innerText = 'Edit OSPF Interface';
  6901. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  6902. }
  6903. function closeOspfInterfaceModal() {
  6904. document.getElementById('ospf-interface-modal').classList.add('hidden');
  6905. }
  6906. async function submitOspfInterface(e) {
  6907. e.preventDefault();
  6908. const payload = {
  6909. id: document.getElementById('modal-ospf-iface-id').value,
  6910. network: document.getElementById('modal-ospf-iface-net').value.trim(),
  6911. area: document.getElementById('modal-ospf-iface-area').value.trim(),
  6912. interface: document.getElementById('modal-ospf-iface-device').value,
  6913. cost: parseInt(document.getElementById('modal-ospf-iface-cost').value, 10),
  6914. priority: parseInt(document.getElementById('modal-ospf-iface-priority').value, 10),
  6915. hello_interval: parseInt(document.getElementById('modal-ospf-iface-hello').value, 10),
  6916. dead_interval: parseInt(document.getElementById('modal-ospf-iface-dead').value, 10),
  6917. auth_type: document.getElementById('modal-ospf-iface-auth-type').value,
  6918. auth_key: document.getElementById('modal-ospf-iface-auth-key').value,
  6919. passive: document.getElementById('modal-ospf-iface-passive').checked,
  6920. disabled: document.getElementById('modal-ospf-iface-disabled').checked,
  6921. comment: document.getElementById('modal-ospf-iface-comment').value.trim()
  6922. };
  6923. try {
  6924. const res = await fetch(`${API_BASE}/routing/ospf/interfaces`, {
  6925. method: 'POST',
  6926. headers: { 'Content-Type': 'application/json' },
  6927. body: JSON.stringify(payload)
  6928. });
  6929. if (res.ok) {
  6930. closeOspfInterfaceModal();
  6931. showToast('Success', 'OSPF interface template saved', 'success');
  6932. loadDynamicRouting();
  6933. } else {
  6934. const err = await res.json();
  6935. showToast('Error', err.error || 'Failed to save interface', 'error');
  6936. }
  6937. } catch (err) {
  6938. showToast('Error', err.message, 'error');
  6939. }
  6940. }
  6941. async function deleteOspfInterface(id) {
  6942. if (!confirm('Are you sure you want to delete this OSPF interface?')) return;
  6943. try {
  6944. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6945. if (res.ok) {
  6946. showToast('Deleted', 'OSPF interface removed', 'success');
  6947. loadDynamicRouting();
  6948. }
  6949. } catch (err) {
  6950. showToast('Error', err.message, 'error');
  6951. }
  6952. }
  6953. async function toggleOspfInterfaceState(id, disabled) {
  6954. try {
  6955. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}/state`, {
  6956. method: 'POST',
  6957. headers: { 'Content-Type': 'application/json' },
  6958. body: JSON.stringify({ disabled })
  6959. });
  6960. if (res.ok) {
  6961. showToast('Updated', `Interface ${disabled ? 'disabled' : 'enabled'}`, 'success');
  6962. loadDynamicRouting();
  6963. }
  6964. } catch (err) {
  6965. showToast('Error', err.message, 'error');
  6966. }
  6967. }
  6968. // ============================================================================
  6969. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  6970. // ============================================================================
  6971. function switchBridgeSubTab(tab) {
  6972. state.bridgeSubTab = tab;
  6973. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  6974. tabs.forEach(t => {
  6975. const panel = document.getElementById(`bridge-subtab-${t}`);
  6976. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  6977. if (panel) {
  6978. if (t === tab) panel.classList.remove('hidden');
  6979. else panel.classList.add('hidden');
  6980. }
  6981. if (btn) {
  6982. if (t === tab) {
  6983. 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';
  6984. } else {
  6985. 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';
  6986. }
  6987. }
  6988. });
  6989. const addBtn = document.getElementById('bridge-top-action-btn');
  6990. if (addBtn) {
  6991. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  6992. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  6993. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  6994. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  6995. }
  6996. if (tab === 'hosts') loadBridgeHosts();
  6997. setTimeout(initTableSorting, 50);
  6998. }
  6999. function openCurrentBridgeModal() {
  7000. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  7001. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  7002. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  7003. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  7004. }
  7005. async function loadBridge() {
  7006. try {
  7007. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  7008. fetch(`${API_BASE}/bridge/bridges`),
  7009. fetch(`${API_BASE}/bridge/ports`),
  7010. fetch(`${API_BASE}/bridge/vlans`),
  7011. fetch(`${API_BASE}/bridge/summary`),
  7012. fetch(`${API_BASE}/vpn/eoip`),
  7013. fetch(`${API_BASE}/vlans`)
  7014. ]);
  7015. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  7016. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  7017. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  7018. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  7019. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  7020. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  7021. // Badges & Stats
  7022. const bBridges = document.getElementById('bridge-badge-bridges');
  7023. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  7024. const bPorts = document.getElementById('bridge-badge-ports');
  7025. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  7026. const bVlans = document.getElementById('bridge-badge-vlans');
  7027. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  7028. const bHosts = document.getElementById('bridge-badge-hosts');
  7029. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  7030. const sBr = document.getElementById('bridge-stat-bridges');
  7031. if (sBr) sBr.innerText = (state.bridges || []).length;
  7032. const sPorts = document.getElementById('bridge-stat-ports');
  7033. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  7034. const sHosts = document.getElementById('bridge-stat-hosts');
  7035. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  7036. renderBridges();
  7037. renderBridgePorts();
  7038. renderBridgeVLANs();
  7039. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  7040. } catch (err) {
  7041. console.error('Failed to load bridge subsystem:', err);
  7042. }
  7043. }
  7044. // ----------------- Bridges -----------------
  7045. function renderBridges() {
  7046. const tbody = document.getElementById('bridge-table-body');
  7047. const empty = document.getElementById('bridge-empty-bridges');
  7048. const countBadge = document.getElementById('bridge-count-badge');
  7049. if (!tbody) return;
  7050. tbody.innerHTML = '';
  7051. const bridges = state.bridges || [];
  7052. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  7053. if (bridges.length === 0) {
  7054. empty?.classList.remove('hidden');
  7055. return;
  7056. }
  7057. empty?.classList.add('hidden');
  7058. bridges.forEach((b, idx) => {
  7059. const tr = document.createElement('tr');
  7060. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  7061. // Format IP addresses pill list
  7062. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  7063. if (b.ip_addresses && b.ip_addresses.length > 0) {
  7064. ipsHtml = b.ip_addresses.map(ip => `
  7065. <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">
  7066. <span>${ip}</span>
  7067. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  7068. </span>
  7069. `).join(' ');
  7070. }
  7071. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  7072. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  7073. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  7074. tr.innerHTML = `
  7075. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  7076. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  7077. <td class="py-2.5 px-3 font-bold text-white text-sm">
  7078. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  7079. </td>
  7080. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  7081. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  7082. <td class="py-2.5 px-3">
  7083. <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>
  7084. </td>
  7085. <td class="py-2.5 px-3 text-center">
  7086. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  7087. </td>
  7088. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  7089. <td class="py-2.5 px-3">
  7090. <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>
  7091. </td>
  7092. <td class="py-2.5 px-3">
  7093. <div class="flex items-center gap-1.5 flex-wrap">
  7094. ${ipsHtml}
  7095. <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>
  7096. </div>
  7097. </td>
  7098. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  7099. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  7100. </td>
  7101. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  7102. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7103. <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>
  7104. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7105. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  7106. </td>
  7107. `;
  7108. tbody.appendChild(tr);
  7109. });
  7110. }
  7111. function openAddBridgeModal() {
  7112. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  7113. document.getElementById('bridge-modal-id').value = '';
  7114. document.getElementById('bridge-modal-name').value = 'bridge1';
  7115. document.getElementById('bridge-modal-name').disabled = false;
  7116. document.getElementById('bridge-modal-mtu').value = '1500';
  7117. document.getElementById('bridge-modal-mac').value = '';
  7118. document.getElementById('bridge-modal-stp').value = 'rstp';
  7119. document.getElementById('bridge-modal-priority').value = '32768';
  7120. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  7121. document.getElementById('bridge-modal-pvid').value = '1';
  7122. document.getElementById('bridge-modal-fastforward').checked = true;
  7123. document.getElementById('bridge-modal-comment').value = '';
  7124. document.getElementById('bridge-modal-disabled').checked = false;
  7125. toggleBridgeModalVlanFiltering();
  7126. document.getElementById('bridge-modal').classList.remove('hidden');
  7127. }
  7128. function openEditBridgeModal(id) {
  7129. const b = (state.bridges || []).find(x => x.id === id);
  7130. if (!b) return;
  7131. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  7132. document.getElementById('bridge-modal-id').value = b.id;
  7133. document.getElementById('bridge-modal-name').value = b.name;
  7134. document.getElementById('bridge-modal-name').disabled = true;
  7135. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  7136. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  7137. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  7138. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  7139. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  7140. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  7141. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  7142. document.getElementById('bridge-modal-comment').value = b.comment || '';
  7143. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  7144. toggleBridgeModalVlanFiltering();
  7145. document.getElementById('bridge-modal').classList.remove('hidden');
  7146. }
  7147. function closeBridgeModal() {
  7148. document.getElementById('bridge-modal').classList.add('hidden');
  7149. }
  7150. function toggleBridgeModalVlanFiltering() {
  7151. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  7152. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  7153. if (pvidBox) {
  7154. if (chk) pvidBox.classList.remove('opacity-40');
  7155. else pvidBox.classList.add('opacity-40');
  7156. }
  7157. }
  7158. async function submitSaveBridge(e) {
  7159. e.preventDefault();
  7160. const id = document.getElementById('bridge-modal-id').value;
  7161. const name = document.getElementById('bridge-modal-name').value.trim();
  7162. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  7163. const mac = document.getElementById('bridge-modal-mac').value.trim();
  7164. const stp = document.getElementById('bridge-modal-stp').value;
  7165. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  7166. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  7167. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  7168. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  7169. const comment = document.getElementById('bridge-modal-comment').value.trim();
  7170. const disabled = document.getElementById('bridge-modal-disabled').checked;
  7171. try {
  7172. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  7173. method: 'POST',
  7174. headers: { 'Content-Type': 'application/json' },
  7175. body: JSON.stringify({
  7176. id,
  7177. name,
  7178. mtu,
  7179. mac_address: mac,
  7180. stp,
  7181. priority,
  7182. vlan_filtering: vlanFiltering,
  7183. pvid,
  7184. fast_forward: fastForward,
  7185. comment,
  7186. disabled
  7187. })
  7188. });
  7189. if (res.ok) {
  7190. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  7191. closeBridgeModal();
  7192. loadBridge();
  7193. fetchData(false);
  7194. } else {
  7195. const err = await res.json();
  7196. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  7197. }
  7198. } catch (err) {
  7199. showToast('Error', err.message, 'error');
  7200. }
  7201. }
  7202. async function toggleBridgeState(id, disabled) {
  7203. try {
  7204. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  7205. method: 'POST',
  7206. headers: { 'Content-Type': 'application/json' },
  7207. body: JSON.stringify({ disabled })
  7208. });
  7209. if (res.ok) {
  7210. loadBridge();
  7211. fetchData(false);
  7212. }
  7213. } catch (err) {
  7214. showToast('Error', err.message, 'error');
  7215. }
  7216. }
  7217. async function deleteBridge(id) {
  7218. const b = (state.bridges || []).find(x => x.id === id);
  7219. const name = b ? b.name : id;
  7220. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  7221. try {
  7222. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7223. if (res.ok) {
  7224. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  7225. loadBridge();
  7226. fetchData(false);
  7227. } else {
  7228. const err = await res.json();
  7229. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  7230. }
  7231. } catch (err) {
  7232. showToast('Error', err.message, 'error');
  7233. }
  7234. }
  7235. // ----------------- Bridge IP Assignments -----------------
  7236. function openAddBridgeIPModal(id, name) {
  7237. document.getElementById('bridge-ip-modal-id').value = id;
  7238. document.getElementById('bridge-ip-modal-sub').innerText = name;
  7239. document.getElementById('bridge-ip-modal-cidr').value = '';
  7240. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  7241. }
  7242. function closeBridgeIPModal() {
  7243. document.getElementById('bridge-ip-modal').classList.add('hidden');
  7244. }
  7245. async function submitAddBridgeIP(e) {
  7246. e.preventDefault();
  7247. const id = document.getElementById('bridge-ip-modal-id').value;
  7248. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  7249. try {
  7250. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  7251. method: 'POST',
  7252. headers: { 'Content-Type': 'application/json' },
  7253. body: JSON.stringify({ ip })
  7254. });
  7255. if (res.ok) {
  7256. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  7257. closeBridgeIPModal();
  7258. loadBridge();
  7259. fetchData(false);
  7260. } else {
  7261. const err = await res.json();
  7262. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  7263. }
  7264. } catch (err) {
  7265. showToast('Error', err.message, 'error');
  7266. }
  7267. }
  7268. async function deleteBridgeIP(id, ip) {
  7269. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  7270. try {
  7271. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  7272. method: 'DELETE',
  7273. headers: { 'Content-Type': 'application/json' },
  7274. body: JSON.stringify({ ip })
  7275. });
  7276. if (res.ok) {
  7277. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  7278. loadBridge();
  7279. fetchData(false);
  7280. }
  7281. } catch (err) {
  7282. showToast('Error', err.message, 'error');
  7283. }
  7284. }
  7285. // ----------------- Bridge Ports -----------------
  7286. function renderBridgePorts() {
  7287. const tbody = document.getElementById('bridge-ports-table-body');
  7288. const empty = document.getElementById('bridge-empty-ports');
  7289. const countBadge = document.getElementById('bridge-ports-count-badge');
  7290. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  7291. if (!tbody) return;
  7292. tbody.innerHTML = '';
  7293. // Update filter select
  7294. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  7295. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  7296. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  7297. if (ports.length === 0) {
  7298. empty?.classList.remove('hidden');
  7299. return;
  7300. }
  7301. empty?.classList.add('hidden');
  7302. ports.forEach((p, idx) => {
  7303. const tr = document.createElement('tr');
  7304. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  7305. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  7306. tr.innerHTML = `
  7307. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  7308. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  7309. <td class="py-2.5 px-3 font-bold text-white text-sm">
  7310. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  7311. </td>
  7312. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  7313. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  7314. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  7315. <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>
  7316. <td class="py-2.5 px-3">
  7317. ${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>'}
  7318. </td>
  7319. <td class="py-2.5 px-3">
  7320. <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>
  7321. </td>
  7322. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  7323. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7324. <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>
  7325. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7326. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  7327. </td>
  7328. `;
  7329. tbody.appendChild(tr);
  7330. });
  7331. }
  7332. function openAddBridgePortModal() {
  7333. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  7334. document.getElementById('bridge-port-modal-id').value = '';
  7335. populateBridgeSelect('bridge-port-modal-bridge');
  7336. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  7337. document.getElementById('bridge-port-modal-pvid').value = '1';
  7338. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  7339. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  7340. document.getElementById('bridge-port-modal-horizon').value = '0';
  7341. document.getElementById('bridge-port-modal-pathcost').value = '10';
  7342. document.getElementById('bridge-port-modal-priority').value = '128';
  7343. document.getElementById('bridge-port-modal-learn').checked = true;
  7344. document.getElementById('bridge-port-modal-comment').value = '';
  7345. document.getElementById('bridge-port-modal-disabled').checked = false;
  7346. document.getElementById('bridge-port-modal').classList.remove('hidden');
  7347. }
  7348. function openEditBridgePortModal(id) {
  7349. const p = (state.bridgePorts || []).find(x => x.id === id);
  7350. if (!p) return;
  7351. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  7352. document.getElementById('bridge-port-modal-id').value = p.id;
  7353. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  7354. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  7355. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  7356. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  7357. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  7358. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  7359. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  7360. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  7361. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  7362. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  7363. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  7364. document.getElementById('bridge-port-modal').classList.remove('hidden');
  7365. }
  7366. function closeBridgePortModal() {
  7367. document.getElementById('bridge-port-modal').classList.add('hidden');
  7368. }
  7369. async function submitSaveBridgePort(e) {
  7370. e.preventDefault();
  7371. const id = document.getElementById('bridge-port-modal-id').value;
  7372. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  7373. const iface = document.getElementById('bridge-port-modal-interface').value;
  7374. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  7375. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  7376. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  7377. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  7378. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  7379. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  7380. const learn = document.getElementById('bridge-port-modal-learn').checked;
  7381. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  7382. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  7383. try {
  7384. const res = await fetch(`${API_BASE}/bridge/ports`, {
  7385. method: 'POST',
  7386. headers: { 'Content-Type': 'application/json' },
  7387. body: JSON.stringify({
  7388. id,
  7389. bridge,
  7390. interface: iface,
  7391. pvid,
  7392. frame_types: frameTypes,
  7393. ingress_filtering: ingressFiltering,
  7394. horizon,
  7395. path_cost: pathCost,
  7396. priority,
  7397. learn,
  7398. comment,
  7399. disabled
  7400. })
  7401. });
  7402. if (res.ok) {
  7403. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  7404. closeBridgePortModal();
  7405. loadBridge();
  7406. fetchData(false);
  7407. } else {
  7408. const err = await res.json();
  7409. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  7410. }
  7411. } catch (err) {
  7412. showToast('Error', err.message, 'error');
  7413. }
  7414. }
  7415. async function toggleBridgePortState(id, disabled) {
  7416. try {
  7417. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  7418. method: 'POST',
  7419. headers: { 'Content-Type': 'application/json' },
  7420. body: JSON.stringify({ disabled })
  7421. });
  7422. if (res.ok) {
  7423. loadBridge();
  7424. fetchData(false);
  7425. }
  7426. } catch (err) {
  7427. showToast('Error', err.message, 'error');
  7428. }
  7429. }
  7430. async function deleteBridgePort(id) {
  7431. const p = (state.bridgePorts || []).find(x => x.id === id);
  7432. const iface = p ? p.interface : id;
  7433. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  7434. try {
  7435. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7436. if (res.ok) {
  7437. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  7438. loadBridge();
  7439. fetchData(false);
  7440. }
  7441. } catch (err) {
  7442. showToast('Error', err.message, 'error');
  7443. }
  7444. }
  7445. // ----------------- Bridge VLANs -----------------
  7446. function renderBridgeVLANs() {
  7447. const tbody = document.getElementById('bridge-vlans-table-body');
  7448. const empty = document.getElementById('bridge-empty-vlans');
  7449. const countBadge = document.getElementById('bridge-vlans-count-badge');
  7450. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  7451. if (!tbody) return;
  7452. tbody.innerHTML = '';
  7453. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  7454. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  7455. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  7456. if (vlans.length === 0) {
  7457. empty?.classList.remove('hidden');
  7458. return;
  7459. }
  7460. empty?.classList.add('hidden');
  7461. vlans.forEach((v, idx) => {
  7462. const tr = document.createElement('tr');
  7463. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  7464. const taggedHtml = (v.tagged && v.tagged.length > 0)
  7465. ? 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(' ')
  7466. : '<span class="text-slate-600">none</span>';
  7467. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  7468. ? 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(' ')
  7469. : '<span class="text-slate-600">none</span>';
  7470. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  7471. tr.innerHTML = `
  7472. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  7473. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  7474. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  7475. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  7476. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  7477. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  7478. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  7479. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7480. <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>
  7481. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7482. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  7483. </td>
  7484. `;
  7485. tbody.appendChild(tr);
  7486. });
  7487. }
  7488. function openAddBridgeVLANModal() {
  7489. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  7490. document.getElementById('bridge-vlan-modal-id').value = '';
  7491. populateBridgeSelect('bridge-vlan-modal-bridge');
  7492. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  7493. document.getElementById('bridge-vlan-modal-comment').value = '';
  7494. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  7495. updateBridgeVlanPortCheckboxes();
  7496. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  7497. }
  7498. function openEditBridgeVLANModal(id) {
  7499. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  7500. if (!v) return;
  7501. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  7502. document.getElementById('bridge-vlan-modal-id').value = v.id;
  7503. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  7504. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  7505. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  7506. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  7507. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  7508. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  7509. }
  7510. function closeBridgeVlanModal() {
  7511. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  7512. }
  7513. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  7514. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  7515. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  7516. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  7517. if (!taggedBox || !untaggedBox) return;
  7518. // Ports belonging to the selected bridge
  7519. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  7520. if (memberPorts.length === 0) {
  7521. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  7522. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  7523. return;
  7524. }
  7525. taggedBox.innerHTML = memberPorts.map(p => `
  7526. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  7527. <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">
  7528. <span>${p.interface}</span>
  7529. </label>
  7530. `).join('');
  7531. untaggedBox.innerHTML = memberPorts.map(p => `
  7532. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  7533. <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">
  7534. <span>${p.interface}</span>
  7535. </label>
  7536. `).join('');
  7537. }
  7538. async function submitSaveBridgeVLAN(e) {
  7539. e.preventDefault();
  7540. const id = document.getElementById('bridge-vlan-modal-id').value;
  7541. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  7542. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  7543. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  7544. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  7545. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  7546. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  7547. try {
  7548. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  7549. method: 'POST',
  7550. headers: { 'Content-Type': 'application/json' },
  7551. body: JSON.stringify({
  7552. id,
  7553. bridge,
  7554. vlan_ids: vlanIDs,
  7555. tagged,
  7556. untagged,
  7557. comment,
  7558. disabled
  7559. })
  7560. });
  7561. if (res.ok) {
  7562. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  7563. closeBridgeVlanModal();
  7564. loadBridge();
  7565. } else {
  7566. const err = await res.json();
  7567. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  7568. }
  7569. } catch (err) {
  7570. showToast('Error', err.message, 'error');
  7571. }
  7572. }
  7573. async function toggleBridgeVLANState(id, disabled) {
  7574. try {
  7575. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  7576. method: 'POST',
  7577. headers: { 'Content-Type': 'application/json' },
  7578. body: JSON.stringify({ disabled })
  7579. });
  7580. if (res.ok) loadBridge();
  7581. } catch (err) {
  7582. showToast('Error', err.message, 'error');
  7583. }
  7584. }
  7585. async function deleteBridgeVLAN(id) {
  7586. if (!confirm('Delete this bridge VLAN entry?')) return;
  7587. try {
  7588. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7589. if (res.ok) {
  7590. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  7591. loadBridge();
  7592. }
  7593. } catch (err) {
  7594. showToast('Error', err.message, 'error');
  7595. }
  7596. }
  7597. // ----------------- Hosts / MAC Table -----------------
  7598. async function loadBridgeHosts() {
  7599. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  7600. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  7601. try {
  7602. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  7603. const res = await fetch(url);
  7604. if (res.ok) {
  7605. state.bridgeHosts = await res.json();
  7606. renderBridgeHosts();
  7607. }
  7608. } catch (err) {
  7609. console.error('Failed to load bridge hosts:', err);
  7610. }
  7611. }
  7612. function renderBridgeHosts() {
  7613. const tbody = document.getElementById('bridge-hosts-table-body');
  7614. const empty = document.getElementById('bridge-empty-hosts');
  7615. const countBadge = document.getElementById('bridge-hosts-count-badge');
  7616. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  7617. if (!tbody) return;
  7618. tbody.innerHTML = '';
  7619. const hosts = (state.bridgeHosts || []).filter(h => {
  7620. if (!search) return true;
  7621. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  7622. });
  7623. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  7624. if (hosts.length === 0) {
  7625. empty?.classList.remove('hidden');
  7626. return;
  7627. }
  7628. empty?.classList.add('hidden');
  7629. hosts.forEach(h => {
  7630. const tr = document.createElement('tr');
  7631. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  7632. let flagBadges = '';
  7633. 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>';
  7634. 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>';
  7635. 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>';
  7636. tr.innerHTML = `
  7637. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  7638. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  7639. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  7640. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  7641. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  7642. <td class="py-2.5 px-3">${flagBadges}</td>
  7643. `;
  7644. tbody.appendChild(tr);
  7645. });
  7646. }
  7647. async function flushBridgeHosts() {
  7648. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  7649. if (!selBridge) {
  7650. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  7651. return;
  7652. }
  7653. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  7654. try {
  7655. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  7656. method: 'POST',
  7657. headers: { 'Content-Type': 'application/json' },
  7658. body: JSON.stringify({ bridge: selBridge })
  7659. });
  7660. if (res.ok) {
  7661. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  7662. loadBridgeHosts();
  7663. }
  7664. } catch (err) {
  7665. showToast('Error', err.message, 'error');
  7666. }
  7667. }
  7668. // ----------------- Helpers -----------------
  7669. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  7670. const sel = document.getElementById(selectId);
  7671. if (!sel) return;
  7672. const prevVal = currentVal || sel.value;
  7673. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  7674. (state.bridges || []).forEach(b => {
  7675. const opt = document.createElement('option');
  7676. opt.value = b.name;
  7677. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  7678. if (b.name === prevVal) opt.selected = true;
  7679. sel.appendChild(opt);
  7680. });
  7681. }
  7682. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  7683. const sel = document.getElementById(selectId);
  7684. if (!sel) return;
  7685. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  7686. // 1. Physical Interfaces
  7687. const grpPhys = document.createElement('optgroup');
  7688. grpPhys.label = 'Physical Interfaces';
  7689. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  7690. const opt = document.createElement('option');
  7691. opt.value = i.name;
  7692. opt.innerText = `${i.name} (${i.role || i.type})`;
  7693. if (i.name === currentVal) opt.selected = true;
  7694. grpPhys.appendChild(opt);
  7695. });
  7696. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  7697. // 2. VLAN Sub-interfaces
  7698. const grpVlans = document.createElement('optgroup');
  7699. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  7700. (state.vlans || []).forEach(v => {
  7701. const opt = document.createElement('option');
  7702. opt.value = v.name;
  7703. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  7704. if (v.name === currentVal) opt.selected = true;
  7705. grpVlans.appendChild(opt);
  7706. });
  7707. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  7708. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  7709. const grpEoip = document.createElement('optgroup');
  7710. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  7711. (state.eoipTunnels || []).forEach(t => {
  7712. const opt = document.createElement('option');
  7713. opt.value = t.name;
  7714. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  7715. if (t.name === currentVal) opt.selected = true;
  7716. grpEoip.appendChild(opt);
  7717. });
  7718. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  7719. }
  7720. // -------------------------------------------------------------
  7721. // Routing Filters Management (/routing filter)
  7722. // -------------------------------------------------------------
  7723. function renderRoutingFilters() {
  7724. const tbody = document.getElementById('routing-filters-table-body');
  7725. if (!tbody) return;
  7726. const empty = document.getElementById('routing-filters-empty');
  7727. const countBadge = document.getElementById('routing-filters-count-badge');
  7728. const navBadge = document.getElementById('badge-filters-count');
  7729. const chainSelect = document.getElementById('routing-filter-chain-select');
  7730. const allRules = state.routingFilters || [];
  7731. if (navBadge) navBadge.innerText = allRules.length;
  7732. // Populate chain filter select options dynamically
  7733. if (chainSelect) {
  7734. const currentVal = state.filterChainSelected || 'all';
  7735. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  7736. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  7737. uniqueChains.map(ch => {
  7738. const count = allRules.filter(r => r.chain === ch).length;
  7739. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  7740. }).join('');
  7741. chainSelect.value = currentVal;
  7742. }
  7743. // Filter rules by selected chain
  7744. const filteredRules = (state.filterChainSelected && state.filterChainSelected !== 'all')
  7745. ? allRules.filter(r => r.chain === state.filterChainSelected)
  7746. : allRules.slice();
  7747. // Sort by chain then rule_order
  7748. filteredRules.sort((a, b) => {
  7749. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  7750. return (a.rule_order || 0) - (b.rule_order || 0);
  7751. });
  7752. if (countBadge) countBadge.innerText = `${filteredRules.length} Rules`;
  7753. if (filteredRules.length === 0) {
  7754. tbody.innerHTML = '';
  7755. if (empty) empty.classList.remove('hidden');
  7756. return;
  7757. }
  7758. if (empty) empty.classList.add('hidden');
  7759. tbody.innerHTML = filteredRules.map(r => {
  7760. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  7761. const flagX = r.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  7762. let actionBadge = '';
  7763. if (r.action === 'accept') {
  7764. 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>';
  7765. } else if (r.action === 'discard') {
  7766. 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>';
  7767. } else if (r.action === 'reject') {
  7768. 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>';
  7769. } else {
  7770. 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>`;
  7771. }
  7772. // Prefix match
  7773. let matchPfx = '';
  7774. if (r.prefix) {
  7775. matchPfx = `<span class="font-bold text-white">${escapeHtml(r.prefix)}</span>`;
  7776. if (r.prefix_len) {
  7777. matchPfx += ` <span class="text-slate-400 text-[11px] font-normal">[${escapeHtml(r.prefix_len)}]</span>`;
  7778. }
  7779. } else {
  7780. matchPfx = '<span class="text-slate-500 italic">any prefix</span>';
  7781. }
  7782. // Other matches
  7783. const matchExtra = [];
  7784. if (r.match_protocol && r.match_protocol !== 'any') {
  7785. 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>`);
  7786. }
  7787. if (r.match_as_path) {
  7788. 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>`);
  7789. }
  7790. if (r.match_community) {
  7791. 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>`);
  7792. }
  7793. const matchExtraHtml = matchExtra.length > 0 ? matchExtra.join(' ') : '<span class="text-slate-600">-</span>';
  7794. // Set modifications
  7795. const setBadges = [];
  7796. if (r.set_local_pref > 0) {
  7797. 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>`);
  7798. }
  7799. if (r.set_metric > 0) {
  7800. 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>`);
  7801. }
  7802. if (r.set_as_prepend > 0) {
  7803. 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>`);
  7804. }
  7805. if (r.set_community) {
  7806. 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>`);
  7807. }
  7808. if (r.set_next_hop) {
  7809. 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>`);
  7810. }
  7811. const setHtml = setBadges.length > 0 ? setBadges.join(' ') : '<span class="text-slate-600">-</span>';
  7812. return `
  7813. <tr class="hover:bg-slate-800/40 transition">
  7814. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagX}</td>
  7815. <td class="py-2.5 px-3 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  7816. <td class="py-2.5 px-3">
  7817. <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>
  7818. </td>
  7819. <td class="py-2.5 px-3">${actionBadge}</td>
  7820. <td class="py-2.5 px-3 font-mono">${matchPfx}</td>
  7821. <td class="py-2.5 px-3 space-x-1">${matchExtraHtml}</td>
  7822. <td class="py-2.5 px-3 space-x-1 font-mono">${setHtml}</td>
  7823. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  7824. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  7825. <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'}">
  7826. ${r.disabled ? 'Enable' : 'Disable'}
  7827. </button>
  7828. <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">
  7829. Edit
  7830. </button>
  7831. <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">
  7832. Delete
  7833. </button>
  7834. </td>
  7835. </tr>
  7836. `;
  7837. }).join('');
  7838. }
  7839. function filterRoutingFiltersByChain(chain) {
  7840. state.filterChainSelected = chain;
  7841. renderRoutingFilters();
  7842. }
  7843. function openAddRoutingFilterModal(defaultChain = '') {
  7844. const form = document.getElementById('routing-filter-form');
  7845. if (form) form.reset();
  7846. const idEl = document.getElementById('modal-rf-id');
  7847. if (idEl) idEl.value = '';
  7848. const titleEl = document.getElementById('modal-rf-title');
  7849. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  7850. const chainEl = document.getElementById('modal-rf-chain');
  7851. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  7852. const orderEl = document.getElementById('modal-rf-order');
  7853. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  7854. const actEl = document.getElementById('modal-rf-action');
  7855. if (actEl) actEl.value = 'accept';
  7856. const protoEl = document.getElementById('modal-rf-protocol');
  7857. if (protoEl) protoEl.value = 'any';
  7858. const disEl = document.getElementById('modal-rf-disabled');
  7859. if (disEl) disEl.checked = false;
  7860. const modal = document.getElementById('modal-routing-filter');
  7861. if (modal) modal.classList.remove('hidden');
  7862. }
  7863. function openEditRoutingFilterModal(id) {
  7864. const r = (state.routingFilters || []).find(item => item.id === id);
  7865. if (!r) return;
  7866. const idEl = document.getElementById('modal-rf-id');
  7867. if (idEl) idEl.value = r.id;
  7868. const titleEl = document.getElementById('modal-rf-title');
  7869. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  7870. const chainEl = document.getElementById('modal-rf-chain');
  7871. if (chainEl) chainEl.value = r.chain || '';
  7872. const orderEl = document.getElementById('modal-rf-order');
  7873. if (orderEl) orderEl.value = r.rule_order || 10;
  7874. const actEl = document.getElementById('modal-rf-action');
  7875. if (actEl) actEl.value = r.action || 'accept';
  7876. const pfxEl = document.getElementById('modal-rf-prefix');
  7877. if (pfxEl) pfxEl.value = r.prefix || '';
  7878. const pfxLenEl = document.getElementById('modal-rf-prefix-len');
  7879. if (pfxLenEl) pfxLenEl.value = r.prefix_len || '';
  7880. const protoEl = document.getElementById('modal-rf-protocol');
  7881. if (protoEl) protoEl.value = r.match_protocol || 'any';
  7882. const aspEl = document.getElementById('modal-rf-as-path');
  7883. if (aspEl) aspEl.value = r.match_as_path || '';
  7884. const commEl = document.getElementById('modal-rf-community');
  7885. if (commEl) commEl.value = r.match_community || '';
  7886. const lpEl = document.getElementById('modal-rf-set-local-pref');
  7887. if (lpEl) lpEl.value = r.set_local_pref || '';
  7888. const metEl = document.getElementById('modal-rf-set-metric');
  7889. if (metEl) metEl.value = r.set_metric || '';
  7890. const prepEl = document.getElementById('modal-rf-set-as-prepend');
  7891. if (prepEl) prepEl.value = r.set_as_prepend || '';
  7892. const setCommEl = document.getElementById('modal-rf-set-community');
  7893. if (setCommEl) setCommEl.value = r.set_community || '';
  7894. const nhEl = document.getElementById('modal-rf-set-next-hop');
  7895. if (nhEl) nhEl.value = r.set_next_hop || '';
  7896. const comEl = document.getElementById('modal-rf-comment');
  7897. if (comEl) comEl.value = r.comment || '';
  7898. const disEl = document.getElementById('modal-rf-disabled');
  7899. if (disEl) disEl.checked = !!r.disabled;
  7900. const modal = document.getElementById('modal-routing-filter');
  7901. if (modal) modal.classList.remove('hidden');
  7902. }
  7903. function closeRoutingFilterModal() {
  7904. const modal = document.getElementById('modal-routing-filter');
  7905. if (modal) modal.classList.add('hidden');
  7906. }
  7907. async function submitRoutingFilter(e) {
  7908. e.preventDefault();
  7909. const payload = {
  7910. id: document.getElementById('modal-rf-id').value,
  7911. chain: document.getElementById('modal-rf-chain').value.trim(),
  7912. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  7913. action: document.getElementById('modal-rf-action').value,
  7914. prefix: document.getElementById('modal-rf-prefix').value.trim(),
  7915. prefix_len: document.getElementById('modal-rf-prefix-len').value.trim(),
  7916. match_protocol: document.getElementById('modal-rf-protocol').value,
  7917. match_as_path: document.getElementById('modal-rf-as-path').value.trim(),
  7918. match_community: document.getElementById('modal-rf-community').value.trim(),
  7919. set_local_pref: parseInt(document.getElementById('modal-rf-set-local-pref').value, 10) || 0,
  7920. set_metric: parseInt(document.getElementById('modal-rf-set-metric').value, 10) || 0,
  7921. set_as_prepend: parseInt(document.getElementById('modal-rf-set-as-prepend').value, 10) || 0,
  7922. set_community: document.getElementById('modal-rf-set-community').value.trim(),
  7923. set_next_hop: document.getElementById('modal-rf-set-next-hop').value.trim(),
  7924. comment: document.getElementById('modal-rf-comment').value.trim(),
  7925. disabled: document.getElementById('modal-rf-disabled').checked
  7926. };
  7927. try {
  7928. const res = await fetch(`${API_BASE}/routing/filters`, {
  7929. method: 'POST',
  7930. headers: { 'Content-Type': 'application/json' },
  7931. body: JSON.stringify(payload)
  7932. });
  7933. if (res.ok) {
  7934. closeRoutingFilterModal();
  7935. showToast('Success', 'Routing filter rule saved', 'success');
  7936. loadDynamicRouting();
  7937. } else {
  7938. const err = await res.json();
  7939. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  7940. }
  7941. } catch (err) {
  7942. showToast('Error', err.message, 'error');
  7943. }
  7944. }
  7945. async function deleteRoutingFilter(id) {
  7946. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  7947. try {
  7948. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7949. if (res.ok) {
  7950. showToast('Deleted', 'Routing filter rule removed', 'info');
  7951. loadDynamicRouting();
  7952. } else {
  7953. const err = await res.json();
  7954. showToast('Error', err.error || 'Failed to delete rule', 'error');
  7955. }
  7956. } catch (err) {
  7957. showToast('Error', err.message, 'error');
  7958. }
  7959. }
  7960. async function toggleRoutingFilterState(id, disabled) {
  7961. try {
  7962. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  7963. method: 'POST',
  7964. headers: { 'Content-Type': 'application/json' },
  7965. body: JSON.stringify({ disabled })
  7966. });
  7967. if (res.ok) {
  7968. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  7969. loadDynamicRouting();
  7970. } else {
  7971. const err = await res.json();
  7972. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  7973. }
  7974. } catch (err) {
  7975. showToast('Error', err.message, 'error');
  7976. }
  7977. }
  7978. // ==========================================
  7979. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  7980. // ==========================================
  7981. function loadToolsView() {
  7982. populateToolsInterfaces();
  7983. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  7984. }
  7985. function populateToolsInterfaces() {
  7986. const pingSel = document.getElementById('tools-ping-iface');
  7987. const traceSel = document.getElementById('tools-tr-iface');
  7988. let opts = '<option value="">Auto (Default Route)</option>';
  7989. if (Array.isArray(state.interfaces)) {
  7990. state.interfaces.forEach(iface => {
  7991. if (iface.name) {
  7992. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  7993. }
  7994. });
  7995. }
  7996. if (pingSel) {
  7997. const cur = pingSel.value;
  7998. pingSel.innerHTML = opts;
  7999. if (cur) pingSel.value = cur;
  8000. }
  8001. if (traceSel) {
  8002. const cur = traceSel.value;
  8003. traceSel.innerHTML = opts;
  8004. if (cur) traceSel.value = cur;
  8005. }
  8006. }
  8007. function switchToolsSubTab(subTab) {
  8008. state.activeToolsSubTab = subTab;
  8009. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  8010. tabs.forEach(t => {
  8011. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  8012. const view = document.getElementById(`tools-view-${t}`);
  8013. if (btn) {
  8014. if (t === subTab) {
  8015. 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';
  8016. } else {
  8017. 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';
  8018. }
  8019. }
  8020. if (view) {
  8021. if (t === subTab) {
  8022. view.classList.remove('hidden');
  8023. } else {
  8024. view.classList.add('hidden');
  8025. }
  8026. }
  8027. });
  8028. }
  8029. function setPortPreset(port) {
  8030. const input = document.getElementById('tools-port-num');
  8031. if (input) input.value = port;
  8032. }
  8033. let pingAbortController = null;
  8034. let tracerouteAbortController = null;
  8035. function clearPingTable() {
  8036. const tbody = document.getElementById('tools-ping-tbody');
  8037. if (tbody) tbody.innerHTML = '';
  8038. const rawEl = document.getElementById('tools-ping-raw');
  8039. if (rawEl) rawEl.innerText = '';
  8040. const sentEl = document.getElementById('tools-ping-stat-sent');
  8041. if (sentEl) sentEl.innerText = '0';
  8042. const recvEl = document.getElementById('tools-ping-stat-recv');
  8043. if (recvEl) recvEl.innerText = '0';
  8044. const lossEl = document.getElementById('tools-ping-stat-loss');
  8045. if (lossEl) lossEl.innerText = '0%';
  8046. const avgEl = document.getElementById('tools-ping-stat-avg');
  8047. if (avgEl) avgEl.innerText = '0 ms';
  8048. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  8049. if (minMaxEl) minMaxEl.innerText = '-';
  8050. const badge = document.getElementById('tools-ping-status-badge');
  8051. if (badge) {
  8052. badge.className = '';
  8053. badge.innerText = '';
  8054. }
  8055. }
  8056. function clearTracerouteTable() {
  8057. const tbody = document.getElementById('tools-tr-tbody');
  8058. if (tbody) tbody.innerHTML = '';
  8059. const rawEl = document.getElementById('tools-tr-raw');
  8060. if (rawEl) rawEl.innerText = '';
  8061. const statHops = document.getElementById('tools-tr-hops-count');
  8062. if (statHops) statHops.innerText = '0 Hops';
  8063. }
  8064. function resetPingButton() {
  8065. const btn = document.getElementById('tools-ping-btn');
  8066. const btnText = document.getElementById('tools-ping-btn-text');
  8067. const spinner = document.getElementById('tools-ping-spinner');
  8068. if (btn) {
  8069. btn.disabled = false;
  8070. 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';
  8071. }
  8072. if (btnText) btnText.innerText = 'Start Ping';
  8073. if (spinner) spinner.classList.add('hidden');
  8074. }
  8075. function setPingRunningButton() {
  8076. const btn = document.getElementById('tools-ping-btn');
  8077. const btnText = document.getElementById('tools-ping-btn-text');
  8078. const spinner = document.getElementById('tools-ping-spinner');
  8079. if (btn) {
  8080. btn.disabled = false;
  8081. 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';
  8082. }
  8083. if (btnText) btnText.innerText = 'Stop Ping';
  8084. if (spinner) spinner.classList.remove('hidden');
  8085. }
  8086. function resetTracerouteButton() {
  8087. const btn = document.getElementById('tools-tr-btn');
  8088. const btnText = document.getElementById('tools-tr-btn-text');
  8089. const spinner = document.getElementById('tools-tr-spinner');
  8090. if (btn) {
  8091. btn.disabled = false;
  8092. 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';
  8093. }
  8094. if (btnText) btnText.innerText = 'Start Traceroute';
  8095. if (spinner) spinner.classList.add('hidden');
  8096. }
  8097. function setTracerouteRunningButton() {
  8098. const btn = document.getElementById('tools-tr-btn');
  8099. const btnText = document.getElementById('tools-tr-btn-text');
  8100. const spinner = document.getElementById('tools-tr-spinner');
  8101. if (btn) {
  8102. btn.disabled = false;
  8103. 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';
  8104. }
  8105. if (btnText) btnText.innerText = 'Stop Traceroute';
  8106. if (spinner) spinner.classList.remove('hidden');
  8107. }
  8108. async function executePing(e) {
  8109. if (e) e.preventDefault();
  8110. // If already running, clicking the button stops the stream!
  8111. if (pingAbortController) {
  8112. pingAbortController.abort();
  8113. pingAbortController = null;
  8114. resetPingButton();
  8115. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  8116. return;
  8117. }
  8118. const target = document.getElementById('tools-ping-target')?.value?.trim();
  8119. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  8120. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  8121. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  8122. const iface = document.getElementById('tools-ping-iface')?.value || '';
  8123. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  8124. if (!target) {
  8125. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  8126. return;
  8127. }
  8128. clearPingTable();
  8129. const resCard = document.getElementById('tools-ping-results');
  8130. if (resCard) resCard.classList.remove('hidden');
  8131. pingAbortController = new AbortController();
  8132. setPingRunningButton();
  8133. try {
  8134. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  8135. method: 'POST',
  8136. headers: { 'Content-Type': 'application/json' },
  8137. body: JSON.stringify({
  8138. target,
  8139. count,
  8140. size,
  8141. timeout,
  8142. interface: iface,
  8143. dont_frag: dontFrag
  8144. }),
  8145. signal: pingAbortController.signal
  8146. });
  8147. if (!res.ok) {
  8148. const errText = await res.text();
  8149. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  8150. resetPingButton();
  8151. pingAbortController = null;
  8152. return;
  8153. }
  8154. const reader = res.body.getReader();
  8155. const decoder = new TextDecoder('utf-8');
  8156. let buffer = '';
  8157. while (true) {
  8158. const { done, value } = await reader.read();
  8159. if (done) break;
  8160. buffer += decoder.decode(value, { stream: true });
  8161. const blocks = buffer.split('\n\n');
  8162. buffer = blocks.pop() || '';
  8163. for (const block of blocks) {
  8164. const trimmed = block.trim();
  8165. if (!trimmed) continue;
  8166. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  8167. try {
  8168. const evt = JSON.parse(line);
  8169. handleLivePingEvent(evt);
  8170. } catch (parseErr) {
  8171. console.warn('Ping SSE parse error:', parseErr, line);
  8172. }
  8173. }
  8174. }
  8175. } catch (err) {
  8176. if (err.name === 'AbortError') {
  8177. // User aborted normally
  8178. } else {
  8179. showToast('Ping Error', err.message, 'error');
  8180. }
  8181. } finally {
  8182. pingAbortController = null;
  8183. resetPingButton();
  8184. }
  8185. }
  8186. function handleLivePingEvent(evt) {
  8187. const sentEl = document.getElementById('tools-ping-stat-sent');
  8188. const recvEl = document.getElementById('tools-ping-stat-recv');
  8189. const lossEl = document.getElementById('tools-ping-stat-loss');
  8190. const avgEl = document.getElementById('tools-ping-stat-avg');
  8191. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  8192. const badge = document.getElementById('tools-ping-status-badge');
  8193. const tbody = document.getElementById('tools-ping-tbody');
  8194. const rawEl = document.getElementById('tools-ping-raw');
  8195. if (evt.raw && rawEl) {
  8196. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  8197. rawEl.scrollTop = rawEl.scrollHeight;
  8198. }
  8199. if (evt.type === 'reply') {
  8200. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  8201. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  8202. if (lossEl && evt.packet_loss_pct !== undefined) {
  8203. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  8204. lossEl.className = evt.packet_loss_pct === 0
  8205. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  8206. : (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');
  8207. }
  8208. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  8209. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  8210. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  8211. }
  8212. if (badge) {
  8213. if (evt.packet_loss_pct === 0) {
  8214. 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';
  8215. badge.innerText = '100% OK';
  8216. } else {
  8217. 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';
  8218. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  8219. }
  8220. }
  8221. if (tbody) {
  8222. const tr = document.createElement('tr');
  8223. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  8224. tr.innerHTML = `
  8225. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  8226. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  8227. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  8228. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  8229. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  8230. <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>
  8231. `;
  8232. tbody.appendChild(tr);
  8233. }
  8234. } else if (evt.type === 'timeout') {
  8235. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  8236. if (lossEl && evt.packet_loss_pct !== undefined) {
  8237. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  8238. 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';
  8239. }
  8240. if (badge) {
  8241. 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';
  8242. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  8243. }
  8244. if (tbody) {
  8245. const tr = document.createElement('tr');
  8246. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  8247. tr.innerHTML = `
  8248. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  8249. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  8250. <td class="py-2 px-3 text-slate-600">--</td>
  8251. <td class="py-2 px-3 text-slate-600">--</td>
  8252. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  8253. <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>
  8254. `;
  8255. tbody.appendChild(tr);
  8256. }
  8257. } else if (evt.type === 'unreach') {
  8258. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  8259. if (lossEl && evt.packet_loss_pct !== undefined) {
  8260. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  8261. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  8262. }
  8263. if (badge) {
  8264. 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';
  8265. badge.innerText = 'UNREACHABLE';
  8266. }
  8267. if (tbody) {
  8268. const tr = document.createElement('tr');
  8269. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  8270. tr.innerHTML = `
  8271. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  8272. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  8273. <td class="py-2 px-3 text-slate-600">--</td>
  8274. <td class="py-2 px-3 text-slate-600">--</td>
  8275. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  8276. <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>
  8277. `;
  8278. tbody.appendChild(tr);
  8279. }
  8280. } else if (evt.type === 'stats') {
  8281. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  8282. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  8283. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  8284. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  8285. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  8286. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  8287. }
  8288. } else if (evt.type === 'done') {
  8289. 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');
  8290. }
  8291. }
  8292. async function executeTraceroute(e) {
  8293. if (e) e.preventDefault();
  8294. if (tracerouteAbortController) {
  8295. tracerouteAbortController.abort();
  8296. tracerouteAbortController = null;
  8297. resetTracerouteButton();
  8298. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  8299. return;
  8300. }
  8301. const target = document.getElementById('tools-tr-target')?.value?.trim();
  8302. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  8303. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  8304. const iface = document.getElementById('tools-tr-iface')?.value || '';
  8305. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  8306. if (!target) {
  8307. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  8308. return;
  8309. }
  8310. clearTracerouteTable();
  8311. const resCard = document.getElementById('tools-tr-results');
  8312. if (resCard) resCard.classList.remove('hidden');
  8313. tracerouteAbortController = new AbortController();
  8314. setTracerouteRunningButton();
  8315. try {
  8316. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  8317. method: 'POST',
  8318. headers: { 'Content-Type': 'application/json' },
  8319. body: JSON.stringify({
  8320. target,
  8321. max_hops: maxHops,
  8322. protocol,
  8323. interface: iface,
  8324. resolve
  8325. }),
  8326. signal: tracerouteAbortController.signal
  8327. });
  8328. if (!res.ok) {
  8329. const errText = await res.text();
  8330. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  8331. resetTracerouteButton();
  8332. tracerouteAbortController = null;
  8333. return;
  8334. }
  8335. const reader = res.body.getReader();
  8336. const decoder = new TextDecoder('utf-8');
  8337. let buffer = '';
  8338. while (true) {
  8339. const { done, value } = await reader.read();
  8340. if (done) break;
  8341. buffer += decoder.decode(value, { stream: true });
  8342. const blocks = buffer.split('\n\n');
  8343. buffer = blocks.pop() || '';
  8344. for (const block of blocks) {
  8345. const trimmed = block.trim();
  8346. if (!trimmed) continue;
  8347. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  8348. try {
  8349. const evt = JSON.parse(line);
  8350. handleLiveTracerouteEvent(evt);
  8351. } catch (parseErr) {
  8352. console.warn('Traceroute SSE parse error:', parseErr, line);
  8353. }
  8354. }
  8355. }
  8356. } catch (err) {
  8357. if (err.name === 'AbortError') {
  8358. // User aborted normally
  8359. } else {
  8360. showToast('Traceroute Error', err.message, 'error');
  8361. }
  8362. } finally {
  8363. tracerouteAbortController = null;
  8364. resetTracerouteButton();
  8365. }
  8366. }
  8367. function handleLiveTracerouteEvent(evt) {
  8368. const statHops = document.getElementById('tools-tr-hops-count');
  8369. const tbody = document.getElementById('tools-tr-tbody');
  8370. const rawEl = document.getElementById('tools-tr-raw');
  8371. if (evt.raw && rawEl) {
  8372. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  8373. rawEl.scrollTop = rawEl.scrollHeight;
  8374. }
  8375. if (evt.hops_count !== undefined && statHops) {
  8376. statHops.innerText = `${evt.hops_count} Hops`;
  8377. }
  8378. if (evt.type === 'hop' && evt.hop && tbody) {
  8379. const h = evt.hop;
  8380. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  8381. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  8382. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  8383. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  8384. const tr = document.createElement('tr');
  8385. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  8386. tr.innerHTML = `
  8387. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  8388. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  8389. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  8390. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  8391. <td class="py-2.5 px-3 text-right">
  8392. ${isTimeout
  8393. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  8394. : '<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>'}
  8395. </td>
  8396. `;
  8397. tbody.appendChild(tr);
  8398. } else if (evt.type === 'done') {
  8399. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  8400. }
  8401. }
  8402. async function executeMTR(e) {
  8403. if (e) e.preventDefault();
  8404. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  8405. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  8406. if (!target) {
  8407. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  8408. return;
  8409. }
  8410. const btn = document.getElementById('tools-mtr-btn');
  8411. const spinner = document.getElementById('tools-mtr-spinner');
  8412. if (btn) btn.disabled = true;
  8413. if (spinner) spinner.classList.remove('hidden');
  8414. try {
  8415. const res = await fetch(`${API_BASE}/tools/mtr`, {
  8416. method: 'POST',
  8417. headers: { 'Content-Type': 'application/json' },
  8418. body: JSON.stringify({ target, count: cycles })
  8419. });
  8420. const data = await res.json();
  8421. if (!res.ok) {
  8422. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  8423. return;
  8424. }
  8425. const resCard = document.getElementById('tools-mtr-results');
  8426. if (resCard) resCard.classList.remove('hidden');
  8427. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  8428. const statHops = document.getElementById('tools-mtr-hops-count');
  8429. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  8430. const tbody = document.getElementById('tools-mtr-tbody');
  8431. if (tbody) {
  8432. if (hopsCount > 0) {
  8433. tbody.innerHTML = data.hops.map(h => {
  8434. 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');
  8435. return `
  8436. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  8437. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  8438. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  8439. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  8440. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  8441. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  8442. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  8443. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  8444. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  8445. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  8446. </tr>
  8447. `;
  8448. }).join('');
  8449. } else {
  8450. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  8451. }
  8452. }
  8453. const rawEl = document.getElementById('tools-mtr-raw');
  8454. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  8455. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  8456. } catch (err) {
  8457. showToast('MTR Error', err.message, 'error');
  8458. } finally {
  8459. if (btn) btn.disabled = false;
  8460. if (spinner) spinner.classList.add('hidden');
  8461. }
  8462. }
  8463. async function executeDNS(e) {
  8464. if (e) e.preventDefault();
  8465. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  8466. const type = document.getElementById('tools-dns-type')?.value || 'A';
  8467. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  8468. if (!domain) {
  8469. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  8470. return;
  8471. }
  8472. const btn = document.getElementById('tools-dns-btn');
  8473. const spinner = document.getElementById('tools-dns-spinner');
  8474. if (btn) btn.disabled = true;
  8475. if (spinner) spinner.classList.remove('hidden');
  8476. try {
  8477. const res = await fetch(`${API_BASE}/tools/dns`, {
  8478. method: 'POST',
  8479. headers: { 'Content-Type': 'application/json' },
  8480. body: JSON.stringify({ domain, type, server })
  8481. });
  8482. const data = await res.json();
  8483. if (!res.ok) {
  8484. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  8485. return;
  8486. }
  8487. const resCard = document.getElementById('tools-dns-results');
  8488. if (resCard) resCard.classList.remove('hidden');
  8489. const metaEl = document.getElementById('tools-dns-meta');
  8490. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  8491. const tbody = document.getElementById('tools-dns-tbody');
  8492. if (tbody) {
  8493. if (Array.isArray(data.records) && data.records.length > 0) {
  8494. tbody.innerHTML = data.records.map(r => `
  8495. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  8496. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  8497. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  8498. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  8499. <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>
  8500. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  8501. </tr>
  8502. `).join('');
  8503. } else {
  8504. 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>`;
  8505. }
  8506. }
  8507. const rawEl = document.getElementById('tools-dns-raw');
  8508. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  8509. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  8510. } catch (err) {
  8511. showToast('DNS Error', err.message, 'error');
  8512. } finally {
  8513. if (btn) btn.disabled = false;
  8514. if (spinner) spinner.classList.add('hidden');
  8515. }
  8516. }
  8517. async function executePortProbe(e) {
  8518. if (e) e.preventDefault();
  8519. const target = document.getElementById('tools-port-target')?.value?.trim();
  8520. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  8521. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  8522. if (!target || !port) {
  8523. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  8524. return;
  8525. }
  8526. const btn = document.getElementById('tools-port-btn');
  8527. const spinner = document.getElementById('tools-port-spinner');
  8528. if (btn) btn.disabled = true;
  8529. if (spinner) spinner.classList.remove('hidden');
  8530. try {
  8531. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  8532. method: 'POST',
  8533. headers: { 'Content-Type': 'application/json' },
  8534. body: JSON.stringify({ target, port, timeout })
  8535. });
  8536. const data = await res.json();
  8537. if (!res.ok) {
  8538. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  8539. return;
  8540. }
  8541. const resCard = document.getElementById('tools-port-results');
  8542. if (resCard) resCard.classList.remove('hidden');
  8543. const banner = document.getElementById('tools-port-banner');
  8544. const icon = document.getElementById('tools-port-icon');
  8545. const title = document.getElementById('tools-port-title');
  8546. const sub = document.getElementById('tools-port-sub');
  8547. const latency = document.getElementById('tools-port-latency');
  8548. if (data.open) {
  8549. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  8550. if (icon) {
  8551. 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';
  8552. icon.innerText = '✓';
  8553. }
  8554. if (title) {
  8555. title.className = 'text-sm font-bold text-emerald-300';
  8556. title.innerText = `PORT ${port} OPEN / LISTENING`;
  8557. }
  8558. if (sub) {
  8559. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  8560. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  8561. }
  8562. if (latency) {
  8563. latency.className = 'text-base font-bold font-mono text-emerald-300';
  8564. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  8565. }
  8566. } else {
  8567. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  8568. if (icon) {
  8569. 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';
  8570. icon.innerText = '✕';
  8571. }
  8572. if (title) {
  8573. title.className = 'text-sm font-bold text-rose-300';
  8574. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  8575. }
  8576. if (sub) {
  8577. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  8578. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  8579. }
  8580. if (latency) {
  8581. latency.className = 'text-base font-bold font-mono text-slate-500';
  8582. latency.innerText = '--';
  8583. }
  8584. }
  8585. const rawEl = document.getElementById('tools-port-raw');
  8586. 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'}`);
  8587. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  8588. } catch (err) {
  8589. showToast('Probe Error', err.message, 'error');
  8590. } finally {
  8591. if (btn) btn.disabled = false;
  8592. if (spinner) spinner.classList.add('hidden');
  8593. }
  8594. }
  8595. // ==========================================
  8596. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  8597. // ==========================================
  8598. async function loadDHCPClients(showToastMsg = false) {
  8599. try {
  8600. const [clientsRes, sumRes] = await Promise.all([
  8601. fetch(`${API_BASE}/dhcp/clients`),
  8602. fetch(`${API_BASE}/dhcp/clients/summary`)
  8603. ]);
  8604. if (clientsRes.ok) {
  8605. state.dhcpClients = await clientsRes.json();
  8606. }
  8607. if (sumRes.ok) {
  8608. state.dhcpSummary = await sumRes.json();
  8609. }
  8610. renderDHCPClients();
  8611. updateDHCPSummaryCards();
  8612. const bDhcp = document.getElementById('badge-dhcp-client-count');
  8613. if (bDhcp && state.dhcpSummary) {
  8614. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  8615. }
  8616. if (showToastMsg) {
  8617. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  8618. }
  8619. } catch (err) {
  8620. console.error('Failed to load DHCP clients:', err);
  8621. if (showToastMsg) {
  8622. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  8623. }
  8624. }
  8625. }
  8626. function updateDHCPSummaryCards() {
  8627. const sum = state.dhcpSummary || {
  8628. total_clients: (state.dhcpClients || []).length,
  8629. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  8630. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  8631. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  8632. };
  8633. const totalEl = document.getElementById('dhcp-stat-total');
  8634. const boundEl = document.getElementById('dhcp-stat-bound');
  8635. const searchEl = document.getElementById('dhcp-stat-searching');
  8636. const disEl = document.getElementById('dhcp-stat-disabled');
  8637. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  8638. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  8639. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  8640. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  8641. }
  8642. function renderDHCPClients() {
  8643. const tbody = document.getElementById('dhcp-clients-tbody');
  8644. const emptyState = document.getElementById('dhcp-clients-empty');
  8645. if (!tbody) return;
  8646. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  8647. if (clients.length === 0) {
  8648. tbody.innerHTML = '';
  8649. if (emptyState) emptyState.classList.remove('hidden');
  8650. return;
  8651. }
  8652. if (emptyState) emptyState.classList.add('hidden');
  8653. tbody.innerHTML = clients.map(c => {
  8654. let statusBadge = '';
  8655. if (!c.enabled) {
  8656. 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>';
  8657. } else if (c.status === 'bound') {
  8658. 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>';
  8659. } else if (c.status === 'searching') {
  8660. 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>';
  8661. } else if (c.status === 'stopped') {
  8662. 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>';
  8663. } else {
  8664. 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>`;
  8665. }
  8666. 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>';
  8667. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  8668. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  8669. 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>';
  8670. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  8671. // Option flags
  8672. const flags = [];
  8673. 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>');
  8674. 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>');
  8675. 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>');
  8676. 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>`);
  8677. return `
  8678. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  8679. <td class="py-3 px-4">
  8680. <div class="flex items-center gap-2">
  8681. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  8682. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  8683. </div>
  8684. </td>
  8685. <td class="py-3 px-4">${statusBadge}</td>
  8686. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  8687. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  8688. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  8689. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  8690. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  8691. <td class="py-3 px-4">
  8692. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  8693. </td>
  8694. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  8695. ${c.enabled ? `
  8696. <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>
  8697. <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>
  8698. <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>
  8699. ` : `
  8700. <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>
  8701. `}
  8702. <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>
  8703. <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>
  8704. </td>
  8705. </tr>
  8706. `;
  8707. }).join('');
  8708. }
  8709. function openDHCPClientModal(clientId = null) {
  8710. const modal = document.getElementById('modal-dhcp-client');
  8711. if (!modal) return;
  8712. const title = document.getElementById('modal-dhcp-title');
  8713. const idInput = document.getElementById('modal-dhcp-id');
  8714. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  8715. const distInput = document.getElementById('modal-dhcp-distance');
  8716. const commentInput = document.getElementById('modal-dhcp-comment');
  8717. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  8718. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  8719. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  8720. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  8721. // Populate interfaces
  8722. if (ifaceSelect) {
  8723. let opts = '<option value="">Select interface...</option>';
  8724. const allIfaces = state.interfaces || [];
  8725. const allVlans = state.vlans || [];
  8726. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  8727. // Group 1: Physical & Bridge Interfaces
  8728. opts += '<optgroup label="Physical & Bridge Interfaces">';
  8729. allIfaces.forEach(i => {
  8730. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  8731. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  8732. });
  8733. opts += '</optgroup>';
  8734. // Group 2: VLAN Interfaces
  8735. if (allVlans.length > 0) {
  8736. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  8737. allVlans.forEach(v => {
  8738. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  8739. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  8740. });
  8741. opts += '</optgroup>';
  8742. }
  8743. ifaceSelect.innerHTML = opts;
  8744. }
  8745. if (clientId) {
  8746. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  8747. if (client) {
  8748. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  8749. if (idInput) idInput.value = client.id;
  8750. if (ifaceSelect) {
  8751. ifaceSelect.value = client.interface;
  8752. ifaceSelect.disabled = true; // interface cannot be changed on edit
  8753. }
  8754. if (distInput) distInput.value = client.default_route_distance || 1;
  8755. if (commentInput) commentInput.value = client.comment || '';
  8756. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  8757. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  8758. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  8759. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  8760. }
  8761. } else {
  8762. if (title) title.innerText = 'Add DHCP Client';
  8763. if (idInput) idInput.value = '';
  8764. if (ifaceSelect) {
  8765. ifaceSelect.value = '';
  8766. ifaceSelect.disabled = false;
  8767. }
  8768. if (distInput) distInput.value = 1;
  8769. if (commentInput) commentInput.value = '';
  8770. if (defRouteCheck) defRouteCheck.checked = true;
  8771. if (peerDnsCheck) peerDnsCheck.checked = true;
  8772. if (peerNtpCheck) peerNtpCheck.checked = true;
  8773. if (enabledCheck) enabledCheck.checked = true;
  8774. }
  8775. modal.classList.remove('hidden');
  8776. }
  8777. function openDHCPClientModalForIface(ifaceName) {
  8778. openDHCPClientModal();
  8779. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  8780. if (ifaceSelect && ifaceName) {
  8781. ifaceSelect.value = ifaceName;
  8782. }
  8783. }
  8784. function closeDHCPClientModal() {
  8785. const modal = document.getElementById('modal-dhcp-client');
  8786. if (modal) modal.classList.add('hidden');
  8787. }
  8788. async function submitSaveDHCPClient(e) {
  8789. if (e) e.preventDefault();
  8790. const id = document.getElementById('modal-dhcp-id')?.value;
  8791. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  8792. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  8793. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  8794. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  8795. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  8796. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  8797. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  8798. if (!id && !iface) {
  8799. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  8800. return;
  8801. }
  8802. try {
  8803. let res;
  8804. if (id) {
  8805. // PUT update
  8806. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  8807. method: 'PUT',
  8808. headers: { 'Content-Type': 'application/json' },
  8809. body: JSON.stringify({
  8810. enabled,
  8811. add_default_route: defRoute,
  8812. default_route_distance: distance,
  8813. use_peer_dns: peerDns,
  8814. use_peer_ntp: peerNtp,
  8815. comment
  8816. })
  8817. });
  8818. } else {
  8819. // POST create
  8820. res = await fetch(`${API_BASE}/dhcp/clients`, {
  8821. method: 'POST',
  8822. headers: { 'Content-Type': 'application/json' },
  8823. body: JSON.stringify({
  8824. interface: iface,
  8825. enabled,
  8826. add_default_route: defRoute,
  8827. default_route_distance: distance,
  8828. use_peer_dns: peerDns,
  8829. use_peer_ntp: peerNtp,
  8830. comment
  8831. })
  8832. });
  8833. }
  8834. const data = await res.json();
  8835. if (!res.ok) {
  8836. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  8837. return;
  8838. }
  8839. closeDHCPClientModal();
  8840. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  8841. await loadDHCPClients();
  8842. fetchData(); // refresh interfaces list with new lease/status
  8843. } catch (err) {
  8844. showToast('Error', err.message, 'error');
  8845. }
  8846. }
  8847. async function toggleDHCPClientState(id, enabled) {
  8848. try {
  8849. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  8850. method: 'POST',
  8851. headers: { 'Content-Type': 'application/json' },
  8852. body: JSON.stringify({ enabled })
  8853. });
  8854. const data = await res.json();
  8855. if (!res.ok) {
  8856. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  8857. return;
  8858. }
  8859. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  8860. await loadDHCPClients();
  8861. fetchData();
  8862. } catch (err) {
  8863. showToast('Error', err.message, 'error');
  8864. }
  8865. }
  8866. async function renewDHCPClient(id) {
  8867. try {
  8868. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  8869. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  8870. method: 'POST'
  8871. });
  8872. const data = await res.json();
  8873. if (!res.ok) {
  8874. showToast('Error', data.error || 'Failed to renew lease', 'error');
  8875. return;
  8876. }
  8877. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  8878. setTimeout(() => {
  8879. loadDHCPClients();
  8880. fetchData();
  8881. }, 1500);
  8882. } catch (err) {
  8883. showToast('Error', err.message, 'error');
  8884. }
  8885. }
  8886. async function releaseDHCPClient(id) {
  8887. try {
  8888. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  8889. method: 'POST'
  8890. });
  8891. const data = await res.json();
  8892. if (!res.ok) {
  8893. showToast('Error', data.error || 'Failed to release lease', 'error');
  8894. return;
  8895. }
  8896. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  8897. await loadDHCPClients();
  8898. fetchData();
  8899. } catch (err) {
  8900. showToast('Error', err.message, 'error');
  8901. }
  8902. }
  8903. async function deleteDHCPClient(id, ifaceName) {
  8904. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  8905. return;
  8906. }
  8907. try {
  8908. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  8909. method: 'DELETE'
  8910. });
  8911. const data = await res.json();
  8912. if (!res.ok) {
  8913. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  8914. return;
  8915. }
  8916. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  8917. await loadDHCPClients();
  8918. fetchData();
  8919. } catch (err) {
  8920. showToast('Error', err.message, 'error');
  8921. }
  8922. }
  8923. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  8924. function initTableSorting() {
  8925. document.querySelectorAll('table').forEach(setupSortableTable);
  8926. }
  8927. function setupSortableTable(table) {
  8928. const thead = table.querySelector('thead');
  8929. const tbody = table.querySelector('tbody');
  8930. if (!thead || !tbody) return;
  8931. const headerRows = thead.querySelectorAll('tr');
  8932. if (headerRows.length === 0) return;
  8933. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  8934. ths.forEach((th, colIdx) => {
  8935. if (th._sortBound) return;
  8936. th._sortBound = true;
  8937. const rawText = th.innerText.trim().toLowerCase();
  8938. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  8939. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  8940. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  8941. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  8942. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  8943. return;
  8944. }
  8945. th.classList.add('table-sortable', 'group');
  8946. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  8947. let icon = th.querySelector('.table-sort-icon');
  8948. if (!icon) {
  8949. icon = document.createElement('span');
  8950. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  8951. icon.innerHTML = '⇅';
  8952. th.appendChild(icon);
  8953. }
  8954. th.addEventListener('click', (e) => {
  8955. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  8956. handleHeaderClick(table, th, colIdx);
  8957. });
  8958. });
  8959. if (!tbody._sortObserved) {
  8960. tbody._sortObserved = true;
  8961. let sortDebounceTimer = null;
  8962. const observer = new MutationObserver((mutations) => {
  8963. if (tbody._isSorting) return;
  8964. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  8965. if (!hasChildChanges) return;
  8966. clearTimeout(sortDebounceTimer);
  8967. sortDebounceTimer = setTimeout(() => {
  8968. if (tbody._isSorting) return;
  8969. if (table._activeSort && table._activeSort.dir !== 'none') {
  8970. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  8971. } else {
  8972. tagOriginalRowOrder(tbody);
  8973. }
  8974. }, 10);
  8975. });
  8976. observer.observe(tbody, { childList: true });
  8977. }
  8978. tagOriginalRowOrder(tbody);
  8979. }
  8980. function tagOriginalRowOrder(tbody) {
  8981. let idx = 0;
  8982. Array.from(tbody.children).forEach(tr => {
  8983. if (!tr.querySelector('td[colspan]')) {
  8984. if (!tr.hasAttribute('data-orig-idx')) {
  8985. tr.setAttribute('data-orig-idx', idx++);
  8986. }
  8987. }
  8988. });
  8989. }
  8990. function handleHeaderClick(table, th, colIdx) {
  8991. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  8992. let newDir = 'asc';
  8993. if (currentSort.colIdx === colIdx) {
  8994. if (currentSort.dir === 'asc') newDir = 'desc';
  8995. else if (currentSort.dir === 'desc') newDir = 'none';
  8996. else newDir = 'asc';
  8997. } else {
  8998. newDir = 'asc';
  8999. }
  9000. table._activeSort = { colIdx, dir: newDir };
  9001. updateHeaderIcons(table, colIdx, newDir);
  9002. applyTableSort(table, colIdx, newDir, true);
  9003. }
  9004. function updateHeaderIcons(table, activeColIdx, dir) {
  9005. const thead = table.querySelector('thead');
  9006. if (!thead) return;
  9007. const ths = thead.querySelectorAll('th');
  9008. ths.forEach((th, idx) => {
  9009. const icon = th.querySelector('.table-sort-icon');
  9010. if (!icon) return;
  9011. if (idx === activeColIdx && dir !== 'none') {
  9012. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  9013. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  9014. th.classList.add('table-sorted-active');
  9015. } else {
  9016. icon.innerHTML = '⇅';
  9017. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  9018. th.classList.remove('table-sorted-active');
  9019. }
  9020. });
  9021. }
  9022. function applyTableSort(table, colIdx, dir, userInitiated) {
  9023. const tbody = table.querySelector('tbody');
  9024. if (!tbody || tbody.children.length <= 1) return;
  9025. tbody._isSorting = true;
  9026. tagOriginalRowOrder(tbody);
  9027. // Group parent rows and any attached drawer/sub-rows
  9028. const groups = [];
  9029. let currentGroup = null;
  9030. Array.from(tbody.children).forEach(tr => {
  9031. if (tr.querySelector('td[colspan]')) {
  9032. if (currentGroup) {
  9033. currentGroup.subRows.push(tr);
  9034. } else {
  9035. groups.push({ mainRow: tr, subRows: [] });
  9036. }
  9037. } else {
  9038. currentGroup = { mainRow: tr, subRows: [] };
  9039. groups.push(currentGroup);
  9040. }
  9041. });
  9042. if (dir === 'none') {
  9043. groups.sort((a, b) => {
  9044. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  9045. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  9046. return idxA - idxB;
  9047. });
  9048. } else {
  9049. groups.sort((a, b) => {
  9050. const cellA = a.mainRow.children[colIdx];
  9051. const cellB = b.mainRow.children[colIdx];
  9052. const res = compareTableCells(cellA, cellB);
  9053. return dir === 'asc' ? res : -res;
  9054. });
  9055. }
  9056. // Re-append rows in sorted order
  9057. groups.forEach(g => {
  9058. tbody.appendChild(g.mainRow);
  9059. g.subRows.forEach(sub => tbody.appendChild(sub));
  9060. });
  9061. tbody._isSorting = false;
  9062. }
  9063. function getCellRawText(cell) {
  9064. if (!cell) return '';
  9065. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  9066. const input = cell.querySelector('input, select');
  9067. if (input) {
  9068. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  9069. return input.value;
  9070. }
  9071. return cell.innerText.trim();
  9072. }
  9073. function parseTrafficToNumber(str) {
  9074. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  9075. if (!m) return null;
  9076. const num = parseFloat(m[1].replace(/,/g, ''));
  9077. if (isNaN(num)) return null;
  9078. const unit = m[2].toUpperCase();
  9079. let mult = 1;
  9080. if (unit.startsWith('K')) mult = 1024;
  9081. else if (unit.startsWith('M')) mult = 1024 * 1024;
  9082. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  9083. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  9084. return num * mult;
  9085. }
  9086. function parseIpToNumber(str) {
  9087. const clean = str.replace(/^[!~]/, '').trim();
  9088. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  9089. if (!m) return null;
  9090. const o1 = parseInt(m[1], 10);
  9091. const o2 = parseInt(m[2], 10);
  9092. const o3 = parseInt(m[3], 10);
  9093. const o4 = parseInt(m[4], 10);
  9094. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  9095. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  9096. }
  9097. function parseCompoundPackets(str) {
  9098. const m = str.match(/^([\d,]+)p/);
  9099. if (!m) return null;
  9100. return parseInt(m[1].replace(/,/g, ''), 10);
  9101. }
  9102. function compareTableCells(cellA, cellB) {
  9103. const a = getCellRawText(cellA);
  9104. const b = getCellRawText(cellB);
  9105. if (a === '' && b !== '') return 1;
  9106. if (b === '' && a !== '') return -1;
  9107. if (a === b) return 0;
  9108. // 1. IP Addresses / CIDR
  9109. const ipA = parseIpToNumber(a);
  9110. const ipB = parseIpToNumber(b);
  9111. if (ipA !== null && ipB !== null) return ipA - ipB;
  9112. // 2. Packet counts (e.g. "1,250p / 45 KB")
  9113. const pktA = parseCompoundPackets(a);
  9114. const pktB = parseCompoundPackets(b);
  9115. if (pktA !== null && pktB !== null) return pktA - pktB;
  9116. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  9117. const trafA = parseTrafficToNumber(a);
  9118. const trafB = parseTrafficToNumber(b);
  9119. if (trafA !== null && trafB !== null) return trafA - trafB;
  9120. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  9121. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  9122. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  9123. const numA = Number(cleanNumA);
  9124. const numB = Number(cleanNumB);
  9125. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  9126. return numA - numB;
  9127. }
  9128. // 5. Natural case-insensitive string compare
  9129. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  9130. }
  9131. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  9132. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  9133. const docTableObserver = new MutationObserver((mutations) => {
  9134. let needsInit = false;
  9135. for (const m of mutations) {
  9136. for (const node of m.addedNodes) {
  9137. if (node.nodeType === 1) {
  9138. if (node.tagName === 'TABLE' || (node.querySelector && node.querySelector('table'))) {
  9139. needsInit = true;
  9140. break;
  9141. }
  9142. }
  9143. }
  9144. if (needsInit) break;
  9145. }
  9146. if (needsInit) {
  9147. initTableSorting();
  9148. }
  9149. });
  9150. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  9151. }