app.js 425 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155
  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 showSystem = document.getElementById('prule-show-system')?.checked;
  4979. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  4980. const bRules = document.getElementById('routes-badge-rules');
  4981. if (bRules) bRules.innerText = userRules.length;
  4982. const bTables = document.getElementById('routes-badge-tables');
  4983. if (bTables) bTables.innerText = (state.routingTables || []).length;
  4984. const bRoutesCount = document.getElementById('badge-routes-count');
  4985. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  4986. renderRoutesList();
  4987. renderPolicyRules();
  4988. renderRoutingTables();
  4989. } catch (err) {
  4990. console.error('Failed to load routing:', err);
  4991. }
  4992. }
  4993. function renderRoutesList() {
  4994. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  4995. const tbody = document.getElementById('routes-table-body');
  4996. const empty = document.getElementById('routes-empty');
  4997. if (!tbody) return;
  4998. tbody.innerHTML = '';
  4999. // Update table filter select
  5000. const sel = document.getElementById('routes-filter-table');
  5001. if (sel) {
  5002. const cur = sel.value;
  5003. sel.innerHTML = '<option value="">All Tables</option>';
  5004. (state.routingTables || []).forEach(t => {
  5005. const opt = document.createElement('option');
  5006. opt.value = t.name;
  5007. opt.innerText = t.name;
  5008. if (t.name === cur) opt.selected = true;
  5009. sel.appendChild(opt);
  5010. });
  5011. }
  5012. const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
  5013. document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
  5014. if (routes.length === 0) {
  5015. empty?.classList.remove('hidden');
  5016. return;
  5017. }
  5018. empty?.classList.add('hidden');
  5019. routes.forEach(r => {
  5020. const tr = document.createElement('tr');
  5021. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  5022. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  5023. // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
  5024. let flags = '';
  5025. if (r.dynamic) flags += 'D';
  5026. if (r.active) flags += 'A';
  5027. if (r.connect) flags += 'C';
  5028. if (r.static) flags += 'S';
  5029. if (r.disabled) flags += 'X';
  5030. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  5031. tr.innerHTML = `
  5032. <td class="py-2.5 px-3 text-center">
  5033. <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'}">
  5034. ${flags || '-'}
  5035. </span>
  5036. </td>
  5037. <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
  5038. <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>
  5039. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  5040. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  5041. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  5042. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  5043. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5044. ${r.static ? `
  5045. <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>
  5046. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  5047. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5048. ` : `
  5049. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  5050. `}
  5051. </td>
  5052. `;
  5053. tbody.appendChild(tr);
  5054. });
  5055. }
  5056. function openAddRouteModal() {
  5057. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  5058. document.getElementById('route-modal-id').value = '';
  5059. document.getElementById('route-modal-old-dst').value = '';
  5060. document.getElementById('route-modal-old-gw').value = '';
  5061. document.getElementById('route-modal-old-distance').value = '';
  5062. document.getElementById('route-modal-old-table').value = '';
  5063. document.getElementById('route-modal-old-iface').value = '';
  5064. const dstInput = document.getElementById('route-modal-dst');
  5065. const gwInput = document.getElementById('route-modal-gw');
  5066. const distInput = document.getElementById('route-modal-distance');
  5067. const ifaceSelect = document.getElementById('route-modal-iface');
  5068. const tableSelect = document.getElementById('route-modal-table');
  5069. const commentInput = document.getElementById('route-modal-comment');
  5070. const disCheck = document.getElementById('route-modal-disabled');
  5071. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5072. dstInput.disabled = false;
  5073. dstInput.value = '0.0.0.0/0';
  5074. gwInput.disabled = false;
  5075. gwInput.value = '';
  5076. distInput.disabled = false;
  5077. distInput.value = '1';
  5078. ifaceSelect.disabled = false;
  5079. tableSelect.disabled = false;
  5080. commentInput.disabled = false;
  5081. commentInput.value = '';
  5082. disCheck.disabled = false;
  5083. disCheck.checked = false;
  5084. if (saveBtn) saveBtn.classList.remove('hidden');
  5085. populateInterfaceSelect('route-modal-iface');
  5086. // Populate tables
  5087. tableSelect.innerHTML = '';
  5088. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5089. const opt = document.createElement('option');
  5090. opt.value = t.name;
  5091. opt.innerText = t.name;
  5092. if (t.name === 'main') opt.selected = true;
  5093. tableSelect.appendChild(opt);
  5094. });
  5095. document.getElementById('route-modal').classList.remove('hidden');
  5096. }
  5097. function openEditRouteModal(id) {
  5098. const r = (state.routes || []).find(route => route.id === id);
  5099. if (!r) return;
  5100. const isStatic = !!r.static;
  5101. document.getElementById('route-modal-title').innerText = isStatic
  5102. ? `Edit Route: ${r.dst_address}`
  5103. : `Route Properties (Read Only): ${r.dst_address}`;
  5104. document.getElementById('route-modal-id').value = r.id;
  5105. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  5106. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  5107. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  5108. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  5109. document.getElementById('route-modal-old-iface').value = r.interface || '';
  5110. const dstInput = document.getElementById('route-modal-dst');
  5111. const gwInput = document.getElementById('route-modal-gw');
  5112. const distInput = document.getElementById('route-modal-distance');
  5113. const ifaceSelect = document.getElementById('route-modal-iface');
  5114. const tableSelect = document.getElementById('route-modal-table');
  5115. const commentInput = document.getElementById('route-modal-comment');
  5116. const disCheck = document.getElementById('route-modal-disabled');
  5117. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5118. dstInput.value = r.dst_address;
  5119. gwInput.value = r.gateway || '';
  5120. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  5121. commentInput.value = r.comment || '';
  5122. disCheck.checked = !!r.disabled;
  5123. dstInput.disabled = !isStatic;
  5124. gwInput.disabled = !isStatic;
  5125. distInput.disabled = !isStatic;
  5126. ifaceSelect.disabled = !isStatic;
  5127. tableSelect.disabled = !isStatic;
  5128. commentInput.disabled = !isStatic;
  5129. disCheck.disabled = !isStatic;
  5130. if (saveBtn) {
  5131. if (isStatic) {
  5132. saveBtn.classList.remove('hidden');
  5133. } else {
  5134. saveBtn.classList.add('hidden');
  5135. }
  5136. }
  5137. populateInterfaceSelect('route-modal-iface', r.interface);
  5138. tableSelect.innerHTML = '';
  5139. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5140. const opt = document.createElement('option');
  5141. opt.value = t.name;
  5142. opt.innerText = t.name;
  5143. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  5144. tableSelect.appendChild(opt);
  5145. });
  5146. document.getElementById('route-modal').classList.remove('hidden');
  5147. }
  5148. function closeRouteModal() {
  5149. document.getElementById('route-modal').classList.add('hidden');
  5150. }
  5151. async function submitSaveRoute(e) {
  5152. e.preventDefault();
  5153. const id = document.getElementById('route-modal-id').value;
  5154. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  5155. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  5156. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  5157. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  5158. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  5159. const dst = document.getElementById('route-modal-dst').value.trim();
  5160. const gw = document.getElementById('route-modal-gw').value.trim();
  5161. const table = document.getElementById('route-modal-table').value;
  5162. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  5163. const iface = document.getElementById('route-modal-iface').value;
  5164. const comment = document.getElementById('route-modal-comment').value.trim();
  5165. const disabled = document.getElementById('route-modal-disabled').checked;
  5166. if (!dst) {
  5167. showToast('Error', 'Destination address is required', 'error');
  5168. return;
  5169. }
  5170. if (!gw && !iface) {
  5171. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  5172. return;
  5173. }
  5174. const payload = {
  5175. id,
  5176. old_dst_address: oldDst,
  5177. old_gateway: oldGw,
  5178. old_routing_table: oldTable,
  5179. old_interface: oldIface,
  5180. dst_address: dst,
  5181. gateway: gw || iface,
  5182. routing_table: table,
  5183. distance,
  5184. interface: iface,
  5185. comment,
  5186. disabled
  5187. };
  5188. if (oldDistStr !== undefined && oldDistStr !== '') {
  5189. payload.old_distance = parseInt(oldDistStr, 10);
  5190. }
  5191. try {
  5192. const res = await fetch(`${API_BASE}/routes`, {
  5193. method: 'POST',
  5194. headers: { 'Content-Type': 'application/json' },
  5195. body: JSON.stringify(payload)
  5196. });
  5197. if (res.ok) {
  5198. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  5199. closeRouteModal();
  5200. loadRoutes();
  5201. } else {
  5202. const err = await res.json();
  5203. showToast('Error', err.message || 'Failed to save route', 'error');
  5204. }
  5205. } catch (err) {
  5206. showToast('Error', err.message, 'error');
  5207. }
  5208. }
  5209. async function toggleRouteState(id, disabled) {
  5210. try {
  5211. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  5212. method: 'POST',
  5213. headers: { 'Content-Type': 'application/json' },
  5214. body: JSON.stringify({ disabled })
  5215. });
  5216. if (res.ok) loadRoutes();
  5217. } catch (err) {
  5218. showToast('Error', err.message, 'error');
  5219. }
  5220. }
  5221. async function deleteRoute(id) {
  5222. if (!confirm('Are you sure you want to delete this route?')) return;
  5223. try {
  5224. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5225. if (res.ok) {
  5226. showToast('Deleted', 'Route removed', 'success');
  5227. loadRoutes();
  5228. }
  5229. } catch (err) {
  5230. showToast('Error', err.message, 'error');
  5231. }
  5232. }
  5233. // ----------------- Policy Rules (/ip route rule) -----------------
  5234. function renderPolicyRules() {
  5235. const tbody = document.getElementById('rules-table-body');
  5236. const empty = document.getElementById('rules-empty');
  5237. if (!tbody) return;
  5238. tbody.innerHTML = '';
  5239. const showSystem = document.getElementById('prule-show-system')?.checked;
  5240. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5241. const countBadge = document.getElementById('rules-count-badge');
  5242. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  5243. const bRules = document.getElementById('routes-badge-rules');
  5244. if (bRules) bRules.innerText = filtered.length;
  5245. if (filtered.length === 0) {
  5246. empty?.classList.remove('hidden');
  5247. return;
  5248. }
  5249. empty?.classList.add('hidden');
  5250. filtered.forEach(pr => {
  5251. const isSys = pr.is_default || pr.is_system;
  5252. const tr = document.createElement('tr');
  5253. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  5254. tr.innerHTML = `
  5255. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  5256. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  5257. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  5258. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  5259. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  5260. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  5261. <td class="py-2.5 px-3 text-right font-sans">
  5262. ${!pr.is_default ? `
  5263. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5264. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  5265. </td>
  5266. `;
  5267. tbody.appendChild(tr);
  5268. });
  5269. }
  5270. function openAddPolicyRuleModal() {
  5271. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  5272. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  5273. document.getElementById('prule-modal-mark').value = '';
  5274. document.getElementById('prule-modal-src').value = '';
  5275. document.getElementById('prule-modal-dst').value = '';
  5276. const sel = document.getElementById('prule-modal-table');
  5277. sel.innerHTML = '';
  5278. (state.routingTables || []).forEach(t => {
  5279. const opt = document.createElement('option');
  5280. opt.value = t.name;
  5281. opt.innerText = t.name;
  5282. sel.appendChild(opt);
  5283. });
  5284. document.getElementById('prule-modal').classList.remove('hidden');
  5285. }
  5286. function closePolicyRuleModal() {
  5287. document.getElementById('prule-modal').classList.add('hidden');
  5288. }
  5289. async function submitSavePolicyRule(e) {
  5290. e.preventDefault();
  5291. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  5292. const mark = document.getElementById('prule-modal-mark').value.trim();
  5293. const src = document.getElementById('prule-modal-src').value.trim();
  5294. const dst = document.getElementById('prule-modal-dst').value.trim();
  5295. const table = document.getElementById('prule-modal-table').value;
  5296. const action = document.getElementById('prule-modal-action').value;
  5297. try {
  5298. const res = await fetch(`${API_BASE}/routing/rules`, {
  5299. method: 'POST',
  5300. headers: { 'Content-Type': 'application/json' },
  5301. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  5302. });
  5303. if (res.ok) {
  5304. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  5305. closePolicyRuleModal();
  5306. loadRoutes();
  5307. } else {
  5308. const err = await res.json();
  5309. showToast('Error', err.message, 'error');
  5310. }
  5311. } catch (err) {
  5312. showToast('Error', err.message, 'error');
  5313. }
  5314. }
  5315. async function deletePolicyRule(id) {
  5316. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  5317. try {
  5318. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5319. if (res.ok) {
  5320. showToast('Rule Removed', 'Policy rule deleted', 'success');
  5321. loadRoutes();
  5322. }
  5323. } catch (err) {
  5324. showToast('Error', err.message, 'error');
  5325. }
  5326. }
  5327. // ----------------- Routing Tables -----------------
  5328. function renderRoutingTables() {
  5329. const tbody = document.getElementById('tables-table-body');
  5330. if (!tbody) return;
  5331. tbody.innerHTML = '';
  5332. (state.routingTables || []).forEach(t => {
  5333. const tr = document.createElement('tr');
  5334. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5335. tr.innerHTML = `
  5336. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  5337. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  5338. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  5339. `;
  5340. tbody.appendChild(tr);
  5341. });
  5342. }
  5343. function openAddTableModal() {
  5344. document.getElementById('table-modal-name').value = '';
  5345. document.getElementById('table-modal-id').value = '';
  5346. document.getElementById('table-modal-comment').value = '';
  5347. document.getElementById('table-modal').classList.remove('hidden');
  5348. }
  5349. function closeTableModal() {
  5350. document.getElementById('table-modal').classList.add('hidden');
  5351. }
  5352. async function submitSaveTable(e) {
  5353. e.preventDefault();
  5354. const name = document.getElementById('table-modal-name').value.trim();
  5355. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  5356. const comment = document.getElementById('table-modal-comment').value.trim();
  5357. try {
  5358. const res = await fetch(`${API_BASE}/routing/tables`, {
  5359. method: 'POST',
  5360. headers: { 'Content-Type': 'application/json' },
  5361. body: JSON.stringify({ name, table_id: id, comment })
  5362. });
  5363. if (res.ok) {
  5364. showToast('Table Created', `Routing table ${name} registered`, 'success');
  5365. closeTableModal();
  5366. loadRoutes();
  5367. } else {
  5368. const err = await res.json();
  5369. showToast('Error', err.message, 'error');
  5370. }
  5371. } catch (err) {
  5372. showToast('Error', err.message, 'error');
  5373. }
  5374. }
  5375. async function loadDebianConfig() {
  5376. const view = document.getElementById('debian-config-view');
  5377. view.innerText = 'Generating live configuration...';
  5378. try {
  5379. const res = await fetch(`${API_BASE}/debian/config`);
  5380. const data = await res.json();
  5381. view.innerText = data.content || '# Empty config';
  5382. } catch (err) {
  5383. view.innerText = 'Failed to generate Debian network config.';
  5384. }
  5385. }
  5386. async function saveDebianConfig() {
  5387. try {
  5388. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  5389. const data = await res.json();
  5390. if (res.ok) {
  5391. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  5392. loadDebianConfig();
  5393. }
  5394. } catch (err) {
  5395. showToast('Error', err.message, 'error');
  5396. }
  5397. }
  5398. function showToast(title, message, type = 'info') {
  5399. const container = document.getElementById('toast-container');
  5400. const toast = document.createElement('div');
  5401. const borderColors = {
  5402. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  5403. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  5404. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  5405. };
  5406. 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}`;
  5407. toast.innerHTML = `
  5408. <div class="flex-1">
  5409. <div class="font-bold text-xs text-white">${title}</div>
  5410. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  5411. </div>
  5412. `;
  5413. container.appendChild(toast);
  5414. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  5415. setTimeout(() => {
  5416. toast.classList.add('opacity-0', 'translate-y-2');
  5417. setTimeout(() => toast.remove(), 300);
  5418. }, 4000);
  5419. }
  5420. function formatTraffic(bytesPerSec) {
  5421. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  5422. const kb = bytesPerSec / 1024;
  5423. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  5424. const mb = kb / 1024;
  5425. return `${mb.toFixed(2)} MB/s`;
  5426. }
  5427. function toggleSidebar() {
  5428. const sb = document.getElementById('sidebar');
  5429. sb.classList.toggle('-translate-x-full');
  5430. }
  5431. // ======================== EoIP (Ethernet over IP) ========================
  5432. async function loadEoIP(populate = true) {
  5433. try {
  5434. const res = await fetch(`${API_BASE}/vpn/eoip`);
  5435. const data = await res.json();
  5436. state.eoipTunnels = Array.isArray(data) ? data : [];
  5437. const badge = document.getElementById('eoip-count-badge');
  5438. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  5439. const sideBadge = document.getElementById('badge-eoip-count');
  5440. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  5441. renderEoIPTunnels();
  5442. } catch (err) {
  5443. console.error('Failed to load EoIP:', err);
  5444. }
  5445. }
  5446. function renderEoIPTunnels() {
  5447. const tbody = document.getElementById('eoip-table-body');
  5448. const empty = document.getElementById('eoip-empty');
  5449. if (!tbody) return;
  5450. tbody.innerHTML = '';
  5451. const tunnels = state.eoipTunnels || [];
  5452. if (tunnels.length === 0) {
  5453. empty?.classList.remove('hidden');
  5454. return;
  5455. }
  5456. empty?.classList.add('hidden');
  5457. tunnels.forEach(t => {
  5458. const tr = document.createElement('tr');
  5459. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  5460. tr.innerHTML = `
  5461. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  5462. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  5463. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  5464. <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>
  5465. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  5466. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  5467. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  5468. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  5469. <td class="py-2.5 px-3 font-mono text-[11px]">
  5470. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  5471. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  5472. </td>
  5473. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  5474. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5475. <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>
  5476. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5477. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  5478. </td>
  5479. `;
  5480. tbody.appendChild(tr);
  5481. });
  5482. }
  5483. function openAddEoIPModal() {
  5484. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  5485. document.getElementById('eoip-modal-id').value = '';
  5486. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  5487. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  5488. document.getElementById('eoip-modal-remote').value = '';
  5489. document.getElementById('eoip-modal-ip').value = '';
  5490. document.getElementById('eoip-modal-local').value = '';
  5491. document.getElementById('eoip-modal-mac').value = '';
  5492. document.getElementById('eoip-modal-mtu').value = '1500';
  5493. document.getElementById('eoip-modal-comment').value = '';
  5494. document.getElementById('eoip-modal-clampmss').checked = true;
  5495. document.getElementById('eoip-modal-disabled').checked = false;
  5496. document.getElementById('eoip-modal').classList.remove('hidden');
  5497. }
  5498. function openEditEoIPModal(id) {
  5499. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  5500. if (!t) return;
  5501. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  5502. document.getElementById('eoip-modal-id').value = t.id;
  5503. document.getElementById('eoip-modal-name').value = t.name;
  5504. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  5505. document.getElementById('eoip-modal-remote').value = t.remote_address;
  5506. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  5507. document.getElementById('eoip-modal-local').value = t.local_address || '';
  5508. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  5509. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  5510. document.getElementById('eoip-modal-comment').value = t.comment || '';
  5511. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  5512. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  5513. document.getElementById('eoip-modal').classList.remove('hidden');
  5514. }
  5515. function closeEoIPModal() {
  5516. document.getElementById('eoip-modal').classList.add('hidden');
  5517. }
  5518. async function submitSaveEoIP(e) {
  5519. e.preventDefault();
  5520. const id = document.getElementById('eoip-modal-id').value;
  5521. const name = document.getElementById('eoip-modal-name').value.trim();
  5522. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  5523. const remote = document.getElementById('eoip-modal-remote').value.trim();
  5524. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  5525. const local = document.getElementById('eoip-modal-local').value.trim();
  5526. const mac = document.getElementById('eoip-modal-mac').value.trim();
  5527. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  5528. const comment = document.getElementById('eoip-modal-comment').value.trim();
  5529. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  5530. const disabled = document.getElementById('eoip-modal-disabled').checked;
  5531. try {
  5532. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  5533. method: 'POST',
  5534. headers: { 'Content-Type': 'application/json' },
  5535. body: JSON.stringify({
  5536. id,
  5537. name,
  5538. tunnel_id: tunnelId,
  5539. remote_address: remote,
  5540. ip_address: ipAddress,
  5541. local_address: local,
  5542. mac_address: mac,
  5543. mtu,
  5544. clamp_mss: clampMss,
  5545. comment,
  5546. disabled
  5547. })
  5548. });
  5549. if (res.ok) {
  5550. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  5551. closeEoIPModal();
  5552. loadEoIP(false);
  5553. fetchData(false);
  5554. } else {
  5555. const err = await res.json();
  5556. showToast('Error', err.message, 'error');
  5557. }
  5558. } catch (err) {
  5559. showToast('Error', err.message, 'error');
  5560. }
  5561. }
  5562. async function toggleEoIPState(id, disabled) {
  5563. try {
  5564. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  5565. method: 'POST',
  5566. headers: { 'Content-Type': 'application/json' },
  5567. body: JSON.stringify({ disabled })
  5568. });
  5569. if (res.ok) {
  5570. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  5571. loadEoIP(false);
  5572. fetchData(false);
  5573. }
  5574. } catch (err) {
  5575. showToast('Error', err.message, 'error');
  5576. }
  5577. }
  5578. async function deleteEoIP(id) {
  5579. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  5580. try {
  5581. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5582. if (res.ok) {
  5583. showToast('Deleted', 'EoIP tunnel removed', 'success');
  5584. loadEoIP(false);
  5585. fetchData(false);
  5586. }
  5587. } catch (err) {
  5588. showToast('Error', err.message, 'error');
  5589. }
  5590. }
  5591. // ======================== PPP Central Hub & Servers ========================
  5592. function switchPPPSubTab(tab) {
  5593. state.pppSubTab = tab;
  5594. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  5595. tabs.forEach(t => {
  5596. const panel = document.getElementById(`ppp-subtab-${t}`);
  5597. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  5598. if (panel) {
  5599. if (t === tab) panel.classList.remove('hidden');
  5600. else panel.classList.add('hidden');
  5601. }
  5602. if (btn) {
  5603. if (t === tab) {
  5604. 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';
  5605. } else {
  5606. 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';
  5607. }
  5608. }
  5609. });
  5610. const addBtn = document.getElementById('ppp-primary-add-btn');
  5611. if (addBtn) {
  5612. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  5613. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  5614. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  5615. else addBtn.innerHTML = '<span>Save Config</span>';
  5616. }
  5617. if (tab === 'active') loadPPPSessions();
  5618. }
  5619. function openCurrentPPPModal() {
  5620. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  5621. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  5622. else if (state.pppSubTab === 'active') loadPPPSessions();
  5623. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  5624. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  5625. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  5626. }
  5627. async function loadPPP(populateDropdowns = true) {
  5628. await Promise.all([
  5629. loadPPPSecrets(),
  5630. loadPPPProfiles(),
  5631. loadPPPServers(),
  5632. loadPPPSessions()
  5633. ]);
  5634. }
  5635. async function loadPPPSecrets() {
  5636. try {
  5637. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  5638. const data = await res.json();
  5639. state.pppSecrets = Array.isArray(data) ? data : [];
  5640. const b = document.getElementById('ppp-badge-secrets');
  5641. if (b) b.innerText = state.pppSecrets.length;
  5642. const b2 = document.getElementById('secrets-count-badge');
  5643. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  5644. renderPPPSecrets();
  5645. } catch (err) {
  5646. console.error('Failed to load PPP secrets:', err);
  5647. }
  5648. }
  5649. function renderPPPSecrets() {
  5650. const tbody = document.getElementById('secrets-table-body');
  5651. const empty = document.getElementById('secrets-empty');
  5652. if (!tbody) return;
  5653. tbody.innerHTML = '';
  5654. const secrets = state.pppSecrets || [];
  5655. if (secrets.length === 0) {
  5656. empty?.classList.remove('hidden');
  5657. return;
  5658. }
  5659. empty?.classList.add('hidden');
  5660. secrets.forEach(s => {
  5661. const tr = document.createElement('tr');
  5662. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  5663. tr.innerHTML = `
  5664. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  5665. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  5666. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  5667. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  5668. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  5669. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  5670. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  5671. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5672. <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>
  5673. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5674. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  5675. </td>
  5676. `;
  5677. tbody.appendChild(tr);
  5678. });
  5679. }
  5680. async function loadPPPProfiles() {
  5681. try {
  5682. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  5683. const data = await res.json();
  5684. state.pppProfiles = Array.isArray(data) ? data : [];
  5685. const b = document.getElementById('ppp-badge-profiles');
  5686. if (b) b.innerText = state.pppProfiles.length;
  5687. const b2 = document.getElementById('profiles-count-badge');
  5688. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  5689. // Populate profile selects across modals
  5690. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  5691. selects.forEach(sid => {
  5692. const el = document.getElementById(sid);
  5693. if (!el) return;
  5694. const cur = el.value;
  5695. el.innerHTML = '';
  5696. state.pppProfiles.forEach(p => {
  5697. const opt = document.createElement('option');
  5698. opt.value = p.name;
  5699. opt.innerText = `${p.name} (${p.remote_address})`;
  5700. if (p.name === cur) opt.selected = true;
  5701. el.appendChild(opt);
  5702. });
  5703. });
  5704. renderPPPProfiles();
  5705. } catch (err) {
  5706. console.error('Failed to load PPP profiles:', err);
  5707. }
  5708. }
  5709. function renderPPPProfiles() {
  5710. const tbody = document.getElementById('profiles-table-body');
  5711. if (!tbody) return;
  5712. tbody.innerHTML = '';
  5713. (state.pppProfiles || []).forEach(p => {
  5714. const isDefault = p.name.startsWith('default');
  5715. const tr = document.createElement('tr');
  5716. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5717. tr.innerHTML = `
  5718. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  5719. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  5720. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  5721. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  5722. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  5723. <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>
  5724. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  5725. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  5726. ${!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>`}
  5727. </td>
  5728. `;
  5729. tbody.appendChild(tr);
  5730. });
  5731. }
  5732. async function loadPPPServers() {
  5733. try {
  5734. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  5735. fetch(`${API_BASE}/vpn/servers/pppoe`),
  5736. fetch(`${API_BASE}/vpn/servers/pptp`),
  5737. fetch(`${API_BASE}/vpn/servers/l2tp`),
  5738. fetch(`${API_BASE}/vpn/servers/ipsec`)
  5739. ]);
  5740. if (pppoeRes.ok) {
  5741. state.pppoeServer = await pppoeRes.json();
  5742. const s = state.pppoeServer;
  5743. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  5744. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  5745. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  5746. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  5747. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  5748. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  5749. const pill = document.getElementById('pppoe-server-status-pill');
  5750. if (pill) {
  5751. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  5752. 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';
  5753. }
  5754. setDotBadge('ppp-badge-pppoe-state', s.running);
  5755. }
  5756. if (pptpRes.ok) {
  5757. state.pptpServer = await pptpRes.json();
  5758. const s = state.pptpServer;
  5759. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  5760. document.getElementById('pptp-server-port').value = s.port || 1723;
  5761. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  5762. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  5763. const pill = document.getElementById('pptp-server-status-pill');
  5764. if (pill) {
  5765. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  5766. 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';
  5767. }
  5768. setDotBadge('ppp-badge-pptp-state', s.running);
  5769. }
  5770. if (l2tpRes.ok) {
  5771. state.l2tpServer = await l2tpRes.json();
  5772. const s = state.l2tpServer;
  5773. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  5774. document.getElementById('l2tp-server-port').value = s.port || 1701;
  5775. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  5776. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  5777. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  5778. const pill = document.getElementById('l2tp-server-status-pill');
  5779. if (pill) {
  5780. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  5781. 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';
  5782. }
  5783. setDotBadge('ppp-badge-l2tp-state', s.running);
  5784. }
  5785. if (ipsecRes.ok) {
  5786. state.ipsecServer = await ipsecRes.json();
  5787. const s = state.ipsecServer;
  5788. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  5789. if (modalEn) modalEn.checked = !!s.enabled;
  5790. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  5791. if (modalPsk) modalPsk.value = s.preshared_key || '';
  5792. const modalPool = document.getElementById('modal-ipsec-server-pool');
  5793. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  5794. const modalDns = document.getElementById('modal-ipsec-server-dns');
  5795. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  5796. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  5797. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  5798. const pill = document.getElementById('modal-ipsec-server-status');
  5799. if (pill) {
  5800. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  5801. 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';
  5802. }
  5803. }
  5804. } catch (err) {
  5805. console.error('Failed to load VPN servers:', err);
  5806. }
  5807. }
  5808. async function loadPPPSessions() {
  5809. try {
  5810. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  5811. const data = await res.json();
  5812. state.pppActiveSessions = Array.isArray(data) ? data : [];
  5813. const b = document.getElementById('ppp-badge-active');
  5814. if (b) b.innerText = state.pppActiveSessions.length;
  5815. const sideB = document.getElementById('badge-ppp-sessions');
  5816. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  5817. renderPPPSessions();
  5818. } catch (err) {
  5819. console.error('Failed to load active PPP sessions:', err);
  5820. }
  5821. }
  5822. function renderPPPSessions() {
  5823. const tbody = document.getElementById('active-ppp-table-body');
  5824. const empty = document.getElementById('active-ppp-empty');
  5825. if (!tbody) return;
  5826. tbody.innerHTML = '';
  5827. const list = state.pppActiveSessions || [];
  5828. if (list.length === 0) {
  5829. empty?.classList.remove('hidden');
  5830. return;
  5831. }
  5832. empty?.classList.add('hidden');
  5833. list.forEach(s => {
  5834. const tr = document.createElement('tr');
  5835. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5836. tr.innerHTML = `
  5837. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  5838. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  5839. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  5840. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  5841. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  5842. <td class="py-2.5 px-3 text-[11px]">
  5843. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  5844. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  5845. </td>
  5846. <td class="py-2.5 px-3 text-right font-sans">
  5847. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  5848. </td>
  5849. `;
  5850. tbody.appendChild(tr);
  5851. });
  5852. }
  5853. async function disconnectPPPSession(iface) {
  5854. if (!confirm(`Disconnect session ${iface}?`)) return;
  5855. try {
  5856. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  5857. if (res.ok) {
  5858. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  5859. loadPPPSessions();
  5860. }
  5861. } catch (err) {
  5862. showToast('Error', err.message, 'error');
  5863. }
  5864. }
  5865. // PPP Secret Modal handlers
  5866. function openAddPPPSecretModal() {
  5867. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  5868. document.getElementById('secret-modal-id').value = '';
  5869. document.getElementById('secret-modal-name').value = '';
  5870. document.getElementById('secret-modal-password').value = '';
  5871. document.getElementById('secret-modal-service').value = 'any';
  5872. document.getElementById('secret-modal-profile').value = 'default';
  5873. document.getElementById('secret-modal-local').value = '';
  5874. document.getElementById('secret-modal-remote').value = '';
  5875. document.getElementById('secret-modal-comment').value = '';
  5876. document.getElementById('secret-modal-disabled').checked = false;
  5877. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  5878. }
  5879. function openEditPPPSecretModal(id) {
  5880. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  5881. if (!s) return;
  5882. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  5883. document.getElementById('secret-modal-id').value = s.id;
  5884. document.getElementById('secret-modal-name').value = s.name;
  5885. document.getElementById('secret-modal-password').value = s.password;
  5886. document.getElementById('secret-modal-service').value = s.service || 'any';
  5887. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  5888. document.getElementById('secret-modal-local').value = s.local_address || '';
  5889. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  5890. document.getElementById('secret-modal-comment').value = s.comment || '';
  5891. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  5892. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  5893. }
  5894. function closePPPSecretModal() {
  5895. document.getElementById('ppp-secret-modal').classList.add('hidden');
  5896. }
  5897. async function submitSavePPPSecret(e) {
  5898. e.preventDefault();
  5899. const id = document.getElementById('secret-modal-id').value;
  5900. const name = document.getElementById('secret-modal-name').value.trim();
  5901. const password = document.getElementById('secret-modal-password').value.trim();
  5902. const service = document.getElementById('secret-modal-service').value;
  5903. const profile = document.getElementById('secret-modal-profile').value;
  5904. const local = document.getElementById('secret-modal-local').value.trim();
  5905. const remote = document.getElementById('secret-modal-remote').value.trim();
  5906. const comment = document.getElementById('secret-modal-comment').value.trim();
  5907. const disabled = document.getElementById('secret-modal-disabled').checked;
  5908. try {
  5909. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  5910. method: 'POST',
  5911. headers: { 'Content-Type': 'application/json' },
  5912. body: JSON.stringify({
  5913. id,
  5914. name,
  5915. password,
  5916. service,
  5917. profile,
  5918. local_address: local,
  5919. remote_address: remote,
  5920. comment,
  5921. disabled
  5922. })
  5923. });
  5924. if (res.ok) {
  5925. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  5926. closePPPSecretModal();
  5927. loadPPPSecrets();
  5928. } else {
  5929. const err = await res.json();
  5930. showToast('Error', err.message, 'error');
  5931. }
  5932. } catch (err) {
  5933. showToast('Error', err.message, 'error');
  5934. }
  5935. }
  5936. async function togglePPPSecretState(id, disabled) {
  5937. try {
  5938. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  5939. method: 'POST',
  5940. headers: { 'Content-Type': 'application/json' },
  5941. body: JSON.stringify({ disabled })
  5942. });
  5943. if (res.ok) {
  5944. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  5945. loadPPPSecrets();
  5946. }
  5947. } catch (err) {
  5948. showToast('Error', err.message, 'error');
  5949. }
  5950. }
  5951. async function deletePPPSecret(id) {
  5952. if (!confirm('Are you sure you want to delete this secret account?')) return;
  5953. try {
  5954. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5955. if (res.ok) {
  5956. showToast('Deleted', 'Secret account removed', 'success');
  5957. loadPPPSecrets();
  5958. }
  5959. } catch (err) {
  5960. showToast('Error', err.message, 'error');
  5961. }
  5962. }
  5963. // PPP Profile Modal handlers
  5964. function openAddPPPProfileModal() {
  5965. document.getElementById('profile-modal-name').value = '';
  5966. document.getElementById('profile-modal-local').value = '10.10.10.1';
  5967. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  5968. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  5969. document.getElementById('profile-modal-encryption').value = 'required';
  5970. document.getElementById('profile-modal-onlyone').checked = true;
  5971. document.getElementById('profile-modal-comment').value = '';
  5972. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  5973. }
  5974. function closePPPProfileModal() {
  5975. document.getElementById('ppp-profile-modal').classList.add('hidden');
  5976. }
  5977. async function submitSavePPPProfile(e) {
  5978. e.preventDefault();
  5979. const name = document.getElementById('profile-modal-name').value.trim();
  5980. const local = document.getElementById('profile-modal-local').value.trim();
  5981. const remote = document.getElementById('profile-modal-remote').value.trim();
  5982. const dns = document.getElementById('profile-modal-dns').value.trim();
  5983. const enc = document.getElementById('profile-modal-encryption').value;
  5984. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  5985. const comment = document.getElementById('profile-modal-comment').value.trim();
  5986. try {
  5987. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  5988. method: 'POST',
  5989. headers: { 'Content-Type': 'application/json' },
  5990. body: JSON.stringify({
  5991. id: name,
  5992. name,
  5993. local_address: local,
  5994. remote_address: remote,
  5995. dns_servers: dns,
  5996. use_encryption: enc,
  5997. only_one: onlyone,
  5998. comment
  5999. })
  6000. });
  6001. if (res.ok) {
  6002. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  6003. closePPPProfileModal();
  6004. loadPPPProfiles();
  6005. } else {
  6006. const err = await res.json();
  6007. showToast('Error', err.message, 'error');
  6008. }
  6009. } catch (err) {
  6010. showToast('Error', err.message, 'error');
  6011. }
  6012. }
  6013. async function deletePPPProfile(name) {
  6014. if (!confirm(`Delete PPP profile ${name}?`)) return;
  6015. try {
  6016. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  6017. if (res.ok) {
  6018. showToast('Deleted', 'Profile removed', 'success');
  6019. loadPPPProfiles();
  6020. } else {
  6021. const err = await res.json();
  6022. showToast('Error', err.message, 'error');
  6023. }
  6024. } catch (err) {
  6025. showToast('Error', err.message, 'error');
  6026. }
  6027. }
  6028. // Server Config submissions
  6029. async function savePPPoEServerConfig(e) {
  6030. e.preventDefault();
  6031. const enabled = document.getElementById('pppoe-server-enabled').checked;
  6032. const name = document.getElementById('pppoe-server-name').value.trim();
  6033. const iface = document.getElementById('pppoe-server-iface').value;
  6034. const profile = document.getElementById('pppoe-server-profile').value;
  6035. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  6036. const onesession = document.getElementById('pppoe-server-onesession').checked;
  6037. try {
  6038. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  6039. method: 'POST',
  6040. headers: { 'Content-Type': 'application/json' },
  6041. body: JSON.stringify({
  6042. enabled,
  6043. service_name: name,
  6044. interface: iface,
  6045. default_profile: profile,
  6046. max_mtu: mtu,
  6047. max_mru: mtu,
  6048. one_session_per_host: onesession
  6049. })
  6050. });
  6051. if (res.ok) {
  6052. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  6053. loadPPPServers();
  6054. fetchData(false);
  6055. } else {
  6056. const err = await res.json();
  6057. showToast('Error', err.message, 'error');
  6058. }
  6059. } catch (err) {
  6060. showToast('Error', err.message, 'error');
  6061. }
  6062. }
  6063. async function savePPTPServerConfig(e) {
  6064. e.preventDefault();
  6065. const enabled = document.getElementById('pptp-server-enabled').checked;
  6066. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  6067. const profile = document.getElementById('pptp-server-profile').value;
  6068. const mppe = document.getElementById('pptp-server-mppe').checked;
  6069. try {
  6070. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  6071. method: 'POST',
  6072. headers: { 'Content-Type': 'application/json' },
  6073. body: JSON.stringify({
  6074. enabled,
  6075. port,
  6076. default_profile: profile,
  6077. require_mppe: mppe
  6078. })
  6079. });
  6080. if (res.ok) {
  6081. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  6082. loadPPPServers();
  6083. fetchData(false);
  6084. } else {
  6085. const err = await res.json();
  6086. showToast('Error', err.message, 'error');
  6087. }
  6088. } catch (err) {
  6089. showToast('Error', err.message, 'error');
  6090. }
  6091. }
  6092. async function saveL2TPServerConfig(e) {
  6093. e.preventDefault();
  6094. const enabled = document.getElementById('l2tp-server-enabled').checked;
  6095. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  6096. const profile = document.getElementById('l2tp-server-profile').value;
  6097. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  6098. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  6099. try {
  6100. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  6101. method: 'POST',
  6102. headers: { 'Content-Type': 'application/json' },
  6103. body: JSON.stringify({
  6104. enabled,
  6105. port,
  6106. default_profile: profile,
  6107. use_ipsec: useipsec,
  6108. ipsec_secret: psk
  6109. })
  6110. });
  6111. if (res.ok) {
  6112. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  6113. loadPPPServers();
  6114. fetchData(false);
  6115. } else {
  6116. const err = await res.json();
  6117. showToast('Error', err.message, 'error');
  6118. }
  6119. } catch (err) {
  6120. showToast('Error', err.message, 'error');
  6121. }
  6122. }
  6123. // IPSec Server Modal
  6124. function openIPSecServerModal() {
  6125. loadPPPServers();
  6126. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  6127. }
  6128. function closeIPSecServerModal() {
  6129. document.getElementById('ipsec-server-modal').classList.add('hidden');
  6130. }
  6131. async function submitSaveIPSecServer(e) {
  6132. e.preventDefault();
  6133. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  6134. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  6135. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  6136. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  6137. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  6138. try {
  6139. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  6140. method: 'POST',
  6141. headers: { 'Content-Type': 'application/json' },
  6142. body: JSON.stringify({
  6143. enabled,
  6144. preshared_key: psk,
  6145. pool_address: pool,
  6146. dns_servers: dns,
  6147. local_subnet: subnet
  6148. })
  6149. });
  6150. if (res.ok) {
  6151. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  6152. closeIPSecServerModal();
  6153. loadPPPServers();
  6154. fetchData(false);
  6155. } else {
  6156. const err = await res.json();
  6157. showToast('Error', err.message, 'error');
  6158. }
  6159. } catch (err) {
  6160. showToast('Error', err.message, 'error');
  6161. }
  6162. }
  6163. // WireGuard Client Config Viewer
  6164. let currentWGClientConf = '';
  6165. async function openWGClientConfModal(iface, clientIP) {
  6166. try {
  6167. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  6168. method: 'POST',
  6169. headers: { 'Content-Type': 'application/json' },
  6170. body: JSON.stringify({
  6171. interface: iface,
  6172. address: clientIP || '10.10.0.2/32',
  6173. dns: '1.1.1.1, 8.8.8.8'
  6174. })
  6175. });
  6176. if (res.ok) {
  6177. const data = await res.json();
  6178. currentWGClientConf = data.config;
  6179. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  6180. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  6181. } else {
  6182. const err = await res.json();
  6183. showToast('Error', err.message, 'error');
  6184. }
  6185. } catch (err) {
  6186. showToast('Error', err.message, 'error');
  6187. }
  6188. }
  6189. function closeWGClientConfModal() {
  6190. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  6191. }
  6192. function copyWGClientConf() {
  6193. if (!currentWGClientConf) return;
  6194. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  6195. }
  6196. function downloadWGClientConf() {
  6197. if (!currentWGClientConf) return;
  6198. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  6199. const a = document.createElement('a');
  6200. a.href = URL.createObjectURL(blob);
  6201. a.download = 'wireguard-client.conf';
  6202. document.body.appendChild(a);
  6203. a.click();
  6204. document.body.removeChild(a);
  6205. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  6206. }
  6207. // =========================================================================
  6208. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  6209. // =========================================================================
  6210. state.activeDynSubTab = 'bgp-peers';
  6211. state.activeBgpSubTab = 'bgp-peers';
  6212. state.activeOspfSubTab = 'ospf-ifaces';
  6213. state.bgpInstance = null;
  6214. state.bgpPeers = [];
  6215. state.bgpNets = [];
  6216. state.bgpRoutes = [];
  6217. state.ospfInstance = null;
  6218. state.ospfInterfaces = [];
  6219. state.ospfAreas = [];
  6220. state.ospfNeighbors = [];
  6221. state.ospfRoutes = [];
  6222. function switchBgpSubTab(subTab) {
  6223. state.activeBgpSubTab = subTab;
  6224. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  6225. tabs.forEach(t => {
  6226. const el = document.getElementById(`dyn-subtab-${t}`);
  6227. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  6228. if (el) el.classList.toggle('hidden', t !== subTab);
  6229. if (btn) {
  6230. if (t === subTab) {
  6231. 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';
  6232. } else {
  6233. 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';
  6234. }
  6235. }
  6236. });
  6237. }
  6238. function switchOspfSubTab(subTab) {
  6239. state.activeOspfSubTab = subTab;
  6240. const tabs = ['ospf-ifaces', 'ospf-areas', 'ospf-nbrs', 'ospf-routes'];
  6241. tabs.forEach(t => {
  6242. const el = document.getElementById(`dyn-subtab-${t}`);
  6243. const btn = document.getElementById(`ospf-subtab-btn-${t}`);
  6244. if (el) el.classList.toggle('hidden', t !== subTab);
  6245. if (btn) {
  6246. if (t === subTab) {
  6247. 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';
  6248. } else {
  6249. 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';
  6250. }
  6251. }
  6252. });
  6253. }
  6254. function switchDynSubTab(subTab) {
  6255. if (subTab.startsWith('bgp')) {
  6256. if (state.activeTab !== 'bgp') navigate('bgp');
  6257. switchBgpSubTab(subTab);
  6258. } else if (subTab.startsWith('ospf')) {
  6259. if (state.activeTab !== 'ospf') navigate('ospf');
  6260. switchOspfSubTab(subTab);
  6261. }
  6262. }
  6263. async function loadDynamicRouting(showToastMsg = false) {
  6264. try {
  6265. const fetchSafeJson = async (url) => {
  6266. try {
  6267. const r = await fetch(url);
  6268. return r.ok ? await r.json() : null;
  6269. } catch (e) {
  6270. return null;
  6271. }
  6272. };
  6273. const [sum, bgpInst, bgpPeers, bgpNets, bgpRoutes, ospfInst, ospfIfaces, ospfAreas, ospfNbrs, ospfRoutes, filters] = await Promise.all([
  6274. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  6275. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  6276. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  6277. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  6278. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  6279. fetchSafeJson(`${API_BASE}/routing/ospf/instance`),
  6280. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces`),
  6281. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  6282. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  6283. fetchSafeJson(`${API_BASE}/routing/ospf/routes`),
  6284. fetchSafeJson(`${API_BASE}/routing/filters`)
  6285. ]);
  6286. if (sum) state.dynSummary = sum;
  6287. if (bgpInst) state.bgpInstance = bgpInst;
  6288. if (bgpPeers) state.bgpPeers = bgpPeers;
  6289. if (bgpNets) state.bgpNets = bgpNets;
  6290. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  6291. if (ospfInst) state.ospfInstance = ospfInst;
  6292. if (ospfIfaces) state.ospfInterfaces = ospfIfaces;
  6293. if (ospfAreas) state.ospfAreas = ospfAreas;
  6294. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  6295. if (ospfRoutes) state.ospfRoutes = ospfRoutes;
  6296. if (filters) state.routingFilters = filters;
  6297. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  6298. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  6299. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  6300. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  6301. try { renderOspfStatusPill(); } catch(e) { console.error('renderOspfStatusPill error:', e); }
  6302. try { renderOspfInterfaces(); } catch(e) { console.error('renderOspfInterfaces error:', e); }
  6303. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  6304. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  6305. try { renderOspfRoutes(); } catch(e) { console.error('renderOspfRoutes error:', e); }
  6306. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  6307. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  6308. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  6309. } catch (err) {
  6310. console.error('Failed to load dynamic routing:', err);
  6311. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  6312. }
  6313. }
  6314. function renderBgpStatusPill() {
  6315. const pill = document.getElementById('bgp-live-status-pill');
  6316. if (!pill) return;
  6317. const inst = state.bgpInstance;
  6318. if (!inst || !inst.enabled) {
  6319. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  6320. pill.innerText = 'BGP DISABLED';
  6321. } else if (inst.running) {
  6322. 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';
  6323. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  6324. } else {
  6325. 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';
  6326. pill.innerText = 'BGP STARTING...';
  6327. }
  6328. }
  6329. function renderBgpPeers() {
  6330. const tbody = document.getElementById('bgp-peers-table-body');
  6331. if (!tbody) return;
  6332. const empty = document.getElementById('bgp-peers-empty');
  6333. const countBadge = document.getElementById('bgp-peers-count-badge');
  6334. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  6335. const peers = state.bgpPeers || [];
  6336. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  6337. if (navBadge) navBadge.innerText = peers.length;
  6338. if (peers.length === 0) {
  6339. tbody.innerHTML = '';
  6340. if (empty) empty.classList.remove('hidden');
  6341. return;
  6342. }
  6343. if (empty) empty.classList.add('hidden');
  6344. tbody.innerHTML = peers.map(p => {
  6345. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  6346. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  6347. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  6348. let stateBadge = '';
  6349. if (p.disabled) {
  6350. 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>';
  6351. } else if (p.state === 'Established') {
  6352. 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>';
  6353. } else if (p.state === 'Connect' || p.state === 'Active') {
  6354. 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>`;
  6355. } else {
  6356. 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>`;
  6357. }
  6358. return `
  6359. <tr class="hover:bg-slate-800/40 transition">
  6360. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  6361. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  6362. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  6363. <td class="py-2.5 px-3 font-bold text-slate-200">AS ${p.remote_as}</td>
  6364. <td class="py-2.5 px-3">${stateBadge}</td>
  6365. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  6366. <td class="py-2.5 px-3 text-slate-300">
  6367. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  6368. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  6369. </td>
  6370. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  6371. ${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> ` : ''}
  6372. ${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>` : ''}
  6373. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  6374. </td>
  6375. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  6376. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  6377. <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'}">
  6378. ${p.disabled ? 'Enable' : 'Disable'}
  6379. </button>
  6380. <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">
  6381. Edit
  6382. </button>
  6383. <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">
  6384. Delete
  6385. </button>
  6386. </td>
  6387. </tr>
  6388. `;
  6389. }).join('');
  6390. }
  6391. function renderBgpNetworks() {
  6392. const tbody = document.getElementById('bgp-nets-table-body');
  6393. if (!tbody) return;
  6394. const empty = document.getElementById('bgp-nets-empty');
  6395. const countBadge = document.getElementById('bgp-nets-count-badge');
  6396. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  6397. const nets = state.bgpNets || [];
  6398. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  6399. if (navBadge) navBadge.innerText = nets.length;
  6400. if (nets.length === 0) {
  6401. tbody.innerHTML = '';
  6402. if (empty) empty.classList.remove('hidden');
  6403. return;
  6404. }
  6405. if (empty) empty.classList.add('hidden');
  6406. tbody.innerHTML = nets.map(n => `
  6407. <tr class="hover:bg-slate-800/40 transition">
  6408. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  6409. <td class="py-2.5 px-3">
  6410. ${n.disabled
  6411. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  6412. : '<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>'}
  6413. </td>
  6414. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  6415. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  6416. <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">
  6417. Delete
  6418. </button>
  6419. </td>
  6420. </tr>
  6421. `).join('');
  6422. }
  6423. function renderBgpRoutes() {
  6424. const tbody = document.getElementById('bgp-routes-table-body');
  6425. if (!tbody) return;
  6426. const empty = document.getElementById('bgp-routes-empty');
  6427. const countBadge = document.getElementById('bgp-routes-count-badge');
  6428. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  6429. const routes = state.bgpRoutes || [];
  6430. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  6431. if (navBadge) navBadge.innerText = routes.length;
  6432. if (routes.length === 0) {
  6433. tbody.innerHTML = '';
  6434. if (empty) empty.classList.remove('hidden');
  6435. return;
  6436. }
  6437. if (empty) empty.classList.add('hidden');
  6438. tbody.innerHTML = routes.map(r => `
  6439. <tr class="hover:bg-slate-800/40 transition">
  6440. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  6441. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  6442. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  6443. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  6444. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  6445. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  6446. </tr>
  6447. `).join('');
  6448. }
  6449. function renderOspfStatusPill() {
  6450. const pill = document.getElementById('ospf-live-status-pill');
  6451. if (!pill) return;
  6452. const inst = state.ospfInstance;
  6453. if (!inst || !inst.enabled) {
  6454. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  6455. pill.innerText = 'OSPF DISABLED';
  6456. } else if (inst.running) {
  6457. 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';
  6458. pill.innerText = `OSPF ACTIVE (ID: ${inst.router_id || 'Auto'})`;
  6459. } else {
  6460. 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';
  6461. pill.innerText = 'OSPF STARTING...';
  6462. }
  6463. }
  6464. function renderOspfInterfaces() {
  6465. const tbody = document.getElementById('ospf-ifaces-table-body');
  6466. if (!tbody) return;
  6467. const empty = document.getElementById('ospf-ifaces-empty');
  6468. const countBadge = document.getElementById('ospf-ifaces-count-badge');
  6469. const navBadge = document.getElementById('dyn-badge-ospf-ifaces');
  6470. const ifaces = state.ospfInterfaces || [];
  6471. if (countBadge) countBadge.innerText = `${ifaces.length} Interfaces`;
  6472. if (navBadge) navBadge.innerText = ifaces.length;
  6473. if (ifaces.length === 0) {
  6474. tbody.innerHTML = '';
  6475. if (empty) empty.classList.remove('hidden');
  6476. return;
  6477. }
  6478. if (empty) empty.classList.add('hidden');
  6479. tbody.innerHTML = ifaces.map(i => {
  6480. let flagA = !i.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  6481. let flagP = i.passive ? '<span class="text-amber-400 font-bold ml-1" title="Passive">P</span>' : '';
  6482. let flagX = i.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  6483. return `
  6484. <tr class="hover:bg-slate-800/40 transition">
  6485. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagP}${flagX}</td>
  6486. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(i.network)}</td>
  6487. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(i.area)}</td>
  6488. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(i.interface || 'Any')}</td>
  6489. <td class="py-2.5 px-3 text-slate-300">${i.cost}</td>
  6490. <td class="py-2.5 px-3 text-slate-300">${i.priority}</td>
  6491. <td class="py-2.5 px-3 text-slate-400">${i.hello_interval}s / ${i.dead_interval}s</td>
  6492. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(i.auth_type || 'none')}</td>
  6493. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(i.comment || '')}</td>
  6494. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  6495. <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'}">
  6496. ${i.disabled ? 'Enable' : 'Disable'}
  6497. </button>
  6498. <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">
  6499. Edit
  6500. </button>
  6501. <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">
  6502. Delete
  6503. </button>
  6504. </td>
  6505. </tr>
  6506. `;
  6507. }).join('');
  6508. }
  6509. function renderOspfAreas() {
  6510. const tbody = document.getElementById('ospf-areas-table-body');
  6511. if (!tbody) return;
  6512. const countBadge = document.getElementById('ospf-areas-count-badge');
  6513. const navBadge = document.getElementById('dyn-badge-ospf-areas');
  6514. const areas = state.ospfAreas || [];
  6515. if (countBadge) countBadge.innerText = `${areas.length} Areas`;
  6516. if (navBadge) navBadge.innerText = areas.length;
  6517. tbody.innerHTML = areas.map(a => `
  6518. <tr class="hover:bg-slate-800/40 transition">
  6519. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(a.name)}</td>
  6520. <td class="py-2.5 px-3 font-bold text-indigo-300">${escapeHtml(a.area_id)}</td>
  6521. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(a.area_type || 'default')}</td>
  6522. <td class="py-2.5 px-3 text-slate-400 font-sans">${escapeHtml(a.comment || '')}</td>
  6523. <td class="py-2.5 px-3 text-right font-sans">
  6524. <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">
  6525. Delete
  6526. </button>
  6527. </td>
  6528. </tr>
  6529. `).join('');
  6530. }
  6531. function renderOspfNeighbors() {
  6532. const tbody = document.getElementById('ospf-nbrs-table-body');
  6533. if (!tbody) return;
  6534. const empty = document.getElementById('ospf-nbrs-empty');
  6535. const countBadge = document.getElementById('ospf-nbrs-count-badge');
  6536. const navBadge = document.getElementById('dyn-badge-ospf-nbrs');
  6537. const nbrs = state.ospfNeighbors || [];
  6538. if (countBadge) countBadge.innerText = `${nbrs.length} Neighbors`;
  6539. if (navBadge) navBadge.innerText = nbrs.length;
  6540. if (nbrs.length === 0) {
  6541. tbody.innerHTML = '';
  6542. if (empty) empty.classList.remove('hidden');
  6543. return;
  6544. }
  6545. if (empty) empty.classList.add('hidden');
  6546. tbody.innerHTML = nbrs.map(n => {
  6547. let stateBadge = '';
  6548. if (n.state && (n.state.startsWith('Full') || n.state.includes('DR') || n.state.includes('Backup'))) {
  6549. 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>`;
  6550. } else {
  6551. 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>`;
  6552. }
  6553. return `
  6554. <tr class="hover:bg-slate-800/40 transition">
  6555. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(n.neighbor_id)}</td>
  6556. <td class="py-2.5 px-3 text-indigo-300 font-bold">${escapeHtml(n.address)}</td>
  6557. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(n.interface)}</td>
  6558. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.area || '0.0.0.0')}</td>
  6559. <td class="py-2.5 px-3">${stateBadge}</td>
  6560. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.dead_timer || '-')}</td>
  6561. </tr>
  6562. `;
  6563. }).join('');
  6564. }
  6565. function renderOspfRoutes() {
  6566. const tbody = document.getElementById('ospf-routes-table-body');
  6567. if (!tbody) return;
  6568. const empty = document.getElementById('ospf-routes-empty');
  6569. const countBadge = document.getElementById('ospf-routes-count-badge');
  6570. const navBadge = document.getElementById('dyn-badge-ospf-routes');
  6571. const routes = state.ospfRoutes || [];
  6572. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  6573. if (navBadge) navBadge.innerText = routes.length;
  6574. if (routes.length === 0) {
  6575. tbody.innerHTML = '';
  6576. if (empty) empty.classList.remove('hidden');
  6577. return;
  6578. }
  6579. if (empty) empty.classList.add('hidden');
  6580. tbody.innerHTML = routes.map(r => `
  6581. <tr class="hover:bg-slate-800/40 transition">
  6582. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(r.prefix)}</td>
  6583. <td class="py-2.5 px-3 text-slate-300">${escapeHtml(r.route_type || 'Network')}</td>
  6584. <td class="py-2.5 px-3 text-slate-300">${r.cost}</td>
  6585. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(r.area || '0.0.0.0')}</td>
  6586. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(r.next_hop || r.interface || '-')}</td>
  6587. </tr>
  6588. `).join('');
  6589. }
  6590. // BGP Modals & Actions
  6591. function openBgpInstanceModal() {
  6592. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  6593. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  6594. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  6595. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  6596. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  6597. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  6598. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  6599. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  6600. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  6601. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  6602. }
  6603. function closeBgpInstanceModal() {
  6604. document.getElementById('bgp-instance-modal').classList.add('hidden');
  6605. }
  6606. async function submitBgpInstance(e) {
  6607. e.preventDefault();
  6608. const payload = {
  6609. enabled: document.getElementById('modal-bgp-enabled').checked,
  6610. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  6611. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  6612. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  6613. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  6614. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  6615. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  6616. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  6617. };
  6618. try {
  6619. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  6620. method: 'POST',
  6621. headers: { 'Content-Type': 'application/json' },
  6622. body: JSON.stringify(payload)
  6623. });
  6624. if (res.ok) {
  6625. closeBgpInstanceModal();
  6626. showToast('Success', 'BGP instance configuration updated', 'success');
  6627. loadDynamicRouting();
  6628. } else {
  6629. const err = await res.json();
  6630. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  6631. }
  6632. } catch (err) {
  6633. showToast('Error', err.message, 'error');
  6634. }
  6635. }
  6636. function openAddBgpPeerModal() {
  6637. document.getElementById('bgp-peer-form').reset();
  6638. document.getElementById('modal-bgp-peer-id').value = '';
  6639. document.getElementById('bgp-peer-modal-title').innerText = 'Add BGP Peer Connection';
  6640. document.getElementById('modal-bgp-peer-nexthop-self').checked = true;
  6641. const inFilterEl = document.getElementById('modal-bgp-peer-in-filter');
  6642. if (inFilterEl) inFilterEl.value = '';
  6643. const outFilterEl = document.getElementById('modal-bgp-peer-out-filter');
  6644. if (outFilterEl) outFilterEl.value = '';
  6645. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  6646. }
  6647. function openEditBgpPeerModal(id) {
  6648. const p = (state.bgpPeers || []).find(item => item.id === id);
  6649. if (!p) return;
  6650. document.getElementById('modal-bgp-peer-id').value = p.id;
  6651. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  6652. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  6653. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  6654. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  6655. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  6656. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  6657. document.getElementById('modal-bgp-peer-nexthop-self').checked = !!p.nexthop_self;
  6658. document.getElementById('modal-bgp-peer-passive').checked = !!p.passive;
  6659. document.getElementById('modal-bgp-peer-disabled').checked = !!p.disabled;
  6660. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  6661. const inFilterEl = document.getElementById('modal-bgp-peer-in-filter');
  6662. if (inFilterEl) inFilterEl.value = p.in_filter || '';
  6663. const outFilterEl = document.getElementById('modal-bgp-peer-out-filter');
  6664. if (outFilterEl) outFilterEl.value = p.out_filter || '';
  6665. document.getElementById('bgp-peer-modal-title').innerText = 'Edit BGP Peer Connection';
  6666. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  6667. }
  6668. function closeBgpPeerModal() {
  6669. document.getElementById('bgp-peer-modal').classList.add('hidden');
  6670. }
  6671. async function submitBgpPeer(e) {
  6672. e.preventDefault();
  6673. const payload = {
  6674. id: document.getElementById('modal-bgp-peer-id').value,
  6675. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  6676. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  6677. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10),
  6678. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  6679. password: document.getElementById('modal-bgp-peer-password').value,
  6680. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  6681. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-self').checked,
  6682. passive: document.getElementById('modal-bgp-peer-passive').checked,
  6683. disabled: document.getElementById('modal-bgp-peer-disabled').checked,
  6684. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  6685. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  6686. comment: document.getElementById('modal-bgp-peer-comment').value.trim()
  6687. };
  6688. try {
  6689. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  6690. method: 'POST',
  6691. headers: { 'Content-Type': 'application/json' },
  6692. body: JSON.stringify(payload)
  6693. });
  6694. if (res.ok) {
  6695. closeBgpPeerModal();
  6696. showToast('Success', 'BGP Peer saved', 'success');
  6697. loadDynamicRouting();
  6698. } else {
  6699. const err = await res.json();
  6700. showToast('Error', err.error || 'Failed to save peer', 'error');
  6701. }
  6702. } catch (err) {
  6703. showToast('Error', err.message, 'error');
  6704. }
  6705. }
  6706. async function deleteBgpPeer(id) {
  6707. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  6708. try {
  6709. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6710. if (res.ok) {
  6711. showToast('Deleted', 'BGP peer removed', 'success');
  6712. loadDynamicRouting();
  6713. }
  6714. } catch (err) {
  6715. showToast('Error', err.message, 'error');
  6716. }
  6717. }
  6718. async function toggleBgpPeerState(id, disabled) {
  6719. try {
  6720. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  6721. method: 'POST',
  6722. headers: { 'Content-Type': 'application/json' },
  6723. body: JSON.stringify({ disabled })
  6724. });
  6725. if (res.ok) {
  6726. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  6727. loadDynamicRouting();
  6728. }
  6729. } catch (err) {
  6730. showToast('Error', err.message, 'error');
  6731. }
  6732. }
  6733. function openAddBgpNetworkModal() {
  6734. document.getElementById('bgp-network-form').reset();
  6735. document.getElementById('modal-bgp-net-id').value = '';
  6736. document.getElementById('bgp-network-modal').classList.remove('hidden');
  6737. }
  6738. function closeBgpNetworkModal() {
  6739. document.getElementById('bgp-network-modal').classList.add('hidden');
  6740. }
  6741. async function submitBgpNetwork(e) {
  6742. e.preventDefault();
  6743. const payload = {
  6744. id: document.getElementById('modal-bgp-net-id').value,
  6745. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  6746. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  6747. disabled: document.getElementById('modal-bgp-net-disabled').checked
  6748. };
  6749. try {
  6750. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  6751. method: 'POST',
  6752. headers: { 'Content-Type': 'application/json' },
  6753. body: JSON.stringify(payload)
  6754. });
  6755. if (res.ok) {
  6756. closeBgpNetworkModal();
  6757. showToast('Success', 'BGP network advertisement saved', 'success');
  6758. loadDynamicRouting();
  6759. } else {
  6760. const err = await res.json();
  6761. showToast('Error', err.error || 'Failed to save network', 'error');
  6762. }
  6763. } catch (err) {
  6764. showToast('Error', err.message, 'error');
  6765. }
  6766. }
  6767. async function deleteBgpNetwork(id) {
  6768. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  6769. try {
  6770. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6771. if (res.ok) {
  6772. showToast('Deleted', 'Network advertisement removed', 'success');
  6773. loadDynamicRouting();
  6774. }
  6775. } catch (err) {
  6776. showToast('Error', err.message, 'error');
  6777. }
  6778. }
  6779. // OSPF Modals & Actions
  6780. function openOspfInstanceModal() {
  6781. const inst = state.ospfInstance || { enabled: false, router_id: '192.168.131.56', default_metric: 10 };
  6782. document.getElementById('modal-ospf-enabled').checked = !!inst.enabled;
  6783. document.getElementById('modal-ospf-router-id').value = inst.router_id || '';
  6784. document.getElementById('modal-ospf-metric').value = inst.default_metric || 10;
  6785. document.getElementById('modal-ospf-redist-conn').checked = !!inst.redistribute_connected;
  6786. document.getElementById('modal-ospf-redist-static').checked = !!inst.redistribute_static;
  6787. document.getElementById('modal-ospf-redist-bgp').checked = !!inst.redistribute_bgp;
  6788. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  6789. }
  6790. function closeOspfInstanceModal() {
  6791. document.getElementById('ospf-instance-modal').classList.add('hidden');
  6792. }
  6793. async function submitOspfInstance(e) {
  6794. e.preventDefault();
  6795. const payload = {
  6796. enabled: document.getElementById('modal-ospf-enabled').checked,
  6797. router_id: document.getElementById('modal-ospf-router-id').value.trim(),
  6798. default_metric: parseInt(document.getElementById('modal-ospf-metric').value, 10),
  6799. redistribute_connected: document.getElementById('modal-ospf-redist-conn').checked,
  6800. redistribute_static: document.getElementById('modal-ospf-redist-static').checked,
  6801. redistribute_bgp: document.getElementById('modal-ospf-redist-bgp').checked
  6802. };
  6803. try {
  6804. const res = await fetch(`${API_BASE}/routing/ospf/instance`, {
  6805. method: 'POST',
  6806. headers: { 'Content-Type': 'application/json' },
  6807. body: JSON.stringify(payload)
  6808. });
  6809. if (res.ok) {
  6810. closeOspfInstanceModal();
  6811. showToast('Success', 'OSPF instance configuration updated', 'success');
  6812. loadDynamicRouting();
  6813. } else {
  6814. const err = await res.json();
  6815. showToast('Error', err.error || 'Failed to update OSPF instance', 'error');
  6816. }
  6817. } catch (err) {
  6818. showToast('Error', err.message, 'error');
  6819. }
  6820. }
  6821. function openAddOspfAreaModal() {
  6822. document.getElementById('ospf-area-form').reset();
  6823. document.getElementById('modal-ospf-area-id').value = '';
  6824. document.getElementById('modal-ospf-area-areaid').value = '0.0.0.0';
  6825. document.getElementById('ospf-area-modal').classList.remove('hidden');
  6826. }
  6827. function closeOspfAreaModal() {
  6828. document.getElementById('ospf-area-modal').classList.add('hidden');
  6829. }
  6830. async function submitOspfArea(e) {
  6831. e.preventDefault();
  6832. const payload = {
  6833. id: document.getElementById('modal-ospf-area-id').value,
  6834. name: document.getElementById('modal-ospf-area-name').value.trim(),
  6835. area_id: document.getElementById('modal-ospf-area-areaid').value.trim(),
  6836. area_type: document.getElementById('modal-ospf-area-type').value,
  6837. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  6838. };
  6839. try {
  6840. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  6841. method: 'POST',
  6842. headers: { 'Content-Type': 'application/json' },
  6843. body: JSON.stringify(payload)
  6844. });
  6845. if (res.ok) {
  6846. closeOspfAreaModal();
  6847. showToast('Success', 'OSPF area saved', 'success');
  6848. loadDynamicRouting();
  6849. } else {
  6850. const err = await res.json();
  6851. showToast('Error', err.error || 'Failed to save area', 'error');
  6852. }
  6853. } catch (err) {
  6854. showToast('Error', err.message, 'error');
  6855. }
  6856. }
  6857. async function deleteOspfArea(id) {
  6858. if (!confirm('Are you sure you want to delete this OSPF area?')) return;
  6859. try {
  6860. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6861. if (res.ok) {
  6862. showToast('Deleted', 'OSPF area removed', 'success');
  6863. loadDynamicRouting();
  6864. }
  6865. } catch (err) {
  6866. showToast('Error', err.message, 'error');
  6867. }
  6868. }
  6869. function populateOspfInterfaceDevices() {
  6870. const select = document.getElementById('modal-ospf-iface-device');
  6871. if (!select) return;
  6872. const current = select.value;
  6873. select.innerHTML = '<option value="">Any matching interface</option>';
  6874. (state.interfaces || []).forEach(iface => {
  6875. select.innerHTML += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)} (${iface.type})</option>`;
  6876. });
  6877. if (current) select.value = current;
  6878. }
  6879. function openAddOspfInterfaceModal() {
  6880. document.getElementById('ospf-interface-form').reset();
  6881. document.getElementById('modal-ospf-iface-id').value = '';
  6882. document.getElementById('modal-ospf-iface-area').value = '0.0.0.0';
  6883. document.getElementById('modal-ospf-iface-cost').value = '10';
  6884. document.getElementById('modal-ospf-iface-priority').value = '1';
  6885. document.getElementById('modal-ospf-iface-hello').value = '10';
  6886. document.getElementById('modal-ospf-iface-dead').value = '40';
  6887. document.getElementById('ospf-interface-modal-title').innerText = 'Add OSPF Interface';
  6888. populateOspfInterfaceDevices();
  6889. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  6890. }
  6891. function openEditOspfInterfaceModal(id) {
  6892. const item = (state.ospfInterfaces || []).find(i => i.id === id);
  6893. if (!item) return;
  6894. populateOspfInterfaceDevices();
  6895. document.getElementById('modal-ospf-iface-id').value = item.id;
  6896. document.getElementById('modal-ospf-iface-net').value = item.network || '';
  6897. document.getElementById('modal-ospf-iface-area').value = item.area || '0.0.0.0';
  6898. document.getElementById('modal-ospf-iface-device').value = item.interface || '';
  6899. document.getElementById('modal-ospf-iface-cost').value = item.cost || 10;
  6900. document.getElementById('modal-ospf-iface-priority').value = item.priority || 1;
  6901. document.getElementById('modal-ospf-iface-hello').value = item.hello_interval || 10;
  6902. document.getElementById('modal-ospf-iface-dead').value = item.dead_interval || 40;
  6903. document.getElementById('modal-ospf-iface-auth-type').value = item.auth_type || 'none';
  6904. document.getElementById('modal-ospf-iface-auth-key').value = item.auth_key || '';
  6905. document.getElementById('modal-ospf-iface-passive').checked = !!item.passive;
  6906. document.getElementById('modal-ospf-iface-disabled').checked = !!item.disabled;
  6907. document.getElementById('modal-ospf-iface-comment').value = item.comment || '';
  6908. document.getElementById('ospf-interface-modal-title').innerText = 'Edit OSPF Interface';
  6909. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  6910. }
  6911. function closeOspfInterfaceModal() {
  6912. document.getElementById('ospf-interface-modal').classList.add('hidden');
  6913. }
  6914. async function submitOspfInterface(e) {
  6915. e.preventDefault();
  6916. const payload = {
  6917. id: document.getElementById('modal-ospf-iface-id').value,
  6918. network: document.getElementById('modal-ospf-iface-net').value.trim(),
  6919. area: document.getElementById('modal-ospf-iface-area').value.trim(),
  6920. interface: document.getElementById('modal-ospf-iface-device').value,
  6921. cost: parseInt(document.getElementById('modal-ospf-iface-cost').value, 10),
  6922. priority: parseInt(document.getElementById('modal-ospf-iface-priority').value, 10),
  6923. hello_interval: parseInt(document.getElementById('modal-ospf-iface-hello').value, 10),
  6924. dead_interval: parseInt(document.getElementById('modal-ospf-iface-dead').value, 10),
  6925. auth_type: document.getElementById('modal-ospf-iface-auth-type').value,
  6926. auth_key: document.getElementById('modal-ospf-iface-auth-key').value,
  6927. passive: document.getElementById('modal-ospf-iface-passive').checked,
  6928. disabled: document.getElementById('modal-ospf-iface-disabled').checked,
  6929. comment: document.getElementById('modal-ospf-iface-comment').value.trim()
  6930. };
  6931. try {
  6932. const res = await fetch(`${API_BASE}/routing/ospf/interfaces`, {
  6933. method: 'POST',
  6934. headers: { 'Content-Type': 'application/json' },
  6935. body: JSON.stringify(payload)
  6936. });
  6937. if (res.ok) {
  6938. closeOspfInterfaceModal();
  6939. showToast('Success', 'OSPF interface template saved', 'success');
  6940. loadDynamicRouting();
  6941. } else {
  6942. const err = await res.json();
  6943. showToast('Error', err.error || 'Failed to save interface', 'error');
  6944. }
  6945. } catch (err) {
  6946. showToast('Error', err.message, 'error');
  6947. }
  6948. }
  6949. async function deleteOspfInterface(id) {
  6950. if (!confirm('Are you sure you want to delete this OSPF interface?')) return;
  6951. try {
  6952. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6953. if (res.ok) {
  6954. showToast('Deleted', 'OSPF interface removed', 'success');
  6955. loadDynamicRouting();
  6956. }
  6957. } catch (err) {
  6958. showToast('Error', err.message, 'error');
  6959. }
  6960. }
  6961. async function toggleOspfInterfaceState(id, disabled) {
  6962. try {
  6963. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}/state`, {
  6964. method: 'POST',
  6965. headers: { 'Content-Type': 'application/json' },
  6966. body: JSON.stringify({ disabled })
  6967. });
  6968. if (res.ok) {
  6969. showToast('Updated', `Interface ${disabled ? 'disabled' : 'enabled'}`, 'success');
  6970. loadDynamicRouting();
  6971. }
  6972. } catch (err) {
  6973. showToast('Error', err.message, 'error');
  6974. }
  6975. }
  6976. // ============================================================================
  6977. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  6978. // ============================================================================
  6979. function switchBridgeSubTab(tab) {
  6980. state.bridgeSubTab = tab;
  6981. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  6982. tabs.forEach(t => {
  6983. const panel = document.getElementById(`bridge-subtab-${t}`);
  6984. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  6985. if (panel) {
  6986. if (t === tab) panel.classList.remove('hidden');
  6987. else panel.classList.add('hidden');
  6988. }
  6989. if (btn) {
  6990. if (t === tab) {
  6991. 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';
  6992. } else {
  6993. 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';
  6994. }
  6995. }
  6996. });
  6997. const addBtn = document.getElementById('bridge-top-action-btn');
  6998. if (addBtn) {
  6999. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  7000. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  7001. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  7002. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  7003. }
  7004. if (tab === 'hosts') loadBridgeHosts();
  7005. setTimeout(initTableSorting, 50);
  7006. }
  7007. function openCurrentBridgeModal() {
  7008. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  7009. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  7010. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  7011. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  7012. }
  7013. async function loadBridge() {
  7014. try {
  7015. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  7016. fetch(`${API_BASE}/bridge/bridges`),
  7017. fetch(`${API_BASE}/bridge/ports`),
  7018. fetch(`${API_BASE}/bridge/vlans`),
  7019. fetch(`${API_BASE}/bridge/summary`),
  7020. fetch(`${API_BASE}/vpn/eoip`),
  7021. fetch(`${API_BASE}/vlans`)
  7022. ]);
  7023. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  7024. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  7025. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  7026. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  7027. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  7028. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  7029. // Badges & Stats
  7030. const bBridges = document.getElementById('bridge-badge-bridges');
  7031. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  7032. const bPorts = document.getElementById('bridge-badge-ports');
  7033. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  7034. const bVlans = document.getElementById('bridge-badge-vlans');
  7035. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  7036. const bHosts = document.getElementById('bridge-badge-hosts');
  7037. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  7038. const sBr = document.getElementById('bridge-stat-bridges');
  7039. if (sBr) sBr.innerText = (state.bridges || []).length;
  7040. const sPorts = document.getElementById('bridge-stat-ports');
  7041. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  7042. const sHosts = document.getElementById('bridge-stat-hosts');
  7043. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  7044. renderBridges();
  7045. renderBridgePorts();
  7046. renderBridgeVLANs();
  7047. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  7048. } catch (err) {
  7049. console.error('Failed to load bridge subsystem:', err);
  7050. }
  7051. }
  7052. // ----------------- Bridges -----------------
  7053. function renderBridges() {
  7054. const tbody = document.getElementById('bridge-table-body');
  7055. const empty = document.getElementById('bridge-empty-bridges');
  7056. const countBadge = document.getElementById('bridge-count-badge');
  7057. if (!tbody) return;
  7058. tbody.innerHTML = '';
  7059. const bridges = state.bridges || [];
  7060. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  7061. if (bridges.length === 0) {
  7062. empty?.classList.remove('hidden');
  7063. return;
  7064. }
  7065. empty?.classList.add('hidden');
  7066. bridges.forEach((b, idx) => {
  7067. const tr = document.createElement('tr');
  7068. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  7069. // Format IP addresses pill list
  7070. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  7071. if (b.ip_addresses && b.ip_addresses.length > 0) {
  7072. ipsHtml = b.ip_addresses.map(ip => `
  7073. <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">
  7074. <span>${ip}</span>
  7075. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  7076. </span>
  7077. `).join(' ');
  7078. }
  7079. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  7080. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  7081. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  7082. tr.innerHTML = `
  7083. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  7084. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  7085. <td class="py-2.5 px-3 font-bold text-white text-sm">
  7086. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  7087. </td>
  7088. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  7089. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  7090. <td class="py-2.5 px-3">
  7091. <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>
  7092. </td>
  7093. <td class="py-2.5 px-3 text-center">
  7094. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  7095. </td>
  7096. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  7097. <td class="py-2.5 px-3">
  7098. <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>
  7099. </td>
  7100. <td class="py-2.5 px-3">
  7101. <div class="flex items-center gap-1.5 flex-wrap">
  7102. ${ipsHtml}
  7103. <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>
  7104. </div>
  7105. </td>
  7106. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  7107. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  7108. </td>
  7109. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  7110. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7111. <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>
  7112. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7113. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  7114. </td>
  7115. `;
  7116. tbody.appendChild(tr);
  7117. });
  7118. }
  7119. function openAddBridgeModal() {
  7120. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  7121. document.getElementById('bridge-modal-id').value = '';
  7122. document.getElementById('bridge-modal-name').value = 'bridge1';
  7123. document.getElementById('bridge-modal-name').disabled = false;
  7124. document.getElementById('bridge-modal-mtu').value = '1500';
  7125. document.getElementById('bridge-modal-mac').value = '';
  7126. document.getElementById('bridge-modal-stp').value = 'rstp';
  7127. document.getElementById('bridge-modal-priority').value = '32768';
  7128. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  7129. document.getElementById('bridge-modal-pvid').value = '1';
  7130. document.getElementById('bridge-modal-fastforward').checked = true;
  7131. document.getElementById('bridge-modal-comment').value = '';
  7132. document.getElementById('bridge-modal-disabled').checked = false;
  7133. toggleBridgeModalVlanFiltering();
  7134. document.getElementById('bridge-modal').classList.remove('hidden');
  7135. }
  7136. function openEditBridgeModal(id) {
  7137. const b = (state.bridges || []).find(x => x.id === id);
  7138. if (!b) return;
  7139. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  7140. document.getElementById('bridge-modal-id').value = b.id;
  7141. document.getElementById('bridge-modal-name').value = b.name;
  7142. document.getElementById('bridge-modal-name').disabled = true;
  7143. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  7144. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  7145. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  7146. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  7147. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  7148. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  7149. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  7150. document.getElementById('bridge-modal-comment').value = b.comment || '';
  7151. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  7152. toggleBridgeModalVlanFiltering();
  7153. document.getElementById('bridge-modal').classList.remove('hidden');
  7154. }
  7155. function closeBridgeModal() {
  7156. document.getElementById('bridge-modal').classList.add('hidden');
  7157. }
  7158. function toggleBridgeModalVlanFiltering() {
  7159. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  7160. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  7161. if (pvidBox) {
  7162. if (chk) pvidBox.classList.remove('opacity-40');
  7163. else pvidBox.classList.add('opacity-40');
  7164. }
  7165. }
  7166. async function submitSaveBridge(e) {
  7167. e.preventDefault();
  7168. const id = document.getElementById('bridge-modal-id').value;
  7169. const name = document.getElementById('bridge-modal-name').value.trim();
  7170. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  7171. const mac = document.getElementById('bridge-modal-mac').value.trim();
  7172. const stp = document.getElementById('bridge-modal-stp').value;
  7173. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  7174. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  7175. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  7176. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  7177. const comment = document.getElementById('bridge-modal-comment').value.trim();
  7178. const disabled = document.getElementById('bridge-modal-disabled').checked;
  7179. try {
  7180. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  7181. method: 'POST',
  7182. headers: { 'Content-Type': 'application/json' },
  7183. body: JSON.stringify({
  7184. id,
  7185. name,
  7186. mtu,
  7187. mac_address: mac,
  7188. stp,
  7189. priority,
  7190. vlan_filtering: vlanFiltering,
  7191. pvid,
  7192. fast_forward: fastForward,
  7193. comment,
  7194. disabled
  7195. })
  7196. });
  7197. if (res.ok) {
  7198. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  7199. closeBridgeModal();
  7200. loadBridge();
  7201. fetchData(false);
  7202. } else {
  7203. const err = await res.json();
  7204. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  7205. }
  7206. } catch (err) {
  7207. showToast('Error', err.message, 'error');
  7208. }
  7209. }
  7210. async function toggleBridgeState(id, disabled) {
  7211. try {
  7212. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  7213. method: 'POST',
  7214. headers: { 'Content-Type': 'application/json' },
  7215. body: JSON.stringify({ disabled })
  7216. });
  7217. if (res.ok) {
  7218. loadBridge();
  7219. fetchData(false);
  7220. }
  7221. } catch (err) {
  7222. showToast('Error', err.message, 'error');
  7223. }
  7224. }
  7225. async function deleteBridge(id) {
  7226. const b = (state.bridges || []).find(x => x.id === id);
  7227. const name = b ? b.name : id;
  7228. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  7229. try {
  7230. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7231. if (res.ok) {
  7232. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  7233. loadBridge();
  7234. fetchData(false);
  7235. } else {
  7236. const err = await res.json();
  7237. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  7238. }
  7239. } catch (err) {
  7240. showToast('Error', err.message, 'error');
  7241. }
  7242. }
  7243. // ----------------- Bridge IP Assignments -----------------
  7244. function openAddBridgeIPModal(id, name) {
  7245. document.getElementById('bridge-ip-modal-id').value = id;
  7246. document.getElementById('bridge-ip-modal-sub').innerText = name;
  7247. document.getElementById('bridge-ip-modal-cidr').value = '';
  7248. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  7249. }
  7250. function closeBridgeIPModal() {
  7251. document.getElementById('bridge-ip-modal').classList.add('hidden');
  7252. }
  7253. async function submitAddBridgeIP(e) {
  7254. e.preventDefault();
  7255. const id = document.getElementById('bridge-ip-modal-id').value;
  7256. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  7257. try {
  7258. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  7259. method: 'POST',
  7260. headers: { 'Content-Type': 'application/json' },
  7261. body: JSON.stringify({ ip })
  7262. });
  7263. if (res.ok) {
  7264. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  7265. closeBridgeIPModal();
  7266. loadBridge();
  7267. fetchData(false);
  7268. } else {
  7269. const err = await res.json();
  7270. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  7271. }
  7272. } catch (err) {
  7273. showToast('Error', err.message, 'error');
  7274. }
  7275. }
  7276. async function deleteBridgeIP(id, ip) {
  7277. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  7278. try {
  7279. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  7280. method: 'DELETE',
  7281. headers: { 'Content-Type': 'application/json' },
  7282. body: JSON.stringify({ ip })
  7283. });
  7284. if (res.ok) {
  7285. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  7286. loadBridge();
  7287. fetchData(false);
  7288. }
  7289. } catch (err) {
  7290. showToast('Error', err.message, 'error');
  7291. }
  7292. }
  7293. // ----------------- Bridge Ports -----------------
  7294. function renderBridgePorts() {
  7295. const tbody = document.getElementById('bridge-ports-table-body');
  7296. const empty = document.getElementById('bridge-empty-ports');
  7297. const countBadge = document.getElementById('bridge-ports-count-badge');
  7298. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  7299. if (!tbody) return;
  7300. tbody.innerHTML = '';
  7301. // Update filter select
  7302. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  7303. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  7304. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  7305. if (ports.length === 0) {
  7306. empty?.classList.remove('hidden');
  7307. return;
  7308. }
  7309. empty?.classList.add('hidden');
  7310. ports.forEach((p, idx) => {
  7311. const tr = document.createElement('tr');
  7312. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  7313. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  7314. tr.innerHTML = `
  7315. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  7316. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  7317. <td class="py-2.5 px-3 font-bold text-white text-sm">
  7318. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  7319. </td>
  7320. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  7321. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  7322. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  7323. <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>
  7324. <td class="py-2.5 px-3">
  7325. ${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>'}
  7326. </td>
  7327. <td class="py-2.5 px-3">
  7328. <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>
  7329. </td>
  7330. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  7331. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7332. <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>
  7333. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7334. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  7335. </td>
  7336. `;
  7337. tbody.appendChild(tr);
  7338. });
  7339. }
  7340. function openAddBridgePortModal() {
  7341. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  7342. document.getElementById('bridge-port-modal-id').value = '';
  7343. populateBridgeSelect('bridge-port-modal-bridge');
  7344. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  7345. document.getElementById('bridge-port-modal-pvid').value = '1';
  7346. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  7347. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  7348. document.getElementById('bridge-port-modal-horizon').value = '0';
  7349. document.getElementById('bridge-port-modal-pathcost').value = '10';
  7350. document.getElementById('bridge-port-modal-priority').value = '128';
  7351. document.getElementById('bridge-port-modal-learn').checked = true;
  7352. document.getElementById('bridge-port-modal-comment').value = '';
  7353. document.getElementById('bridge-port-modal-disabled').checked = false;
  7354. document.getElementById('bridge-port-modal').classList.remove('hidden');
  7355. }
  7356. function openEditBridgePortModal(id) {
  7357. const p = (state.bridgePorts || []).find(x => x.id === id);
  7358. if (!p) return;
  7359. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  7360. document.getElementById('bridge-port-modal-id').value = p.id;
  7361. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  7362. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  7363. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  7364. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  7365. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  7366. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  7367. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  7368. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  7369. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  7370. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  7371. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  7372. document.getElementById('bridge-port-modal').classList.remove('hidden');
  7373. }
  7374. function closeBridgePortModal() {
  7375. document.getElementById('bridge-port-modal').classList.add('hidden');
  7376. }
  7377. async function submitSaveBridgePort(e) {
  7378. e.preventDefault();
  7379. const id = document.getElementById('bridge-port-modal-id').value;
  7380. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  7381. const iface = document.getElementById('bridge-port-modal-interface').value;
  7382. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  7383. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  7384. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  7385. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  7386. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  7387. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  7388. const learn = document.getElementById('bridge-port-modal-learn').checked;
  7389. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  7390. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  7391. try {
  7392. const res = await fetch(`${API_BASE}/bridge/ports`, {
  7393. method: 'POST',
  7394. headers: { 'Content-Type': 'application/json' },
  7395. body: JSON.stringify({
  7396. id,
  7397. bridge,
  7398. interface: iface,
  7399. pvid,
  7400. frame_types: frameTypes,
  7401. ingress_filtering: ingressFiltering,
  7402. horizon,
  7403. path_cost: pathCost,
  7404. priority,
  7405. learn,
  7406. comment,
  7407. disabled
  7408. })
  7409. });
  7410. if (res.ok) {
  7411. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  7412. closeBridgePortModal();
  7413. loadBridge();
  7414. fetchData(false);
  7415. } else {
  7416. const err = await res.json();
  7417. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  7418. }
  7419. } catch (err) {
  7420. showToast('Error', err.message, 'error');
  7421. }
  7422. }
  7423. async function toggleBridgePortState(id, disabled) {
  7424. try {
  7425. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  7426. method: 'POST',
  7427. headers: { 'Content-Type': 'application/json' },
  7428. body: JSON.stringify({ disabled })
  7429. });
  7430. if (res.ok) {
  7431. loadBridge();
  7432. fetchData(false);
  7433. }
  7434. } catch (err) {
  7435. showToast('Error', err.message, 'error');
  7436. }
  7437. }
  7438. async function deleteBridgePort(id) {
  7439. const p = (state.bridgePorts || []).find(x => x.id === id);
  7440. const iface = p ? p.interface : id;
  7441. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  7442. try {
  7443. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7444. if (res.ok) {
  7445. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  7446. loadBridge();
  7447. fetchData(false);
  7448. }
  7449. } catch (err) {
  7450. showToast('Error', err.message, 'error');
  7451. }
  7452. }
  7453. // ----------------- Bridge VLANs -----------------
  7454. function renderBridgeVLANs() {
  7455. const tbody = document.getElementById('bridge-vlans-table-body');
  7456. const empty = document.getElementById('bridge-empty-vlans');
  7457. const countBadge = document.getElementById('bridge-vlans-count-badge');
  7458. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  7459. if (!tbody) return;
  7460. tbody.innerHTML = '';
  7461. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  7462. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  7463. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  7464. if (vlans.length === 0) {
  7465. empty?.classList.remove('hidden');
  7466. return;
  7467. }
  7468. empty?.classList.add('hidden');
  7469. vlans.forEach((v, idx) => {
  7470. const tr = document.createElement('tr');
  7471. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  7472. const taggedHtml = (v.tagged && v.tagged.length > 0)
  7473. ? 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(' ')
  7474. : '<span class="text-slate-600">none</span>';
  7475. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  7476. ? 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(' ')
  7477. : '<span class="text-slate-600">none</span>';
  7478. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  7479. tr.innerHTML = `
  7480. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  7481. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  7482. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  7483. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  7484. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  7485. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  7486. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  7487. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7488. <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>
  7489. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7490. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  7491. </td>
  7492. `;
  7493. tbody.appendChild(tr);
  7494. });
  7495. }
  7496. function openAddBridgeVLANModal() {
  7497. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  7498. document.getElementById('bridge-vlan-modal-id').value = '';
  7499. populateBridgeSelect('bridge-vlan-modal-bridge');
  7500. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  7501. document.getElementById('bridge-vlan-modal-comment').value = '';
  7502. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  7503. updateBridgeVlanPortCheckboxes();
  7504. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  7505. }
  7506. function openEditBridgeVLANModal(id) {
  7507. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  7508. if (!v) return;
  7509. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  7510. document.getElementById('bridge-vlan-modal-id').value = v.id;
  7511. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  7512. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  7513. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  7514. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  7515. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  7516. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  7517. }
  7518. function closeBridgeVlanModal() {
  7519. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  7520. }
  7521. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  7522. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  7523. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  7524. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  7525. if (!taggedBox || !untaggedBox) return;
  7526. // Ports belonging to the selected bridge
  7527. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  7528. if (memberPorts.length === 0) {
  7529. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  7530. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  7531. return;
  7532. }
  7533. taggedBox.innerHTML = memberPorts.map(p => `
  7534. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  7535. <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">
  7536. <span>${p.interface}</span>
  7537. </label>
  7538. `).join('');
  7539. untaggedBox.innerHTML = memberPorts.map(p => `
  7540. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  7541. <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">
  7542. <span>${p.interface}</span>
  7543. </label>
  7544. `).join('');
  7545. }
  7546. async function submitSaveBridgeVLAN(e) {
  7547. e.preventDefault();
  7548. const id = document.getElementById('bridge-vlan-modal-id').value;
  7549. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  7550. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  7551. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  7552. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  7553. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  7554. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  7555. try {
  7556. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  7557. method: 'POST',
  7558. headers: { 'Content-Type': 'application/json' },
  7559. body: JSON.stringify({
  7560. id,
  7561. bridge,
  7562. vlan_ids: vlanIDs,
  7563. tagged,
  7564. untagged,
  7565. comment,
  7566. disabled
  7567. })
  7568. });
  7569. if (res.ok) {
  7570. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  7571. closeBridgeVlanModal();
  7572. loadBridge();
  7573. } else {
  7574. const err = await res.json();
  7575. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  7576. }
  7577. } catch (err) {
  7578. showToast('Error', err.message, 'error');
  7579. }
  7580. }
  7581. async function toggleBridgeVLANState(id, disabled) {
  7582. try {
  7583. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  7584. method: 'POST',
  7585. headers: { 'Content-Type': 'application/json' },
  7586. body: JSON.stringify({ disabled })
  7587. });
  7588. if (res.ok) loadBridge();
  7589. } catch (err) {
  7590. showToast('Error', err.message, 'error');
  7591. }
  7592. }
  7593. async function deleteBridgeVLAN(id) {
  7594. if (!confirm('Delete this bridge VLAN entry?')) return;
  7595. try {
  7596. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7597. if (res.ok) {
  7598. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  7599. loadBridge();
  7600. }
  7601. } catch (err) {
  7602. showToast('Error', err.message, 'error');
  7603. }
  7604. }
  7605. // ----------------- Hosts / MAC Table -----------------
  7606. async function loadBridgeHosts() {
  7607. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  7608. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  7609. try {
  7610. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  7611. const res = await fetch(url);
  7612. if (res.ok) {
  7613. state.bridgeHosts = await res.json();
  7614. renderBridgeHosts();
  7615. }
  7616. } catch (err) {
  7617. console.error('Failed to load bridge hosts:', err);
  7618. }
  7619. }
  7620. function renderBridgeHosts() {
  7621. const tbody = document.getElementById('bridge-hosts-table-body');
  7622. const empty = document.getElementById('bridge-empty-hosts');
  7623. const countBadge = document.getElementById('bridge-hosts-count-badge');
  7624. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  7625. if (!tbody) return;
  7626. tbody.innerHTML = '';
  7627. const hosts = (state.bridgeHosts || []).filter(h => {
  7628. if (!search) return true;
  7629. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  7630. });
  7631. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  7632. if (hosts.length === 0) {
  7633. empty?.classList.remove('hidden');
  7634. return;
  7635. }
  7636. empty?.classList.add('hidden');
  7637. hosts.forEach(h => {
  7638. const tr = document.createElement('tr');
  7639. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  7640. let flagBadges = '';
  7641. 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>';
  7642. 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>';
  7643. 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>';
  7644. tr.innerHTML = `
  7645. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  7646. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  7647. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  7648. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  7649. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  7650. <td class="py-2.5 px-3">${flagBadges}</td>
  7651. `;
  7652. tbody.appendChild(tr);
  7653. });
  7654. }
  7655. async function flushBridgeHosts() {
  7656. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  7657. if (!selBridge) {
  7658. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  7659. return;
  7660. }
  7661. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  7662. try {
  7663. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  7664. method: 'POST',
  7665. headers: { 'Content-Type': 'application/json' },
  7666. body: JSON.stringify({ bridge: selBridge })
  7667. });
  7668. if (res.ok) {
  7669. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  7670. loadBridgeHosts();
  7671. }
  7672. } catch (err) {
  7673. showToast('Error', err.message, 'error');
  7674. }
  7675. }
  7676. // ----------------- Helpers -----------------
  7677. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  7678. const sel = document.getElementById(selectId);
  7679. if (!sel) return;
  7680. const prevVal = currentVal || sel.value;
  7681. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  7682. (state.bridges || []).forEach(b => {
  7683. const opt = document.createElement('option');
  7684. opt.value = b.name;
  7685. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  7686. if (b.name === prevVal) opt.selected = true;
  7687. sel.appendChild(opt);
  7688. });
  7689. }
  7690. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  7691. const sel = document.getElementById(selectId);
  7692. if (!sel) return;
  7693. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  7694. // 1. Physical Interfaces
  7695. const grpPhys = document.createElement('optgroup');
  7696. grpPhys.label = 'Physical Interfaces';
  7697. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  7698. const opt = document.createElement('option');
  7699. opt.value = i.name;
  7700. opt.innerText = `${i.name} (${i.role || i.type})`;
  7701. if (i.name === currentVal) opt.selected = true;
  7702. grpPhys.appendChild(opt);
  7703. });
  7704. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  7705. // 2. VLAN Sub-interfaces
  7706. const grpVlans = document.createElement('optgroup');
  7707. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  7708. (state.vlans || []).forEach(v => {
  7709. const opt = document.createElement('option');
  7710. opt.value = v.name;
  7711. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  7712. if (v.name === currentVal) opt.selected = true;
  7713. grpVlans.appendChild(opt);
  7714. });
  7715. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  7716. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  7717. const grpEoip = document.createElement('optgroup');
  7718. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  7719. (state.eoipTunnels || []).forEach(t => {
  7720. const opt = document.createElement('option');
  7721. opt.value = t.name;
  7722. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  7723. if (t.name === currentVal) opt.selected = true;
  7724. grpEoip.appendChild(opt);
  7725. });
  7726. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  7727. }
  7728. // -------------------------------------------------------------
  7729. // Routing Filters Management (/routing filter)
  7730. // -------------------------------------------------------------
  7731. function renderRoutingFilters() {
  7732. const tbody = document.getElementById('routing-filters-table-body');
  7733. if (!tbody) return;
  7734. const empty = document.getElementById('routing-filters-empty');
  7735. const countBadge = document.getElementById('routing-filters-count-badge');
  7736. const navBadge = document.getElementById('badge-filters-count');
  7737. const chainSelect = document.getElementById('routing-filter-chain-select');
  7738. const allRules = state.routingFilters || [];
  7739. if (navBadge) navBadge.innerText = allRules.length;
  7740. // Populate chain filter select options dynamically
  7741. if (chainSelect) {
  7742. const currentVal = state.filterChainSelected || 'all';
  7743. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  7744. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  7745. uniqueChains.map(ch => {
  7746. const count = allRules.filter(r => r.chain === ch).length;
  7747. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  7748. }).join('');
  7749. chainSelect.value = currentVal;
  7750. }
  7751. // Filter rules by selected chain
  7752. const filteredRules = (state.filterChainSelected && state.filterChainSelected !== 'all')
  7753. ? allRules.filter(r => r.chain === state.filterChainSelected)
  7754. : allRules.slice();
  7755. // Sort by chain then rule_order
  7756. filteredRules.sort((a, b) => {
  7757. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  7758. return (a.rule_order || 0) - (b.rule_order || 0);
  7759. });
  7760. if (countBadge) countBadge.innerText = `${filteredRules.length} Rules`;
  7761. if (filteredRules.length === 0) {
  7762. tbody.innerHTML = '';
  7763. if (empty) empty.classList.remove('hidden');
  7764. return;
  7765. }
  7766. if (empty) empty.classList.add('hidden');
  7767. tbody.innerHTML = filteredRules.map(r => {
  7768. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  7769. const flagX = r.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  7770. let actionBadge = '';
  7771. if (r.action === 'accept') {
  7772. 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>';
  7773. } else if (r.action === 'discard') {
  7774. 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>';
  7775. } else if (r.action === 'reject') {
  7776. 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>';
  7777. } else {
  7778. 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>`;
  7779. }
  7780. // Prefix match
  7781. let matchPfx = '';
  7782. if (r.prefix) {
  7783. matchPfx = `<span class="font-bold text-white">${escapeHtml(r.prefix)}</span>`;
  7784. if (r.prefix_len) {
  7785. matchPfx += ` <span class="text-slate-400 text-[11px] font-normal">[${escapeHtml(r.prefix_len)}]</span>`;
  7786. }
  7787. } else {
  7788. matchPfx = '<span class="text-slate-500 italic">any prefix</span>';
  7789. }
  7790. // Other matches
  7791. const matchExtra = [];
  7792. if (r.match_protocol && r.match_protocol !== 'any') {
  7793. 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>`);
  7794. }
  7795. if (r.match_as_path) {
  7796. 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>`);
  7797. }
  7798. if (r.match_community) {
  7799. 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>`);
  7800. }
  7801. const matchExtraHtml = matchExtra.length > 0 ? matchExtra.join(' ') : '<span class="text-slate-600">-</span>';
  7802. // Set modifications
  7803. const setBadges = [];
  7804. if (r.set_local_pref > 0) {
  7805. 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>`);
  7806. }
  7807. if (r.set_metric > 0) {
  7808. 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>`);
  7809. }
  7810. if (r.set_as_prepend > 0) {
  7811. 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>`);
  7812. }
  7813. if (r.set_community) {
  7814. 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>`);
  7815. }
  7816. if (r.set_next_hop) {
  7817. 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>`);
  7818. }
  7819. const setHtml = setBadges.length > 0 ? setBadges.join(' ') : '<span class="text-slate-600">-</span>';
  7820. return `
  7821. <tr class="hover:bg-slate-800/40 transition">
  7822. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagX}</td>
  7823. <td class="py-2.5 px-3 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  7824. <td class="py-2.5 px-3">
  7825. <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>
  7826. </td>
  7827. <td class="py-2.5 px-3">${actionBadge}</td>
  7828. <td class="py-2.5 px-3 font-mono">${matchPfx}</td>
  7829. <td class="py-2.5 px-3 space-x-1">${matchExtraHtml}</td>
  7830. <td class="py-2.5 px-3 space-x-1 font-mono">${setHtml}</td>
  7831. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  7832. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  7833. <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'}">
  7834. ${r.disabled ? 'Enable' : 'Disable'}
  7835. </button>
  7836. <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">
  7837. Edit
  7838. </button>
  7839. <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">
  7840. Delete
  7841. </button>
  7842. </td>
  7843. </tr>
  7844. `;
  7845. }).join('');
  7846. }
  7847. function filterRoutingFiltersByChain(chain) {
  7848. state.filterChainSelected = chain;
  7849. renderRoutingFilters();
  7850. }
  7851. function openAddRoutingFilterModal(defaultChain = '') {
  7852. const form = document.getElementById('routing-filter-form');
  7853. if (form) form.reset();
  7854. const idEl = document.getElementById('modal-rf-id');
  7855. if (idEl) idEl.value = '';
  7856. const titleEl = document.getElementById('modal-rf-title');
  7857. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  7858. const chainEl = document.getElementById('modal-rf-chain');
  7859. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  7860. const orderEl = document.getElementById('modal-rf-order');
  7861. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  7862. const actEl = document.getElementById('modal-rf-action');
  7863. if (actEl) actEl.value = 'accept';
  7864. const protoEl = document.getElementById('modal-rf-protocol');
  7865. if (protoEl) protoEl.value = 'any';
  7866. const disEl = document.getElementById('modal-rf-disabled');
  7867. if (disEl) disEl.checked = false;
  7868. const modal = document.getElementById('modal-routing-filter');
  7869. if (modal) modal.classList.remove('hidden');
  7870. }
  7871. function openEditRoutingFilterModal(id) {
  7872. const r = (state.routingFilters || []).find(item => item.id === id);
  7873. if (!r) return;
  7874. const idEl = document.getElementById('modal-rf-id');
  7875. if (idEl) idEl.value = r.id;
  7876. const titleEl = document.getElementById('modal-rf-title');
  7877. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  7878. const chainEl = document.getElementById('modal-rf-chain');
  7879. if (chainEl) chainEl.value = r.chain || '';
  7880. const orderEl = document.getElementById('modal-rf-order');
  7881. if (orderEl) orderEl.value = r.rule_order || 10;
  7882. const actEl = document.getElementById('modal-rf-action');
  7883. if (actEl) actEl.value = r.action || 'accept';
  7884. const pfxEl = document.getElementById('modal-rf-prefix');
  7885. if (pfxEl) pfxEl.value = r.prefix || '';
  7886. const pfxLenEl = document.getElementById('modal-rf-prefix-len');
  7887. if (pfxLenEl) pfxLenEl.value = r.prefix_len || '';
  7888. const protoEl = document.getElementById('modal-rf-protocol');
  7889. if (protoEl) protoEl.value = r.match_protocol || 'any';
  7890. const aspEl = document.getElementById('modal-rf-as-path');
  7891. if (aspEl) aspEl.value = r.match_as_path || '';
  7892. const commEl = document.getElementById('modal-rf-community');
  7893. if (commEl) commEl.value = r.match_community || '';
  7894. const lpEl = document.getElementById('modal-rf-set-local-pref');
  7895. if (lpEl) lpEl.value = r.set_local_pref || '';
  7896. const metEl = document.getElementById('modal-rf-set-metric');
  7897. if (metEl) metEl.value = r.set_metric || '';
  7898. const prepEl = document.getElementById('modal-rf-set-as-prepend');
  7899. if (prepEl) prepEl.value = r.set_as_prepend || '';
  7900. const setCommEl = document.getElementById('modal-rf-set-community');
  7901. if (setCommEl) setCommEl.value = r.set_community || '';
  7902. const nhEl = document.getElementById('modal-rf-set-next-hop');
  7903. if (nhEl) nhEl.value = r.set_next_hop || '';
  7904. const comEl = document.getElementById('modal-rf-comment');
  7905. if (comEl) comEl.value = r.comment || '';
  7906. const disEl = document.getElementById('modal-rf-disabled');
  7907. if (disEl) disEl.checked = !!r.disabled;
  7908. const modal = document.getElementById('modal-routing-filter');
  7909. if (modal) modal.classList.remove('hidden');
  7910. }
  7911. function closeRoutingFilterModal() {
  7912. const modal = document.getElementById('modal-routing-filter');
  7913. if (modal) modal.classList.add('hidden');
  7914. }
  7915. async function submitRoutingFilter(e) {
  7916. e.preventDefault();
  7917. const payload = {
  7918. id: document.getElementById('modal-rf-id').value,
  7919. chain: document.getElementById('modal-rf-chain').value.trim(),
  7920. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  7921. action: document.getElementById('modal-rf-action').value,
  7922. prefix: document.getElementById('modal-rf-prefix').value.trim(),
  7923. prefix_len: document.getElementById('modal-rf-prefix-len').value.trim(),
  7924. match_protocol: document.getElementById('modal-rf-protocol').value,
  7925. match_as_path: document.getElementById('modal-rf-as-path').value.trim(),
  7926. match_community: document.getElementById('modal-rf-community').value.trim(),
  7927. set_local_pref: parseInt(document.getElementById('modal-rf-set-local-pref').value, 10) || 0,
  7928. set_metric: parseInt(document.getElementById('modal-rf-set-metric').value, 10) || 0,
  7929. set_as_prepend: parseInt(document.getElementById('modal-rf-set-as-prepend').value, 10) || 0,
  7930. set_community: document.getElementById('modal-rf-set-community').value.trim(),
  7931. set_next_hop: document.getElementById('modal-rf-set-next-hop').value.trim(),
  7932. comment: document.getElementById('modal-rf-comment').value.trim(),
  7933. disabled: document.getElementById('modal-rf-disabled').checked
  7934. };
  7935. try {
  7936. const res = await fetch(`${API_BASE}/routing/filters`, {
  7937. method: 'POST',
  7938. headers: { 'Content-Type': 'application/json' },
  7939. body: JSON.stringify(payload)
  7940. });
  7941. if (res.ok) {
  7942. closeRoutingFilterModal();
  7943. showToast('Success', 'Routing filter rule saved', 'success');
  7944. loadDynamicRouting();
  7945. } else {
  7946. const err = await res.json();
  7947. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  7948. }
  7949. } catch (err) {
  7950. showToast('Error', err.message, 'error');
  7951. }
  7952. }
  7953. async function deleteRoutingFilter(id) {
  7954. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  7955. try {
  7956. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7957. if (res.ok) {
  7958. showToast('Deleted', 'Routing filter rule removed', 'info');
  7959. loadDynamicRouting();
  7960. } else {
  7961. const err = await res.json();
  7962. showToast('Error', err.error || 'Failed to delete rule', 'error');
  7963. }
  7964. } catch (err) {
  7965. showToast('Error', err.message, 'error');
  7966. }
  7967. }
  7968. async function toggleRoutingFilterState(id, disabled) {
  7969. try {
  7970. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  7971. method: 'POST',
  7972. headers: { 'Content-Type': 'application/json' },
  7973. body: JSON.stringify({ disabled })
  7974. });
  7975. if (res.ok) {
  7976. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  7977. loadDynamicRouting();
  7978. } else {
  7979. const err = await res.json();
  7980. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  7981. }
  7982. } catch (err) {
  7983. showToast('Error', err.message, 'error');
  7984. }
  7985. }
  7986. // ==========================================
  7987. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  7988. // ==========================================
  7989. function loadToolsView() {
  7990. populateToolsInterfaces();
  7991. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  7992. }
  7993. function populateToolsInterfaces() {
  7994. const pingSel = document.getElementById('tools-ping-iface');
  7995. const traceSel = document.getElementById('tools-tr-iface');
  7996. let opts = '<option value="">Auto (Default Route)</option>';
  7997. if (Array.isArray(state.interfaces)) {
  7998. state.interfaces.forEach(iface => {
  7999. if (iface.name) {
  8000. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  8001. }
  8002. });
  8003. }
  8004. if (pingSel) {
  8005. const cur = pingSel.value;
  8006. pingSel.innerHTML = opts;
  8007. if (cur) pingSel.value = cur;
  8008. }
  8009. if (traceSel) {
  8010. const cur = traceSel.value;
  8011. traceSel.innerHTML = opts;
  8012. if (cur) traceSel.value = cur;
  8013. }
  8014. }
  8015. function switchToolsSubTab(subTab) {
  8016. state.activeToolsSubTab = subTab;
  8017. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  8018. tabs.forEach(t => {
  8019. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  8020. const view = document.getElementById(`tools-view-${t}`);
  8021. if (btn) {
  8022. if (t === subTab) {
  8023. 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';
  8024. } else {
  8025. 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';
  8026. }
  8027. }
  8028. if (view) {
  8029. if (t === subTab) {
  8030. view.classList.remove('hidden');
  8031. } else {
  8032. view.classList.add('hidden');
  8033. }
  8034. }
  8035. });
  8036. }
  8037. function setPortPreset(port) {
  8038. const input = document.getElementById('tools-port-num');
  8039. if (input) input.value = port;
  8040. }
  8041. let pingAbortController = null;
  8042. let tracerouteAbortController = null;
  8043. function clearPingTable() {
  8044. const tbody = document.getElementById('tools-ping-tbody');
  8045. if (tbody) tbody.innerHTML = '';
  8046. const rawEl = document.getElementById('tools-ping-raw');
  8047. if (rawEl) rawEl.innerText = '';
  8048. const sentEl = document.getElementById('tools-ping-stat-sent');
  8049. if (sentEl) sentEl.innerText = '0';
  8050. const recvEl = document.getElementById('tools-ping-stat-recv');
  8051. if (recvEl) recvEl.innerText = '0';
  8052. const lossEl = document.getElementById('tools-ping-stat-loss');
  8053. if (lossEl) lossEl.innerText = '0%';
  8054. const avgEl = document.getElementById('tools-ping-stat-avg');
  8055. if (avgEl) avgEl.innerText = '0 ms';
  8056. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  8057. if (minMaxEl) minMaxEl.innerText = '-';
  8058. const badge = document.getElementById('tools-ping-status-badge');
  8059. if (badge) {
  8060. badge.className = '';
  8061. badge.innerText = '';
  8062. }
  8063. }
  8064. function clearTracerouteTable() {
  8065. const tbody = document.getElementById('tools-tr-tbody');
  8066. if (tbody) tbody.innerHTML = '';
  8067. const rawEl = document.getElementById('tools-tr-raw');
  8068. if (rawEl) rawEl.innerText = '';
  8069. const statHops = document.getElementById('tools-tr-hops-count');
  8070. if (statHops) statHops.innerText = '0 Hops';
  8071. }
  8072. function resetPingButton() {
  8073. const btn = document.getElementById('tools-ping-btn');
  8074. const btnText = document.getElementById('tools-ping-btn-text');
  8075. const spinner = document.getElementById('tools-ping-spinner');
  8076. if (btn) {
  8077. btn.disabled = false;
  8078. 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';
  8079. }
  8080. if (btnText) btnText.innerText = 'Start Ping';
  8081. if (spinner) spinner.classList.add('hidden');
  8082. }
  8083. function setPingRunningButton() {
  8084. const btn = document.getElementById('tools-ping-btn');
  8085. const btnText = document.getElementById('tools-ping-btn-text');
  8086. const spinner = document.getElementById('tools-ping-spinner');
  8087. if (btn) {
  8088. btn.disabled = false;
  8089. 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';
  8090. }
  8091. if (btnText) btnText.innerText = 'Stop Ping';
  8092. if (spinner) spinner.classList.remove('hidden');
  8093. }
  8094. function resetTracerouteButton() {
  8095. const btn = document.getElementById('tools-tr-btn');
  8096. const btnText = document.getElementById('tools-tr-btn-text');
  8097. const spinner = document.getElementById('tools-tr-spinner');
  8098. if (btn) {
  8099. btn.disabled = false;
  8100. 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';
  8101. }
  8102. if (btnText) btnText.innerText = 'Start Traceroute';
  8103. if (spinner) spinner.classList.add('hidden');
  8104. }
  8105. function setTracerouteRunningButton() {
  8106. const btn = document.getElementById('tools-tr-btn');
  8107. const btnText = document.getElementById('tools-tr-btn-text');
  8108. const spinner = document.getElementById('tools-tr-spinner');
  8109. if (btn) {
  8110. btn.disabled = false;
  8111. 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';
  8112. }
  8113. if (btnText) btnText.innerText = 'Stop Traceroute';
  8114. if (spinner) spinner.classList.remove('hidden');
  8115. }
  8116. async function executePing(e) {
  8117. if (e) e.preventDefault();
  8118. // If already running, clicking the button stops the stream!
  8119. if (pingAbortController) {
  8120. pingAbortController.abort();
  8121. pingAbortController = null;
  8122. resetPingButton();
  8123. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  8124. return;
  8125. }
  8126. const target = document.getElementById('tools-ping-target')?.value?.trim();
  8127. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  8128. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  8129. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  8130. const iface = document.getElementById('tools-ping-iface')?.value || '';
  8131. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  8132. if (!target) {
  8133. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  8134. return;
  8135. }
  8136. clearPingTable();
  8137. const resCard = document.getElementById('tools-ping-results');
  8138. if (resCard) resCard.classList.remove('hidden');
  8139. pingAbortController = new AbortController();
  8140. setPingRunningButton();
  8141. try {
  8142. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  8143. method: 'POST',
  8144. headers: { 'Content-Type': 'application/json' },
  8145. body: JSON.stringify({
  8146. target,
  8147. count,
  8148. size,
  8149. timeout,
  8150. interface: iface,
  8151. dont_frag: dontFrag
  8152. }),
  8153. signal: pingAbortController.signal
  8154. });
  8155. if (!res.ok) {
  8156. const errText = await res.text();
  8157. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  8158. resetPingButton();
  8159. pingAbortController = null;
  8160. return;
  8161. }
  8162. const reader = res.body.getReader();
  8163. const decoder = new TextDecoder('utf-8');
  8164. let buffer = '';
  8165. while (true) {
  8166. const { done, value } = await reader.read();
  8167. if (done) break;
  8168. buffer += decoder.decode(value, { stream: true });
  8169. const blocks = buffer.split('\n\n');
  8170. buffer = blocks.pop() || '';
  8171. for (const block of blocks) {
  8172. const trimmed = block.trim();
  8173. if (!trimmed) continue;
  8174. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  8175. try {
  8176. const evt = JSON.parse(line);
  8177. handleLivePingEvent(evt);
  8178. } catch (parseErr) {
  8179. console.warn('Ping SSE parse error:', parseErr, line);
  8180. }
  8181. }
  8182. }
  8183. } catch (err) {
  8184. if (err.name === 'AbortError') {
  8185. // User aborted normally
  8186. } else {
  8187. showToast('Ping Error', err.message, 'error');
  8188. }
  8189. } finally {
  8190. pingAbortController = null;
  8191. resetPingButton();
  8192. }
  8193. }
  8194. function handleLivePingEvent(evt) {
  8195. const sentEl = document.getElementById('tools-ping-stat-sent');
  8196. const recvEl = document.getElementById('tools-ping-stat-recv');
  8197. const lossEl = document.getElementById('tools-ping-stat-loss');
  8198. const avgEl = document.getElementById('tools-ping-stat-avg');
  8199. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  8200. const badge = document.getElementById('tools-ping-status-badge');
  8201. const tbody = document.getElementById('tools-ping-tbody');
  8202. const rawEl = document.getElementById('tools-ping-raw');
  8203. if (evt.raw && rawEl) {
  8204. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  8205. rawEl.scrollTop = rawEl.scrollHeight;
  8206. }
  8207. if (evt.type === 'reply') {
  8208. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  8209. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  8210. if (lossEl && evt.packet_loss_pct !== undefined) {
  8211. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  8212. lossEl.className = evt.packet_loss_pct === 0
  8213. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  8214. : (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');
  8215. }
  8216. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  8217. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  8218. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  8219. }
  8220. if (badge) {
  8221. if (evt.packet_loss_pct === 0) {
  8222. 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';
  8223. badge.innerText = '100% OK';
  8224. } else {
  8225. 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';
  8226. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  8227. }
  8228. }
  8229. if (tbody) {
  8230. const tr = document.createElement('tr');
  8231. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  8232. tr.innerHTML = `
  8233. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  8234. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  8235. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  8236. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  8237. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  8238. <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>
  8239. `;
  8240. tbody.appendChild(tr);
  8241. }
  8242. } else if (evt.type === 'timeout') {
  8243. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  8244. if (lossEl && evt.packet_loss_pct !== undefined) {
  8245. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  8246. 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';
  8247. }
  8248. if (badge) {
  8249. 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';
  8250. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  8251. }
  8252. if (tbody) {
  8253. const tr = document.createElement('tr');
  8254. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  8255. tr.innerHTML = `
  8256. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  8257. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  8258. <td class="py-2 px-3 text-slate-600">--</td>
  8259. <td class="py-2 px-3 text-slate-600">--</td>
  8260. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  8261. <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>
  8262. `;
  8263. tbody.appendChild(tr);
  8264. }
  8265. } else if (evt.type === 'unreach') {
  8266. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  8267. if (lossEl && evt.packet_loss_pct !== undefined) {
  8268. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  8269. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  8270. }
  8271. if (badge) {
  8272. 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';
  8273. badge.innerText = 'UNREACHABLE';
  8274. }
  8275. if (tbody) {
  8276. const tr = document.createElement('tr');
  8277. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  8278. tr.innerHTML = `
  8279. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  8280. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  8281. <td class="py-2 px-3 text-slate-600">--</td>
  8282. <td class="py-2 px-3 text-slate-600">--</td>
  8283. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  8284. <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>
  8285. `;
  8286. tbody.appendChild(tr);
  8287. }
  8288. } else if (evt.type === 'stats') {
  8289. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  8290. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  8291. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  8292. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  8293. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  8294. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  8295. }
  8296. } else if (evt.type === 'done') {
  8297. 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');
  8298. }
  8299. }
  8300. async function executeTraceroute(e) {
  8301. if (e) e.preventDefault();
  8302. if (tracerouteAbortController) {
  8303. tracerouteAbortController.abort();
  8304. tracerouteAbortController = null;
  8305. resetTracerouteButton();
  8306. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  8307. return;
  8308. }
  8309. const target = document.getElementById('tools-tr-target')?.value?.trim();
  8310. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  8311. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  8312. const iface = document.getElementById('tools-tr-iface')?.value || '';
  8313. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  8314. if (!target) {
  8315. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  8316. return;
  8317. }
  8318. clearTracerouteTable();
  8319. const resCard = document.getElementById('tools-tr-results');
  8320. if (resCard) resCard.classList.remove('hidden');
  8321. tracerouteAbortController = new AbortController();
  8322. setTracerouteRunningButton();
  8323. try {
  8324. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  8325. method: 'POST',
  8326. headers: { 'Content-Type': 'application/json' },
  8327. body: JSON.stringify({
  8328. target,
  8329. max_hops: maxHops,
  8330. protocol,
  8331. interface: iface,
  8332. resolve
  8333. }),
  8334. signal: tracerouteAbortController.signal
  8335. });
  8336. if (!res.ok) {
  8337. const errText = await res.text();
  8338. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  8339. resetTracerouteButton();
  8340. tracerouteAbortController = null;
  8341. return;
  8342. }
  8343. const reader = res.body.getReader();
  8344. const decoder = new TextDecoder('utf-8');
  8345. let buffer = '';
  8346. while (true) {
  8347. const { done, value } = await reader.read();
  8348. if (done) break;
  8349. buffer += decoder.decode(value, { stream: true });
  8350. const blocks = buffer.split('\n\n');
  8351. buffer = blocks.pop() || '';
  8352. for (const block of blocks) {
  8353. const trimmed = block.trim();
  8354. if (!trimmed) continue;
  8355. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  8356. try {
  8357. const evt = JSON.parse(line);
  8358. handleLiveTracerouteEvent(evt);
  8359. } catch (parseErr) {
  8360. console.warn('Traceroute SSE parse error:', parseErr, line);
  8361. }
  8362. }
  8363. }
  8364. } catch (err) {
  8365. if (err.name === 'AbortError') {
  8366. // User aborted normally
  8367. } else {
  8368. showToast('Traceroute Error', err.message, 'error');
  8369. }
  8370. } finally {
  8371. tracerouteAbortController = null;
  8372. resetTracerouteButton();
  8373. }
  8374. }
  8375. function handleLiveTracerouteEvent(evt) {
  8376. const statHops = document.getElementById('tools-tr-hops-count');
  8377. const tbody = document.getElementById('tools-tr-tbody');
  8378. const rawEl = document.getElementById('tools-tr-raw');
  8379. if (evt.raw && rawEl) {
  8380. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  8381. rawEl.scrollTop = rawEl.scrollHeight;
  8382. }
  8383. if (evt.hops_count !== undefined && statHops) {
  8384. statHops.innerText = `${evt.hops_count} Hops`;
  8385. }
  8386. if (evt.type === 'hop' && evt.hop && tbody) {
  8387. const h = evt.hop;
  8388. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  8389. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  8390. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  8391. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  8392. const tr = document.createElement('tr');
  8393. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  8394. tr.innerHTML = `
  8395. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  8396. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  8397. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  8398. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  8399. <td class="py-2.5 px-3 text-right">
  8400. ${isTimeout
  8401. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  8402. : '<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>'}
  8403. </td>
  8404. `;
  8405. tbody.appendChild(tr);
  8406. } else if (evt.type === 'done') {
  8407. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  8408. }
  8409. }
  8410. async function executeMTR(e) {
  8411. if (e) e.preventDefault();
  8412. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  8413. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  8414. if (!target) {
  8415. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  8416. return;
  8417. }
  8418. const btn = document.getElementById('tools-mtr-btn');
  8419. const spinner = document.getElementById('tools-mtr-spinner');
  8420. if (btn) btn.disabled = true;
  8421. if (spinner) spinner.classList.remove('hidden');
  8422. try {
  8423. const res = await fetch(`${API_BASE}/tools/mtr`, {
  8424. method: 'POST',
  8425. headers: { 'Content-Type': 'application/json' },
  8426. body: JSON.stringify({ target, count: cycles })
  8427. });
  8428. const data = await res.json();
  8429. if (!res.ok) {
  8430. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  8431. return;
  8432. }
  8433. const resCard = document.getElementById('tools-mtr-results');
  8434. if (resCard) resCard.classList.remove('hidden');
  8435. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  8436. const statHops = document.getElementById('tools-mtr-hops-count');
  8437. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  8438. const tbody = document.getElementById('tools-mtr-tbody');
  8439. if (tbody) {
  8440. if (hopsCount > 0) {
  8441. tbody.innerHTML = data.hops.map(h => {
  8442. 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');
  8443. return `
  8444. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  8445. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  8446. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  8447. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  8448. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  8449. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  8450. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  8451. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  8452. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  8453. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  8454. </tr>
  8455. `;
  8456. }).join('');
  8457. } else {
  8458. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  8459. }
  8460. }
  8461. const rawEl = document.getElementById('tools-mtr-raw');
  8462. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  8463. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  8464. } catch (err) {
  8465. showToast('MTR Error', err.message, 'error');
  8466. } finally {
  8467. if (btn) btn.disabled = false;
  8468. if (spinner) spinner.classList.add('hidden');
  8469. }
  8470. }
  8471. async function executeDNS(e) {
  8472. if (e) e.preventDefault();
  8473. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  8474. const type = document.getElementById('tools-dns-type')?.value || 'A';
  8475. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  8476. if (!domain) {
  8477. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  8478. return;
  8479. }
  8480. const btn = document.getElementById('tools-dns-btn');
  8481. const spinner = document.getElementById('tools-dns-spinner');
  8482. if (btn) btn.disabled = true;
  8483. if (spinner) spinner.classList.remove('hidden');
  8484. try {
  8485. const res = await fetch(`${API_BASE}/tools/dns`, {
  8486. method: 'POST',
  8487. headers: { 'Content-Type': 'application/json' },
  8488. body: JSON.stringify({ domain, type, server })
  8489. });
  8490. const data = await res.json();
  8491. if (!res.ok) {
  8492. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  8493. return;
  8494. }
  8495. const resCard = document.getElementById('tools-dns-results');
  8496. if (resCard) resCard.classList.remove('hidden');
  8497. const metaEl = document.getElementById('tools-dns-meta');
  8498. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  8499. const tbody = document.getElementById('tools-dns-tbody');
  8500. if (tbody) {
  8501. if (Array.isArray(data.records) && data.records.length > 0) {
  8502. tbody.innerHTML = data.records.map(r => `
  8503. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  8504. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  8505. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  8506. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  8507. <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>
  8508. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  8509. </tr>
  8510. `).join('');
  8511. } else {
  8512. 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>`;
  8513. }
  8514. }
  8515. const rawEl = document.getElementById('tools-dns-raw');
  8516. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  8517. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  8518. } catch (err) {
  8519. showToast('DNS Error', err.message, 'error');
  8520. } finally {
  8521. if (btn) btn.disabled = false;
  8522. if (spinner) spinner.classList.add('hidden');
  8523. }
  8524. }
  8525. async function executePortProbe(e) {
  8526. if (e) e.preventDefault();
  8527. const target = document.getElementById('tools-port-target')?.value?.trim();
  8528. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  8529. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  8530. if (!target || !port) {
  8531. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  8532. return;
  8533. }
  8534. const btn = document.getElementById('tools-port-btn');
  8535. const spinner = document.getElementById('tools-port-spinner');
  8536. if (btn) btn.disabled = true;
  8537. if (spinner) spinner.classList.remove('hidden');
  8538. try {
  8539. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  8540. method: 'POST',
  8541. headers: { 'Content-Type': 'application/json' },
  8542. body: JSON.stringify({ target, port, timeout })
  8543. });
  8544. const data = await res.json();
  8545. if (!res.ok) {
  8546. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  8547. return;
  8548. }
  8549. const resCard = document.getElementById('tools-port-results');
  8550. if (resCard) resCard.classList.remove('hidden');
  8551. const banner = document.getElementById('tools-port-banner');
  8552. const icon = document.getElementById('tools-port-icon');
  8553. const title = document.getElementById('tools-port-title');
  8554. const sub = document.getElementById('tools-port-sub');
  8555. const latency = document.getElementById('tools-port-latency');
  8556. if (data.open) {
  8557. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  8558. if (icon) {
  8559. 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';
  8560. icon.innerText = '✓';
  8561. }
  8562. if (title) {
  8563. title.className = 'text-sm font-bold text-emerald-300';
  8564. title.innerText = `PORT ${port} OPEN / LISTENING`;
  8565. }
  8566. if (sub) {
  8567. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  8568. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  8569. }
  8570. if (latency) {
  8571. latency.className = 'text-base font-bold font-mono text-emerald-300';
  8572. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  8573. }
  8574. } else {
  8575. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  8576. if (icon) {
  8577. 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';
  8578. icon.innerText = '✕';
  8579. }
  8580. if (title) {
  8581. title.className = 'text-sm font-bold text-rose-300';
  8582. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  8583. }
  8584. if (sub) {
  8585. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  8586. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  8587. }
  8588. if (latency) {
  8589. latency.className = 'text-base font-bold font-mono text-slate-500';
  8590. latency.innerText = '--';
  8591. }
  8592. }
  8593. const rawEl = document.getElementById('tools-port-raw');
  8594. 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'}`);
  8595. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  8596. } catch (err) {
  8597. showToast('Probe Error', err.message, 'error');
  8598. } finally {
  8599. if (btn) btn.disabled = false;
  8600. if (spinner) spinner.classList.add('hidden');
  8601. }
  8602. }
  8603. // ==========================================
  8604. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  8605. // ==========================================
  8606. async function loadDHCPClients(showToastMsg = false) {
  8607. try {
  8608. const [clientsRes, sumRes] = await Promise.all([
  8609. fetch(`${API_BASE}/dhcp/clients`),
  8610. fetch(`${API_BASE}/dhcp/clients/summary`)
  8611. ]);
  8612. if (clientsRes.ok) {
  8613. state.dhcpClients = await clientsRes.json();
  8614. }
  8615. if (sumRes.ok) {
  8616. state.dhcpSummary = await sumRes.json();
  8617. }
  8618. renderDHCPClients();
  8619. updateDHCPSummaryCards();
  8620. const bDhcp = document.getElementById('badge-dhcp-client-count');
  8621. if (bDhcp && state.dhcpSummary) {
  8622. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  8623. }
  8624. if (showToastMsg) {
  8625. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  8626. }
  8627. } catch (err) {
  8628. console.error('Failed to load DHCP clients:', err);
  8629. if (showToastMsg) {
  8630. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  8631. }
  8632. }
  8633. }
  8634. function updateDHCPSummaryCards() {
  8635. const sum = state.dhcpSummary || {
  8636. total_clients: (state.dhcpClients || []).length,
  8637. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  8638. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  8639. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  8640. };
  8641. const totalEl = document.getElementById('dhcp-stat-total');
  8642. const boundEl = document.getElementById('dhcp-stat-bound');
  8643. const searchEl = document.getElementById('dhcp-stat-searching');
  8644. const disEl = document.getElementById('dhcp-stat-disabled');
  8645. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  8646. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  8647. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  8648. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  8649. }
  8650. function renderDHCPClients() {
  8651. const tbody = document.getElementById('dhcp-clients-tbody');
  8652. const emptyState = document.getElementById('dhcp-clients-empty');
  8653. if (!tbody) return;
  8654. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  8655. if (clients.length === 0) {
  8656. tbody.innerHTML = '';
  8657. if (emptyState) emptyState.classList.remove('hidden');
  8658. return;
  8659. }
  8660. if (emptyState) emptyState.classList.add('hidden');
  8661. tbody.innerHTML = clients.map(c => {
  8662. let statusBadge = '';
  8663. if (!c.enabled) {
  8664. 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>';
  8665. } else if (c.status === 'bound') {
  8666. 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>';
  8667. } else if (c.status === 'searching') {
  8668. 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>';
  8669. } else if (c.status === 'stopped') {
  8670. 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>';
  8671. } else {
  8672. 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>`;
  8673. }
  8674. 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>';
  8675. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  8676. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  8677. 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>';
  8678. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  8679. // Option flags
  8680. const flags = [];
  8681. 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>');
  8682. 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>');
  8683. 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>');
  8684. 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>`);
  8685. return `
  8686. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  8687. <td class="py-3 px-4">
  8688. <div class="flex items-center gap-2">
  8689. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  8690. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  8691. </div>
  8692. </td>
  8693. <td class="py-3 px-4">${statusBadge}</td>
  8694. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  8695. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  8696. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  8697. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  8698. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  8699. <td class="py-3 px-4">
  8700. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  8701. </td>
  8702. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  8703. ${c.enabled ? `
  8704. <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>
  8705. <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>
  8706. <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>
  8707. ` : `
  8708. <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>
  8709. `}
  8710. <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>
  8711. <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>
  8712. </td>
  8713. </tr>
  8714. `;
  8715. }).join('');
  8716. }
  8717. function openDHCPClientModal(clientId = null) {
  8718. const modal = document.getElementById('modal-dhcp-client');
  8719. if (!modal) return;
  8720. const title = document.getElementById('modal-dhcp-title');
  8721. const idInput = document.getElementById('modal-dhcp-id');
  8722. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  8723. const distInput = document.getElementById('modal-dhcp-distance');
  8724. const commentInput = document.getElementById('modal-dhcp-comment');
  8725. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  8726. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  8727. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  8728. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  8729. // Populate interfaces
  8730. if (ifaceSelect) {
  8731. let opts = '<option value="">Select interface...</option>';
  8732. const allIfaces = state.interfaces || [];
  8733. const allVlans = state.vlans || [];
  8734. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  8735. // Group 1: Physical & Bridge Interfaces
  8736. opts += '<optgroup label="Physical & Bridge Interfaces">';
  8737. allIfaces.forEach(i => {
  8738. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  8739. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  8740. });
  8741. opts += '</optgroup>';
  8742. // Group 2: VLAN Interfaces
  8743. if (allVlans.length > 0) {
  8744. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  8745. allVlans.forEach(v => {
  8746. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  8747. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  8748. });
  8749. opts += '</optgroup>';
  8750. }
  8751. ifaceSelect.innerHTML = opts;
  8752. }
  8753. if (clientId) {
  8754. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  8755. if (client) {
  8756. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  8757. if (idInput) idInput.value = client.id;
  8758. if (ifaceSelect) {
  8759. ifaceSelect.value = client.interface;
  8760. ifaceSelect.disabled = true; // interface cannot be changed on edit
  8761. }
  8762. if (distInput) distInput.value = client.default_route_distance || 1;
  8763. if (commentInput) commentInput.value = client.comment || '';
  8764. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  8765. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  8766. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  8767. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  8768. }
  8769. } else {
  8770. if (title) title.innerText = 'Add DHCP Client';
  8771. if (idInput) idInput.value = '';
  8772. if (ifaceSelect) {
  8773. ifaceSelect.value = '';
  8774. ifaceSelect.disabled = false;
  8775. }
  8776. if (distInput) distInput.value = 1;
  8777. if (commentInput) commentInput.value = '';
  8778. if (defRouteCheck) defRouteCheck.checked = true;
  8779. if (peerDnsCheck) peerDnsCheck.checked = true;
  8780. if (peerNtpCheck) peerNtpCheck.checked = true;
  8781. if (enabledCheck) enabledCheck.checked = true;
  8782. }
  8783. modal.classList.remove('hidden');
  8784. }
  8785. function openDHCPClientModalForIface(ifaceName) {
  8786. openDHCPClientModal();
  8787. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  8788. if (ifaceSelect && ifaceName) {
  8789. ifaceSelect.value = ifaceName;
  8790. }
  8791. }
  8792. function closeDHCPClientModal() {
  8793. const modal = document.getElementById('modal-dhcp-client');
  8794. if (modal) modal.classList.add('hidden');
  8795. }
  8796. async function submitSaveDHCPClient(e) {
  8797. if (e) e.preventDefault();
  8798. const id = document.getElementById('modal-dhcp-id')?.value;
  8799. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  8800. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  8801. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  8802. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  8803. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  8804. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  8805. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  8806. if (!id && !iface) {
  8807. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  8808. return;
  8809. }
  8810. try {
  8811. let res;
  8812. if (id) {
  8813. // PUT update
  8814. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  8815. method: 'PUT',
  8816. headers: { 'Content-Type': 'application/json' },
  8817. body: JSON.stringify({
  8818. enabled,
  8819. add_default_route: defRoute,
  8820. default_route_distance: distance,
  8821. use_peer_dns: peerDns,
  8822. use_peer_ntp: peerNtp,
  8823. comment
  8824. })
  8825. });
  8826. } else {
  8827. // POST create
  8828. res = await fetch(`${API_BASE}/dhcp/clients`, {
  8829. method: 'POST',
  8830. headers: { 'Content-Type': 'application/json' },
  8831. body: JSON.stringify({
  8832. interface: iface,
  8833. enabled,
  8834. add_default_route: defRoute,
  8835. default_route_distance: distance,
  8836. use_peer_dns: peerDns,
  8837. use_peer_ntp: peerNtp,
  8838. comment
  8839. })
  8840. });
  8841. }
  8842. const data = await res.json();
  8843. if (!res.ok) {
  8844. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  8845. return;
  8846. }
  8847. closeDHCPClientModal();
  8848. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  8849. await loadDHCPClients();
  8850. fetchData(); // refresh interfaces list with new lease/status
  8851. } catch (err) {
  8852. showToast('Error', err.message, 'error');
  8853. }
  8854. }
  8855. async function toggleDHCPClientState(id, enabled) {
  8856. try {
  8857. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  8858. method: 'POST',
  8859. headers: { 'Content-Type': 'application/json' },
  8860. body: JSON.stringify({ enabled })
  8861. });
  8862. const data = await res.json();
  8863. if (!res.ok) {
  8864. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  8865. return;
  8866. }
  8867. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  8868. await loadDHCPClients();
  8869. fetchData();
  8870. } catch (err) {
  8871. showToast('Error', err.message, 'error');
  8872. }
  8873. }
  8874. async function renewDHCPClient(id) {
  8875. try {
  8876. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  8877. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  8878. method: 'POST'
  8879. });
  8880. const data = await res.json();
  8881. if (!res.ok) {
  8882. showToast('Error', data.error || 'Failed to renew lease', 'error');
  8883. return;
  8884. }
  8885. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  8886. setTimeout(() => {
  8887. loadDHCPClients();
  8888. fetchData();
  8889. }, 1500);
  8890. } catch (err) {
  8891. showToast('Error', err.message, 'error');
  8892. }
  8893. }
  8894. async function releaseDHCPClient(id) {
  8895. try {
  8896. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  8897. method: 'POST'
  8898. });
  8899. const data = await res.json();
  8900. if (!res.ok) {
  8901. showToast('Error', data.error || 'Failed to release lease', 'error');
  8902. return;
  8903. }
  8904. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  8905. await loadDHCPClients();
  8906. fetchData();
  8907. } catch (err) {
  8908. showToast('Error', err.message, 'error');
  8909. }
  8910. }
  8911. async function deleteDHCPClient(id, ifaceName) {
  8912. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  8913. return;
  8914. }
  8915. try {
  8916. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  8917. method: 'DELETE'
  8918. });
  8919. const data = await res.json();
  8920. if (!res.ok) {
  8921. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  8922. return;
  8923. }
  8924. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  8925. await loadDHCPClients();
  8926. fetchData();
  8927. } catch (err) {
  8928. showToast('Error', err.message, 'error');
  8929. }
  8930. }
  8931. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  8932. function initTableSorting() {
  8933. document.querySelectorAll('table').forEach(setupSortableTable);
  8934. }
  8935. function setupSortableTable(table) {
  8936. const thead = table.querySelector('thead');
  8937. const tbody = table.querySelector('tbody');
  8938. if (!thead || !tbody) return;
  8939. const headerRows = thead.querySelectorAll('tr');
  8940. if (headerRows.length === 0) return;
  8941. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  8942. ths.forEach((th, colIdx) => {
  8943. if (th._sortBound) return;
  8944. th._sortBound = true;
  8945. const rawText = th.innerText.trim().toLowerCase();
  8946. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  8947. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  8948. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  8949. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  8950. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  8951. return;
  8952. }
  8953. th.classList.add('table-sortable', 'group');
  8954. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  8955. let icon = th.querySelector('.table-sort-icon');
  8956. if (!icon) {
  8957. icon = document.createElement('span');
  8958. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  8959. icon.innerHTML = '⇅';
  8960. th.appendChild(icon);
  8961. }
  8962. th.addEventListener('click', (e) => {
  8963. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  8964. handleHeaderClick(table, th, colIdx);
  8965. });
  8966. });
  8967. if (!tbody._sortObserved) {
  8968. tbody._sortObserved = true;
  8969. let sortDebounceTimer = null;
  8970. const observer = new MutationObserver((mutations) => {
  8971. if (tbody._isSorting) return;
  8972. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  8973. if (!hasChildChanges) return;
  8974. clearTimeout(sortDebounceTimer);
  8975. sortDebounceTimer = setTimeout(() => {
  8976. if (tbody._isSorting) return;
  8977. if (table._activeSort && table._activeSort.dir !== 'none') {
  8978. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  8979. } else {
  8980. tagOriginalRowOrder(tbody);
  8981. }
  8982. }, 10);
  8983. });
  8984. observer.observe(tbody, { childList: true });
  8985. }
  8986. tagOriginalRowOrder(tbody);
  8987. }
  8988. function tagOriginalRowOrder(tbody) {
  8989. let idx = 0;
  8990. Array.from(tbody.children).forEach(tr => {
  8991. if (!tr.querySelector('td[colspan]')) {
  8992. if (!tr.hasAttribute('data-orig-idx')) {
  8993. tr.setAttribute('data-orig-idx', idx++);
  8994. }
  8995. }
  8996. });
  8997. }
  8998. function handleHeaderClick(table, th, colIdx) {
  8999. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  9000. let newDir = 'asc';
  9001. if (currentSort.colIdx === colIdx) {
  9002. if (currentSort.dir === 'asc') newDir = 'desc';
  9003. else if (currentSort.dir === 'desc') newDir = 'none';
  9004. else newDir = 'asc';
  9005. } else {
  9006. newDir = 'asc';
  9007. }
  9008. table._activeSort = { colIdx, dir: newDir };
  9009. updateHeaderIcons(table, colIdx, newDir);
  9010. applyTableSort(table, colIdx, newDir, true);
  9011. }
  9012. function updateHeaderIcons(table, activeColIdx, dir) {
  9013. const thead = table.querySelector('thead');
  9014. if (!thead) return;
  9015. const ths = thead.querySelectorAll('th');
  9016. ths.forEach((th, idx) => {
  9017. const icon = th.querySelector('.table-sort-icon');
  9018. if (!icon) return;
  9019. if (idx === activeColIdx && dir !== 'none') {
  9020. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  9021. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  9022. th.classList.add('table-sorted-active');
  9023. } else {
  9024. icon.innerHTML = '⇅';
  9025. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  9026. th.classList.remove('table-sorted-active');
  9027. }
  9028. });
  9029. }
  9030. function applyTableSort(table, colIdx, dir, userInitiated) {
  9031. const tbody = table.querySelector('tbody');
  9032. if (!tbody || tbody.children.length <= 1) return;
  9033. tbody._isSorting = true;
  9034. tagOriginalRowOrder(tbody);
  9035. // Group parent rows and any attached drawer/sub-rows
  9036. const groups = [];
  9037. let currentGroup = null;
  9038. Array.from(tbody.children).forEach(tr => {
  9039. if (tr.querySelector('td[colspan]')) {
  9040. if (currentGroup) {
  9041. currentGroup.subRows.push(tr);
  9042. } else {
  9043. groups.push({ mainRow: tr, subRows: [] });
  9044. }
  9045. } else {
  9046. currentGroup = { mainRow: tr, subRows: [] };
  9047. groups.push(currentGroup);
  9048. }
  9049. });
  9050. if (dir === 'none') {
  9051. groups.sort((a, b) => {
  9052. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  9053. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  9054. return idxA - idxB;
  9055. });
  9056. } else {
  9057. groups.sort((a, b) => {
  9058. const cellA = a.mainRow.children[colIdx];
  9059. const cellB = b.mainRow.children[colIdx];
  9060. const res = compareTableCells(cellA, cellB);
  9061. return dir === 'asc' ? res : -res;
  9062. });
  9063. }
  9064. // Re-append rows in sorted order
  9065. groups.forEach(g => {
  9066. tbody.appendChild(g.mainRow);
  9067. g.subRows.forEach(sub => tbody.appendChild(sub));
  9068. });
  9069. tbody._isSorting = false;
  9070. }
  9071. function getCellRawText(cell) {
  9072. if (!cell) return '';
  9073. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  9074. const input = cell.querySelector('input, select');
  9075. if (input) {
  9076. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  9077. return input.value;
  9078. }
  9079. return cell.innerText.trim();
  9080. }
  9081. function parseTrafficToNumber(str) {
  9082. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  9083. if (!m) return null;
  9084. const num = parseFloat(m[1].replace(/,/g, ''));
  9085. if (isNaN(num)) return null;
  9086. const unit = m[2].toUpperCase();
  9087. let mult = 1;
  9088. if (unit.startsWith('K')) mult = 1024;
  9089. else if (unit.startsWith('M')) mult = 1024 * 1024;
  9090. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  9091. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  9092. return num * mult;
  9093. }
  9094. function parseIpToNumber(str) {
  9095. const clean = str.replace(/^[!~]/, '').trim();
  9096. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  9097. if (!m) return null;
  9098. const o1 = parseInt(m[1], 10);
  9099. const o2 = parseInt(m[2], 10);
  9100. const o3 = parseInt(m[3], 10);
  9101. const o4 = parseInt(m[4], 10);
  9102. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  9103. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  9104. }
  9105. function parseCompoundPackets(str) {
  9106. const m = str.match(/^([\d,]+)p/);
  9107. if (!m) return null;
  9108. return parseInt(m[1].replace(/,/g, ''), 10);
  9109. }
  9110. function compareTableCells(cellA, cellB) {
  9111. const a = getCellRawText(cellA);
  9112. const b = getCellRawText(cellB);
  9113. if (a === '' && b !== '') return 1;
  9114. if (b === '' && a !== '') return -1;
  9115. if (a === b) return 0;
  9116. // 1. IP Addresses / CIDR
  9117. const ipA = parseIpToNumber(a);
  9118. const ipB = parseIpToNumber(b);
  9119. if (ipA !== null && ipB !== null) return ipA - ipB;
  9120. // 2. Packet counts (e.g. "1,250p / 45 KB")
  9121. const pktA = parseCompoundPackets(a);
  9122. const pktB = parseCompoundPackets(b);
  9123. if (pktA !== null && pktB !== null) return pktA - pktB;
  9124. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  9125. const trafA = parseTrafficToNumber(a);
  9126. const trafB = parseTrafficToNumber(b);
  9127. if (trafA !== null && trafB !== null) return trafA - trafB;
  9128. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  9129. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  9130. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  9131. const numA = Number(cleanNumA);
  9132. const numB = Number(cleanNumB);
  9133. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  9134. return numA - numB;
  9135. }
  9136. // 5. Natural case-insensitive string compare
  9137. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  9138. }
  9139. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  9140. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  9141. const docTableObserver = new MutationObserver((mutations) => {
  9142. let needsInit = false;
  9143. for (const m of mutations) {
  9144. for (const node of m.addedNodes) {
  9145. if (node.nodeType === 1) {
  9146. if (node.tagName === 'TABLE' || (node.querySelector && node.querySelector('table'))) {
  9147. needsInit = true;
  9148. break;
  9149. }
  9150. }
  9151. }
  9152. if (needsInit) break;
  9153. }
  9154. if (needsInit) {
  9155. initTableSorting();
  9156. }
  9157. });
  9158. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  9159. }