app.js 513 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249
  1. // DebTik - Debian Linux Router Frontend Application Logic
  2. let state = {
  3. interfaces: [],
  4. vlans: [],
  5. systemStatus: null,
  6. vpnStatus: null,
  7. routes: [],
  8. activeTab: 'dashboard',
  9. fwSubTab: 'filter',
  10. bridgeSubTab: 'bridges',
  11. bridges: [],
  12. bridgePorts: [],
  13. bridgeVLANs: [],
  14. bridgeHosts: [],
  15. bridgeSummary: null,
  16. routesSubTab: 'routes',
  17. pppSubTab: 'secrets',
  18. eoipTunnels: [],
  19. pppSecrets: [],
  20. pppProfiles: [],
  21. pppActiveSessions: [],
  22. pppoeServer: null,
  23. pptpServer: null,
  24. l2tpServer: null,
  25. ipsecServer: null,
  26. ifaceFilter: 'all',
  27. currentModalIface: null,
  28. isPolling: true,
  29. expandedParents: new Set(['eth0']),
  30. pppoeData: null,
  31. wgData: null,
  32. ipsecData: null,
  33. l2tpData: null,
  34. pptpData: null,
  35. fwSummary: null,
  36. filterRules: [],
  37. natRules: [],
  38. mangleRules: [],
  39. addressLists: [],
  40. connections: [],
  41. policyRules: [],
  42. routingTables: [],
  43. routingFilters: [],
  44. filterChainSelected: 'all',
  45. activeToolsSubTab: 'ping',
  46. dhcpClients: [],
  47. dhcpSummary: null
  48. };
  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: 'BIRD 2 BGP Multi-Instance peering sessions, advertised networks, and BGP routing table (RIB)' },
  102. ospf: { title: 'OSPF Routing (/routing ospf)', sub: 'BIRD 2 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: 'BIRD 2 dynamic routing engine' },
  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. switchOspfTab(state.activeOspfTab || 'instances');
  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 FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  1610. function switchIpsecModalTab(tab) {
  1611. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  1612. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  1613. const p1Content = document.getElementById('ipsec-tab-content-p1');
  1614. const p2Content = document.getElementById('ipsec-tab-content-p2');
  1615. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  1616. if (tab === 'p1') {
  1617. if (p1Tab) {
  1618. p1Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-amber-500 text-amber-300 transition flex items-center gap-2';
  1619. }
  1620. if (p2Tab) {
  1621. p2Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  1622. }
  1623. if (p1Content) p1Content.classList.remove('hidden');
  1624. if (p2Content) p2Content.classList.add('hidden');
  1625. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  1626. } else {
  1627. if (p1Tab) {
  1628. p1Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  1629. }
  1630. if (p2Tab) {
  1631. p2Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-cyan-300 transition flex items-center gap-2';
  1632. }
  1633. if (p1Content) p1Content.classList.add('hidden');
  1634. if (p2Content) p2Content.classList.remove('hidden');
  1635. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  1636. }
  1637. }
  1638. function toggleIpsecPhaseStep() {
  1639. const p1Content = document.getElementById('ipsec-tab-content-p1');
  1640. if (p1Content && !p1Content.classList.contains('hidden')) {
  1641. switchIpsecModalTab('p2');
  1642. } else {
  1643. switchIpsecModalTab('p1');
  1644. }
  1645. }
  1646. function toggleIpsecPskVisibility() {
  1647. const pskInput = document.getElementById('ipsec-modal-psk');
  1648. if (!pskInput) return;
  1649. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  1650. }
  1651. function addIpsecLocalSubnet(val = '') {
  1652. const container = document.getElementById('ipsec-modal-local-subnets-container');
  1653. if (!container) return;
  1654. const row = document.createElement('div');
  1655. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  1656. row.innerHTML = `
  1657. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 192.168.10.0/24 or 10.0.1.0/24" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-cyan-500">
  1658. <button type="button" onclick="this.closest('.ipsec-subnet-row').remove()" class="w-7 h-7 flex items-center justify-center bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-400 border border-slate-700 rounded-lg text-base font-bold transition" title="Remove local subnet">-</button>
  1659. `;
  1660. container.appendChild(row);
  1661. }
  1662. function addIpsecRemoteSubnet(val = '') {
  1663. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  1664. if (!container) return;
  1665. const row = document.createElement('div');
  1666. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  1667. row.innerHTML = `
  1668. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 192.168.20.0/24 or 10.0.2.0/24" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-purple-500">
  1669. <button type="button" onclick="this.closest('.ipsec-subnet-row').remove()" class="w-7 h-7 flex items-center justify-center bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-400 border border-slate-700 rounded-lg text-base font-bold transition" title="Remove remote subnet">-</button>
  1670. `;
  1671. container.appendChild(row);
  1672. }
  1673. function updateIpsecEspProposalFromPFS(val) {
  1674. const prop = document.getElementById('ipsec-modal-espprop');
  1675. if (!prop) return;
  1676. if (val === 'none') {
  1677. prop.value = 'aes256-sha256,aes128-sha256,default';
  1678. } else {
  1679. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  1680. }
  1681. }
  1682. async function loadIPSec(populateInputs = true) {
  1683. try {
  1684. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1685. const list = await res.json();
  1686. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1687. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1688. const badge = document.getElementById('ipsec-sas-badge');
  1689. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1690. const tbody = document.getElementById('ipsec-table-body');
  1691. const empty = document.getElementById('ipsec-empty');
  1692. if (!tbody) return;
  1693. tbody.innerHTML = '';
  1694. if (state.ipsecTunnels.length === 0) {
  1695. if (empty) empty.classList.remove('hidden');
  1696. } else {
  1697. if (empty) empty.classList.add('hidden');
  1698. state.ipsecTunnels.forEach(c => {
  1699. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1700. const tr = document.createElement('tr');
  1701. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  1702. // Local subnets tags
  1703. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  1704. const localBadges = localList.map(s => `<span class="px-1.5 py-0.5 rounded bg-cyan-950/60 border border-cyan-800/60 text-cyan-300 font-mono text-[10px] mr-1">${escapeHtml(s)}</span>`).join('');
  1705. // Remote subnets tags
  1706. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  1707. const remoteBadges = remoteList.map(s => `<span class="px-1.5 py-0.5 rounded bg-purple-950/60 border border-purple-800/60 text-purple-300 font-mono text-[10px] mr-1">${escapeHtml(s)}</span>`).join('');
  1708. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  1709. const p2Name = c.phase2_name || `${c.name}_p2`;
  1710. tr.innerHTML = `
  1711. <td class="py-2.5 px-3 text-center">
  1712. ${isEstablished ? `
  1713. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  1714. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  1715. <span>UP</span>
  1716. </span>
  1717. ` : (c.disabled ? `
  1718. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  1719. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  1720. <span>DOWN</span>
  1721. </span>
  1722. ` : `
  1723. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  1724. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  1725. <span>IDLE</span>
  1726. </span>
  1727. `)}
  1728. </td>
  1729. <td class="py-2.5 px-4 font-bold text-white">
  1730. <div class="flex items-center gap-2">
  1731. <span class="text-amber-400">🛡</span>
  1732. <div>
  1733. <div>${escapeHtml(c.name)}</div>
  1734. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  1735. </div>
  1736. </div>
  1737. </td>
  1738. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  1739. <td class="py-2.5 px-4 font-sans">
  1740. <div class="flex items-center gap-1.5">
  1741. <span class="px-1.5 py-0.5 rounded bg-amber-500/10 text-amber-300 border border-amber-500/30 font-mono text-[10px] font-semibold">${ikeVersionBadge}</span>
  1742. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  1743. </div>
  1744. </td>
  1745. <td class="py-2.5 px-4">
  1746. <div class="space-y-1">
  1747. <div class="flex items-center flex-wrap gap-1">
  1748. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  1749. ${localBadges}
  1750. </div>
  1751. <div class="flex items-center flex-wrap gap-1">
  1752. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  1753. ${remoteBadges}
  1754. </div>
  1755. </div>
  1756. </td>
  1757. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  1758. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  1759. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  1760. </div>
  1761. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  1762. </td>
  1763. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  1764. ${isEstablished ? `
  1765. <button onclick="stopIPSecTunnel('${c.name}')" class="px-2 py-0.5 text-xs bg-rose-500/20 text-rose-400 hover:bg-rose-500/30 rounded border border-rose-500/30 font-medium">Bring Down</button>
  1766. ` : `
  1767. <button onclick="startIPSecTunnel('${c.name}')" class="px-2 py-0.5 text-xs bg-emerald-500/20 text-emerald-400 hover:bg-emerald-500/30 rounded border border-emerald-500/30 font-semibold">Bring Up</button>
  1768. `}
  1769. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1770. ${c.disabled ? 'Enable' : 'Disable'}
  1771. </button>
  1772. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  1773. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1774. </td>
  1775. `;
  1776. tbody.appendChild(tr);
  1777. });
  1778. }
  1779. } catch (err) {
  1780. console.error('Failed to load IPSec:', err);
  1781. }
  1782. }
  1783. function openAddIPSecModal() {
  1784. document.getElementById('ipsec-modal-title').innerText = 'Configure IPSec Site-to-Site Tunnel';
  1785. // Phase 1 Fields
  1786. document.getElementById('ipsec-modal-name').value = `tunnel-${(state.ipsecTunnels || []).length + 1}`;
  1787. document.getElementById('ipsec-modal-name').readOnly = false;
  1788. document.getElementById('ipsec-modal-ikeversion').value = 'ikev2';
  1789. document.getElementById('ipsec-modal-remotegw').value = '';
  1790. document.getElementById('ipsec-modal-psk').value = '';
  1791. document.getElementById('ipsec-modal-ikeprop').value = 'aes256-sha256-modp2048,aes128-sha256-modp2048,default';
  1792. document.getElementById('ipsec-modal-ikekeylife').value = '86400';
  1793. document.getElementById('ipsec-modal-localid').value = '';
  1794. document.getElementById('ipsec-modal-remoteid').value = '';
  1795. document.getElementById('ipsec-modal-dpd').value = 'on-demand';
  1796. // Phase 2 Fields
  1797. document.getElementById('ipsec-modal-p2name').value = `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`;
  1798. document.getElementById('ipsec-modal-espprop').value = 'aes256-sha256-modp2048,aes128-sha256-modp2048,default';
  1799. document.getElementById('ipsec-modal-pfsgroup').value = 'modp2048';
  1800. document.getElementById('ipsec-modal-autostart').checked = true;
  1801. document.getElementById('ipsec-modal-disabled').checked = false;
  1802. // Clear & Populate default dynamic subnets
  1803. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  1804. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  1805. if (localContainer) {
  1806. localContainer.innerHTML = '';
  1807. addIpsecLocalSubnet('192.168.10.0/24');
  1808. }
  1809. if (remoteContainer) {
  1810. remoteContainer.innerHTML = '';
  1811. addIpsecRemoteSubnet('192.168.20.0/24');
  1812. }
  1813. switchIpsecModalTab('p1');
  1814. document.getElementById('ipsec-modal').classList.remove('hidden');
  1815. }
  1816. function openEditIPSecModal(name) {
  1817. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  1818. if (!conn) return;
  1819. document.getElementById('ipsec-modal-title').innerText = `Edit IPSec Tunnel: ${name}`;
  1820. // Phase 1 Fields
  1821. document.getElementById('ipsec-modal-name').value = conn.name;
  1822. document.getElementById('ipsec-modal-name').readOnly = true;
  1823. document.getElementById('ipsec-modal-ikeversion').value = conn.ike_version || 'ikev2';
  1824. document.getElementById('ipsec-modal-remotegw').value = conn.remote_addrs || '';
  1825. document.getElementById('ipsec-modal-psk').value = conn.preshared_key || '';
  1826. document.getElementById('ipsec-modal-ikeprop').value = conn.ike_proposals || 'aes256-sha256-modp2048,default';
  1827. document.getElementById('ipsec-modal-ikekeylife').value = conn.ike_keylife || 86400;
  1828. document.getElementById('ipsec-modal-localid').value = conn.local_id || '';
  1829. document.getElementById('ipsec-modal-remoteid').value = conn.remote_id || '';
  1830. document.getElementById('ipsec-modal-dpd').value = conn.dpd || 'on-demand';
  1831. // Phase 2 Fields
  1832. document.getElementById('ipsec-modal-p2name').value = conn.phase2_name || `${conn.name}_p2`;
  1833. document.getElementById('ipsec-modal-espprop').value = conn.esp_proposals || 'aes256-sha256-modp2048,default';
  1834. document.getElementById('ipsec-modal-pfsgroup').value = conn.pfs_group || 'modp2048';
  1835. document.getElementById('ipsec-modal-autostart').checked = conn.auto_start ?? true;
  1836. document.getElementById('ipsec-modal-disabled').checked = !!conn.disabled;
  1837. // Populate dynamic subnets
  1838. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  1839. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  1840. if (localContainer) {
  1841. localContainer.innerHTML = '';
  1842. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  1843. locals.forEach(s => addIpsecLocalSubnet(s));
  1844. }
  1845. if (remoteContainer) {
  1846. remoteContainer.innerHTML = '';
  1847. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  1848. remotes.forEach(s => addIpsecRemoteSubnet(s));
  1849. }
  1850. switchIpsecModalTab('p1');
  1851. document.getElementById('ipsec-modal').classList.remove('hidden');
  1852. }
  1853. function closeAddIPSecModal() {
  1854. document.getElementById('ipsec-modal').classList.add('hidden');
  1855. }
  1856. async function submitSaveIPSec(e) {
  1857. e.preventDefault();
  1858. const name = document.getElementById('ipsec-modal-name').value.trim();
  1859. const ikeVersion = document.getElementById('ipsec-modal-ikeversion').value;
  1860. const remotegw = document.getElementById('ipsec-modal-remotegw').value.trim();
  1861. const psk = document.getElementById('ipsec-modal-psk').value;
  1862. const ikeProposals = document.getElementById('ipsec-modal-ikeprop').value.trim();
  1863. const ikeKeylife = parseInt(document.getElementById('ipsec-modal-ikekeylife').value, 10) || 86400;
  1864. const localId = document.getElementById('ipsec-modal-localid').value.trim();
  1865. const remoteId = document.getElementById('ipsec-modal-remoteid').value.trim();
  1866. const dpd = document.getElementById('ipsec-modal-dpd').value;
  1867. const phase2Name = document.getElementById('ipsec-modal-p2name').value.trim() || `${name}_p2`;
  1868. const espProposals = document.getElementById('ipsec-modal-espprop').value.trim();
  1869. const pfsGroup = document.getElementById('ipsec-modal-pfsgroup').value;
  1870. const autostart = document.getElementById('ipsec-modal-autostart').checked;
  1871. const disabled = document.getElementById('ipsec-modal-disabled').checked;
  1872. // Scrape dynamic local and remote subnets
  1873. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  1874. const localSubnets = [];
  1875. localInputs.forEach(inp => {
  1876. const v = inp.value.trim();
  1877. if (v) localSubnets.push(v);
  1878. });
  1879. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  1880. const remoteSubnets = [];
  1881. remoteInputs.forEach(inp => {
  1882. const v = inp.value.trim();
  1883. if (v) remoteSubnets.push(v);
  1884. });
  1885. try {
  1886. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  1887. method: 'POST',
  1888. headers: { 'Content-Type': 'application/json' },
  1889. body: JSON.stringify({
  1890. name,
  1891. ike_version: ikeVersion,
  1892. local_addrs: '%any',
  1893. remote_addrs: remotegw,
  1894. preshared_key: psk,
  1895. ike_proposals: ikeProposals,
  1896. ike_keylife: ikeKeylife,
  1897. local_id: localId,
  1898. remote_id: remoteId,
  1899. dpd: dpd,
  1900. phase2_name: phase2Name,
  1901. esp_proposals: espProposals,
  1902. pfs_group: pfsGroup,
  1903. pfs: pfsGroup !== 'none',
  1904. local_subnets: localSubnets,
  1905. remote_subnets: remoteSubnets,
  1906. local_subnet: localSubnets[0] || '0.0.0.0/0',
  1907. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  1908. auto_start: autostart,
  1909. disabled
  1910. })
  1911. });
  1912. if (res.ok) {
  1913. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  1914. closeAddIPSecModal();
  1915. loadIPSec(false);
  1916. } else {
  1917. const err = await res.json();
  1918. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  1919. }
  1920. } catch (err) {
  1921. showToast('Error', err.message, 'error');
  1922. }
  1923. }
  1924. async function startIPSecTunnel(name) {
  1925. try {
  1926. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1927. if (res.ok) {
  1928. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  1929. setTimeout(() => loadIPSec(false), 2000);
  1930. }
  1931. } catch (err) {
  1932. showToast('Error', err.message, 'error');
  1933. }
  1934. }
  1935. async function stopIPSecTunnel(name) {
  1936. try {
  1937. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1938. if (res.ok) {
  1939. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  1940. loadIPSec(false);
  1941. }
  1942. } catch (err) {
  1943. showToast('Error', err.message, 'error');
  1944. }
  1945. }
  1946. async function toggleIPSecState(name, enable) {
  1947. try {
  1948. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  1949. method: 'POST',
  1950. headers: { 'Content-Type': 'application/json' },
  1951. body: JSON.stringify({ enabled: enable })
  1952. });
  1953. if (res.ok) {
  1954. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  1955. loadIPSec(false);
  1956. }
  1957. } catch (err) {
  1958. showToast('Error', err.message, 'error');
  1959. }
  1960. }
  1961. async function deleteIPSecConn(name) {
  1962. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  1963. try {
  1964. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1965. if (res.ok) {
  1966. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  1967. loadIPSec(false);
  1968. fetchData(false);
  1969. }
  1970. } catch (err) {
  1971. showToast('Error', err.message, 'error');
  1972. }
  1973. }
  1974. // ======================== L2TP Multi-Instance ========================
  1975. async function loadL2TP(populateInputs = true) {
  1976. try {
  1977. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  1978. const list = await res.json();
  1979. state.l2tpList = Array.isArray(list) ? list : [];
  1980. const badge = document.getElementById('l2tp-count-badge');
  1981. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  1982. const tbody = document.getElementById('l2tp-table-body');
  1983. const empty = document.getElementById('l2tp-empty');
  1984. if (!tbody) return;
  1985. tbody.innerHTML = '';
  1986. if (state.l2tpList.length === 0) {
  1987. if (empty) empty.classList.remove('hidden');
  1988. } else {
  1989. if (empty) empty.classList.add('hidden');
  1990. state.l2tpList.forEach(inst => {
  1991. const tr = document.createElement('tr');
  1992. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1993. tr.innerHTML = `
  1994. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1995. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1996. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.connect_to}</td>
  1997. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1998. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1999. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  2000. <td class="py-2.5 px-3 text-center">
  2001. <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'}">
  2002. ${inst.default_route ? 'Yes' : 'No'}
  2003. </span>
  2004. </td>
  2005. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2006. ${inst.running ? `
  2007. <button onclick="disconnectL2TPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2008. ` : `
  2009. <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>
  2010. `}
  2011. <button onclick="toggleL2TPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2012. ${inst.disabled ? 'Enable' : 'Disable'}
  2013. </button>
  2014. <button onclick="openEditL2TPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2015. <button onclick="deleteL2TPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2016. </td>
  2017. `;
  2018. tbody.appendChild(tr);
  2019. });
  2020. }
  2021. } catch (err) {
  2022. console.error('Failed to load L2TP:', err);
  2023. }
  2024. }
  2025. function openAddL2TPModal() {
  2026. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2027. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2028. document.getElementById('l2tp-modal-name').readOnly = false;
  2029. document.getElementById('l2tp-modal-server').value = '';
  2030. document.getElementById('l2tp-modal-user').value = '';
  2031. document.getElementById('l2tp-modal-pass').value = '';
  2032. document.getElementById('l2tp-modal-ipsec').value = '';
  2033. document.getElementById('l2tp-modal-defroute').checked = true;
  2034. document.getElementById('l2tp-modal-disabled').checked = false;
  2035. document.getElementById('l2tp-modal').classList.remove('hidden');
  2036. }
  2037. function openEditL2TPModal(name) {
  2038. const inst = (state.l2tpList || []).find(i => i.name === name);
  2039. if (!inst) return;
  2040. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2041. document.getElementById('l2tp-modal-name').value = inst.name;
  2042. document.getElementById('l2tp-modal-name').readOnly = true;
  2043. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2044. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2045. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2046. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2047. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2048. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2049. document.getElementById('l2tp-modal').classList.remove('hidden');
  2050. }
  2051. function closeL2TPModal() {
  2052. document.getElementById('l2tp-modal').classList.add('hidden');
  2053. }
  2054. async function submitSaveL2TP(e) {
  2055. e.preventDefault();
  2056. const name = document.getElementById('l2tp-modal-name').value.trim();
  2057. const server = document.getElementById('l2tp-modal-server').value.trim();
  2058. const user = document.getElementById('l2tp-modal-user').value.trim();
  2059. const pass = document.getElementById('l2tp-modal-pass').value;
  2060. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2061. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2062. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2063. try {
  2064. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2065. method: 'POST',
  2066. headers: { 'Content-Type': 'application/json' },
  2067. body: JSON.stringify({
  2068. name,
  2069. connect_to: server,
  2070. username: user,
  2071. password: pass,
  2072. ipsec_secret: ipsec,
  2073. default_route: defRoute,
  2074. disabled
  2075. })
  2076. });
  2077. if (res.ok) {
  2078. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2079. closeL2TPModal();
  2080. loadL2TP(false);
  2081. fetchData(false);
  2082. }
  2083. } catch (err) {
  2084. showToast('Error', err.message, 'error');
  2085. }
  2086. }
  2087. async function connectL2TPInstance(name) {
  2088. try {
  2089. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2090. if (res.ok) {
  2091. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2092. setTimeout(() => loadL2TP(false), 2000);
  2093. }
  2094. } catch (err) {
  2095. showToast('Error', err.message, 'error');
  2096. }
  2097. }
  2098. async function disconnectL2TPInstance(name) {
  2099. try {
  2100. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2101. if (res.ok) {
  2102. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2103. loadL2TP(false);
  2104. }
  2105. } catch (err) {
  2106. showToast('Error', err.message, 'error');
  2107. }
  2108. }
  2109. async function toggleL2TPState(name, enable) {
  2110. try {
  2111. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2112. method: 'POST',
  2113. headers: { 'Content-Type': 'application/json' },
  2114. body: JSON.stringify({ enabled: enable })
  2115. });
  2116. if (res.ok) {
  2117. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2118. loadL2TP(false);
  2119. }
  2120. } catch (err) {
  2121. showToast('Error', err.message, 'error');
  2122. }
  2123. }
  2124. async function deleteL2TPInstance(name) {
  2125. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2126. try {
  2127. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2128. if (res.ok) {
  2129. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2130. loadL2TP(false);
  2131. fetchData(false);
  2132. }
  2133. } catch (err) {
  2134. showToast('Error', err.message, 'error');
  2135. }
  2136. }
  2137. // ======================== PPTP Multi-Instance ========================
  2138. async function loadPPTP(populateInputs = true) {
  2139. try {
  2140. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2141. const list = await res.json();
  2142. state.pptpList = Array.isArray(list) ? list : [];
  2143. const badge = document.getElementById('pptp-count-badge');
  2144. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2145. const tbody = document.getElementById('pptp-table-body');
  2146. const empty = document.getElementById('pptp-empty');
  2147. if (!tbody) return;
  2148. tbody.innerHTML = '';
  2149. if (state.pptpList.length === 0) {
  2150. if (empty) empty.classList.remove('hidden');
  2151. } else {
  2152. if (empty) empty.classList.add('hidden');
  2153. state.pptpList.forEach(inst => {
  2154. const tr = document.createElement('tr');
  2155. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2156. tr.innerHTML = `
  2157. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2158. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  2159. <td class="py-2.5 px-3 text-purple-400 font-mono">${inst.connect_to}</td>
  2160. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  2161. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  2162. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  2163. <td class="py-2.5 px-3 text-center">
  2164. <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'}">
  2165. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2166. </span>
  2167. </td>
  2168. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2169. ${inst.running ? `
  2170. <button onclick="disconnectPPTPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2171. ` : `
  2172. <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>
  2173. `}
  2174. <button onclick="togglePPTPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2175. ${inst.disabled ? 'Enable' : 'Disable'}
  2176. </button>
  2177. <button onclick="openEditPPTPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2178. <button onclick="deletePPTPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2179. </td>
  2180. `;
  2181. tbody.appendChild(tr);
  2182. });
  2183. }
  2184. } catch (err) {
  2185. console.error('Failed to load PPTP:', err);
  2186. }
  2187. }
  2188. function openAddPPTPModal() {
  2189. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2190. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2191. document.getElementById('pptp-modal-name').readOnly = false;
  2192. document.getElementById('pptp-modal-server').value = '';
  2193. document.getElementById('pptp-modal-user').value = '';
  2194. document.getElementById('pptp-modal-pass').value = '';
  2195. document.getElementById('pptp-modal-mppe').checked = true;
  2196. document.getElementById('pptp-modal-defroute').checked = true;
  2197. document.getElementById('pptp-modal-disabled').checked = false;
  2198. document.getElementById('pptp-modal').classList.remove('hidden');
  2199. }
  2200. function openEditPPTPModal(name) {
  2201. const inst = (state.pptpList || []).find(i => i.name === name);
  2202. if (!inst) return;
  2203. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2204. document.getElementById('pptp-modal-name').value = inst.name;
  2205. document.getElementById('pptp-modal-name').readOnly = true;
  2206. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2207. document.getElementById('pptp-modal-user').value = inst.username || '';
  2208. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2209. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2210. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2211. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2212. document.getElementById('pptp-modal').classList.remove('hidden');
  2213. }
  2214. function closePPTPModal() {
  2215. document.getElementById('pptp-modal').classList.add('hidden');
  2216. }
  2217. async function submitSavePPTP(e) {
  2218. e.preventDefault();
  2219. const name = document.getElementById('pptp-modal-name').value.trim();
  2220. const server = document.getElementById('pptp-modal-server').value.trim();
  2221. const user = document.getElementById('pptp-modal-user').value.trim();
  2222. const pass = document.getElementById('pptp-modal-pass').value;
  2223. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2224. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2225. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2226. try {
  2227. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2228. method: 'POST',
  2229. headers: { 'Content-Type': 'application/json' },
  2230. body: JSON.stringify({
  2231. name,
  2232. connect_to: server,
  2233. username: user,
  2234. password: pass,
  2235. require_mppe: mppe,
  2236. default_route: defRoute,
  2237. auto_reconnect: true,
  2238. disabled
  2239. })
  2240. });
  2241. if (res.ok) {
  2242. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2243. closePPTPModal();
  2244. loadPPTP(false);
  2245. fetchData(false);
  2246. }
  2247. } catch (err) {
  2248. showToast('Error', err.message, 'error');
  2249. }
  2250. }
  2251. async function connectPPTPInstance(name) {
  2252. try {
  2253. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2254. if (res.ok) {
  2255. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2256. setTimeout(() => loadPPTP(false), 2000);
  2257. }
  2258. } catch (err) {
  2259. showToast('Error', err.message, 'error');
  2260. }
  2261. }
  2262. async function disconnectPPTPInstance(name) {
  2263. try {
  2264. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2265. if (res.ok) {
  2266. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2267. loadPPTP(false);
  2268. }
  2269. } catch (err) {
  2270. showToast('Error', err.message, 'error');
  2271. }
  2272. }
  2273. async function togglePPTPState(name, enable) {
  2274. try {
  2275. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2276. method: 'POST',
  2277. headers: { 'Content-Type': 'application/json' },
  2278. body: JSON.stringify({ enabled: enable })
  2279. });
  2280. if (res.ok) {
  2281. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2282. loadPPTP(false);
  2283. }
  2284. } catch (err) {
  2285. showToast('Error', err.message, 'error');
  2286. }
  2287. }
  2288. async function deletePPTPInstance(name) {
  2289. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2290. try {
  2291. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2292. if (res.ok) {
  2293. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2294. loadPPTP(false);
  2295. fetchData(false);
  2296. }
  2297. } catch (err) {
  2298. showToast('Error', err.message, 'error');
  2299. }
  2300. }
  2301. // ---------------- Modal & Helper Functions ----------------
  2302. function openVlanModal(defaultParent = '') {
  2303. const select = document.getElementById('vlan-parent');
  2304. select.innerHTML = '';
  2305. const allIfaces = state.interfaces || [];
  2306. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2307. if (eligible.length === 0) {
  2308. const opt = document.createElement('option');
  2309. opt.value = '';
  2310. opt.innerText = 'No VLAN-capable interfaces available';
  2311. select.appendChild(opt);
  2312. } else {
  2313. eligible.forEach(i => {
  2314. const opt = document.createElement('option');
  2315. opt.value = i.name;
  2316. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2317. if (i.name === defaultParent) opt.selected = true;
  2318. select.appendChild(opt);
  2319. });
  2320. }
  2321. document.getElementById('vlan-id').value = '';
  2322. document.getElementById('vlan-name').value = '';
  2323. document.getElementById('vlan-ip').value = '';
  2324. document.getElementById('vlan-desc').value = '';
  2325. autoSuggestVlanName();
  2326. document.getElementById('vlan-modal').classList.remove('hidden');
  2327. }
  2328. function closeVlanModal() {
  2329. document.getElementById('vlan-modal').classList.add('hidden');
  2330. }
  2331. function autoSuggestVlanName() {
  2332. const parent = document.getElementById('vlan-parent').value;
  2333. if (!parent) return;
  2334. const id = document.getElementById('vlan-id').value;
  2335. const nameInput = document.getElementById('vlan-name');
  2336. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  2337. }
  2338. function setSubnetPreset(cidr) {
  2339. const ipInput = document.getElementById('vlan-ip');
  2340. const id = document.getElementById('vlan-id').value || '10';
  2341. ipInput.value = `192.168.${id}.1${cidr}`;
  2342. }
  2343. async function submitCreateVlan(e) {
  2344. e.preventDefault();
  2345. const btn = document.getElementById('vlan-submit-btn');
  2346. btn.disabled = true;
  2347. btn.innerText = 'Creating...';
  2348. const parent = document.getElementById('vlan-parent').value;
  2349. if (!parent) {
  2350. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  2351. btn.disabled = false;
  2352. btn.innerText = 'Create VLAN';
  2353. return;
  2354. }
  2355. const id = parseInt(document.getElementById('vlan-id').value, 10);
  2356. const name = document.getElementById('vlan-name').value.trim();
  2357. const ip = document.getElementById('vlan-ip').value.trim();
  2358. const role = document.getElementById('vlan-role').value;
  2359. const desc = document.getElementById('vlan-desc').value.trim();
  2360. try {
  2361. const res = await fetch(`${API_BASE}/vlans`, {
  2362. method: 'POST',
  2363. headers: { 'Content-Type': 'application/json' },
  2364. body: JSON.stringify({
  2365. parent_name: parent,
  2366. vlan_id: id,
  2367. name: name,
  2368. ip_address: ip,
  2369. role: role,
  2370. description: desc,
  2371. mtu: 1500,
  2372. auto_up: true
  2373. })
  2374. });
  2375. const data = await res.json();
  2376. if (res.ok) {
  2377. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  2378. state.expandedParents.add(parent);
  2379. closeVlanModal();
  2380. await fetchData(true);
  2381. if (state.activeTab !== 'interfaces') navigate('interfaces');
  2382. } else {
  2383. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  2384. }
  2385. } catch (err) {
  2386. showToast('Error', err.message, 'error');
  2387. } finally {
  2388. btn.disabled = false;
  2389. btn.innerText = 'Create VLAN';
  2390. }
  2391. }
  2392. async function confirmDeleteVlan(name) {
  2393. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  2394. try {
  2395. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2396. if (res.ok) {
  2397. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  2398. closeIfaceModal();
  2399. fetchData(true);
  2400. }
  2401. } catch (err) {
  2402. showToast('Error', err.message, 'error');
  2403. }
  2404. }
  2405. function openIfaceModal(name) {
  2406. const iface = (state.interfaces || []).find(i => i.name === name);
  2407. if (!iface) return;
  2408. state.currentModalIface = iface.name;
  2409. document.getElementById('modal-iface-name').innerText = iface.name;
  2410. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  2411. document.getElementById('modal-iface-mtu').value = iface.mtu;
  2412. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  2413. document.getElementById('modal-iface-desc').value = iface.description || '';
  2414. const delBtn = document.getElementById('modal-delete-vlan-btn');
  2415. if (iface.is_vlan) {
  2416. delBtn.classList.remove('hidden');
  2417. } else {
  2418. delBtn.classList.add('hidden');
  2419. }
  2420. renderModalIPs(iface);
  2421. document.getElementById('iface-modal').classList.remove('hidden');
  2422. }
  2423. function renderModalIPs(iface) {
  2424. const container = document.getElementById('modal-ip-list');
  2425. container.innerHTML = '';
  2426. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  2427. if (addrs.length === 0) {
  2428. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  2429. return;
  2430. }
  2431. addrs.forEach(addr => {
  2432. const row = document.createElement('div');
  2433. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  2434. row.innerHTML = `
  2435. <span class="text-white">${addr}</span>
  2436. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  2437. `;
  2438. container.appendChild(row);
  2439. });
  2440. }
  2441. function closeIfaceModal() {
  2442. document.getElementById('iface-modal').classList.add('hidden');
  2443. state.currentModalIface = null;
  2444. }
  2445. async function setIfaceState(name, newState) {
  2446. await toggleInterfaceState(name, newState);
  2447. const updated = (state.interfaces || []).find(i => i.name === name);
  2448. if (updated) openIfaceModal(name);
  2449. }
  2450. async function applyMTU() {
  2451. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  2452. try {
  2453. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  2454. method: 'POST',
  2455. headers: { 'Content-Type': 'application/json' },
  2456. body: JSON.stringify({ mtu })
  2457. });
  2458. if (res.ok) {
  2459. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  2460. fetchData(false);
  2461. }
  2462. } catch (err) {
  2463. showToast('Error', err.message, 'error');
  2464. }
  2465. }
  2466. async function addInterfaceIP() {
  2467. const ip = document.getElementById('modal-new-ip').value.trim();
  2468. if (!ip) return;
  2469. try {
  2470. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2471. method: 'POST',
  2472. headers: { 'Content-Type': 'application/json' },
  2473. body: JSON.stringify({ ip })
  2474. });
  2475. if (res.ok) {
  2476. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  2477. document.getElementById('modal-new-ip').value = '';
  2478. await fetchData(false);
  2479. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2480. if (iface) renderModalIPs(iface);
  2481. } else {
  2482. const err = await res.json();
  2483. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  2484. }
  2485. } catch (err) {
  2486. showToast('Error', err.message, 'error');
  2487. }
  2488. }
  2489. async function removeInterfaceIP(ip) {
  2490. if (!confirm(`Remove IP ${ip}?`)) return;
  2491. try {
  2492. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2493. method: 'DELETE',
  2494. headers: { 'Content-Type': 'application/json' },
  2495. body: JSON.stringify({ ip })
  2496. });
  2497. if (res.ok) {
  2498. showToast('IP Removed', `Removed ${ip}`, 'success');
  2499. await fetchData(false);
  2500. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2501. if (iface) renderModalIPs(iface);
  2502. }
  2503. } catch (err) {
  2504. showToast('Error', err.message, 'error');
  2505. }
  2506. }
  2507. async function saveInterfaceMetadata() {
  2508. const role = document.getElementById('modal-iface-role').value;
  2509. const desc = document.getElementById('modal-iface-desc').value.trim();
  2510. try {
  2511. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/metadata`, {
  2512. method: 'POST',
  2513. headers: { 'Content-Type': 'application/json' },
  2514. body: JSON.stringify({ role, description: desc })
  2515. });
  2516. if (res.ok) {
  2517. showToast('Saved', 'Metadata updated', 'success');
  2518. closeIfaceModal();
  2519. fetchData(false);
  2520. }
  2521. } catch (err) {
  2522. showToast('Error', err.message, 'error');
  2523. }
  2524. }
  2525. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  2526. state.fwSubTab = 'filter';
  2527. state.routesSubTab = 'routes';
  2528. function renderRuleFlag(disabled, hasComment) {
  2529. let flags = '';
  2530. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  2531. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  2532. return flags || '<span class="text-slate-600">-</span>';
  2533. }
  2534. function renderActionBadge(action) {
  2535. const act = (action || '').toLowerCase();
  2536. let color = 'bg-slate-800 text-slate-300';
  2537. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  2538. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  2539. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  2540. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  2541. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  2542. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  2543. }
  2544. function switchFWSubTab(tab) {
  2545. state.fwSubTab = tab;
  2546. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  2547. tabs.forEach(t => {
  2548. const panel = document.getElementById(`fw-subtab-${t}`);
  2549. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  2550. if (panel) {
  2551. if (t === tab) panel.classList.remove('hidden');
  2552. else panel.classList.add('hidden');
  2553. }
  2554. if (btn) {
  2555. if (t === tab) {
  2556. 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';
  2557. } else {
  2558. 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';
  2559. }
  2560. }
  2561. });
  2562. const addBtn = document.getElementById('fw-primary-add-btn');
  2563. if (addBtn) {
  2564. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  2565. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  2566. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  2567. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  2568. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  2569. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  2570. }
  2571. if (tab === 'geo') loadGeoIP();
  2572. if (tab === 'connections') loadConnections();
  2573. setTimeout(initTableSorting, 50);
  2574. }
  2575. function openCurrentFWModal() {
  2576. if (state.fwSubTab === 'filter') openAddFilterModal();
  2577. else if (state.fwSubTab === 'nat') openAddNATModal();
  2578. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  2579. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  2580. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  2581. else if (state.fwSubTab === 'connections') loadConnections();
  2582. }
  2583. async function loadFirewall(populateDropdowns = true) {
  2584. try {
  2585. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  2586. fetch(`${API_BASE}/firewall/summary`),
  2587. fetch(`${API_BASE}/firewall/filter`),
  2588. fetch(`${API_BASE}/firewall/nat`),
  2589. fetch(`${API_BASE}/firewall/mangle`),
  2590. fetch(`${API_BASE}/firewall/address-lists`),
  2591. fetch(`${API_BASE}/firewall/geoip/status`),
  2592. fetch(`${API_BASE}/firewall/geoip/countries`)
  2593. ]);
  2594. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  2595. if (filterRes.ok) state.filterRules = await filterRes.json();
  2596. if (natRes.ok) state.natRules = await natRes.json();
  2597. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  2598. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  2599. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  2600. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  2601. // Badges
  2602. const bFilter = document.getElementById('fw-badge-filter');
  2603. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  2604. const bNat = document.getElementById('fw-badge-nat');
  2605. if (bNat) bNat.innerText = (state.natRules || []).length;
  2606. const bMangle = document.getElementById('fw-badge-mangle');
  2607. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  2608. const bAddr = document.getElementById('fw-badge-addrlist');
  2609. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  2610. const bGeo = document.getElementById('fw-badge-geo');
  2611. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  2612. renderFilterRules();
  2613. renderNATRules();
  2614. renderMangleRules();
  2615. renderAddressLists();
  2616. renderGeoCountries();
  2617. if (state.fwSubTab === 'connections') {
  2618. loadConnections();
  2619. }
  2620. } catch (err) {
  2621. console.error('Failed to load firewall:', err);
  2622. }
  2623. }
  2624. // ----------------- Filter Rules -----------------
  2625. function renderFilterRules() {
  2626. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  2627. const tbody = document.getElementById('filter-table-body');
  2628. const empty = document.getElementById('filter-empty');
  2629. if (!tbody) return;
  2630. tbody.innerHTML = '';
  2631. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2632. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2633. if (rules.length === 0) {
  2634. empty?.classList.remove('hidden');
  2635. return;
  2636. }
  2637. empty?.classList.add('hidden');
  2638. rules.forEach((r, idx) => {
  2639. const tr = document.createElement('tr');
  2640. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2641. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2642. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2643. let actionExtra = '';
  2644. if (r.action === 'reject') {
  2645. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  2646. } else if (r.action === 'jump') {
  2647. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  2648. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  2649. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  2650. } else if (r.action === 'log' && r.log_prefix) {
  2651. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  2652. }
  2653. tr.innerHTML = `
  2654. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2655. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2656. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2657. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2658. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2659. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2660. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2661. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2662. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  2663. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2664. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2665. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2666. </td>
  2667. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2668. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2669. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2670. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2671. <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>
  2672. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2673. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2674. </td>
  2675. `;
  2676. tbody.appendChild(tr);
  2677. });
  2678. }
  2679. function formatTarget(addr, list, geo) {
  2680. const parts = [];
  2681. if (addr) parts.push(`<span>${addr}</span>`);
  2682. if (list) {
  2683. const inv = list.startsWith('!') ? '!' : '';
  2684. const clean = list.replace(/^!/, '');
  2685. 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>`);
  2686. }
  2687. if (geo) {
  2688. const inv = geo.startsWith('!') ? '!' : '';
  2689. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  2690. 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>`);
  2691. }
  2692. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  2693. return parts.join(' ');
  2694. }
  2695. function populateInterfaceSelect(selectId, currentVal = '') {
  2696. const sel = document.getElementById(selectId);
  2697. if (!sel) return;
  2698. sel.innerHTML = '<option value="">(Any Interface)</option>';
  2699. (state.interfaces || []).forEach(i => {
  2700. const opt = document.createElement('option');
  2701. opt.value = i.name;
  2702. opt.innerText = `${i.name} (${i.role || i.type})`;
  2703. if (i.name === currentVal) opt.selected = true;
  2704. sel.appendChild(opt);
  2705. });
  2706. }
  2707. function populateAddressListSelect(selectId, currentVal = '') {
  2708. const sel = document.getElementById(selectId);
  2709. if (!sel) return;
  2710. sel.innerHTML = '<option value="">(None)</option>';
  2711. const cleanVal = (currentVal || '').replace(/^!/, '');
  2712. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  2713. customNames.forEach(name => {
  2714. const count = (state.addressLists || []).filter(a => a.name === name).length;
  2715. const opt = document.createElement('option');
  2716. opt.value = name;
  2717. opt.innerText = `${name} (${count} entries)`;
  2718. if (name === cleanVal) opt.selected = true;
  2719. sel.appendChild(opt);
  2720. });
  2721. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  2722. const opt = document.createElement('option');
  2723. opt.value = cleanVal;
  2724. opt.innerText = cleanVal;
  2725. opt.selected = true;
  2726. sel.appendChild(opt);
  2727. }
  2728. populateCommonAddrListDatalist();
  2729. }
  2730. function populateCommonAddrListDatalist() {
  2731. const dl = document.getElementById('fw-addrlist-datalist');
  2732. if (!dl) return;
  2733. dl.innerHTML = '';
  2734. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  2735. names.forEach(name => {
  2736. const opt = document.createElement('option');
  2737. opt.value = name;
  2738. dl.appendChild(opt);
  2739. });
  2740. }
  2741. function populateGeoIPSelect(selectId, currentVal = '') {
  2742. const sel = document.getElementById(selectId);
  2743. if (!sel) return;
  2744. sel.innerHTML = '<option value="">(None)</option>';
  2745. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  2746. // Presets optgroup
  2747. const grpPresets = document.createElement('optgroup');
  2748. grpPresets.label = '⚡ Regional Presets';
  2749. const presets = [
  2750. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  2751. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  2752. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  2753. ];
  2754. presets.forEach(p => {
  2755. const opt = document.createElement('option');
  2756. opt.value = p.code;
  2757. opt.innerText = p.label;
  2758. if (p.code === cleanVal) opt.selected = true;
  2759. grpPresets.appendChild(opt);
  2760. });
  2761. sel.appendChild(grpPresets);
  2762. // All Countries optgroup
  2763. const grpCountries = document.createElement('optgroup');
  2764. grpCountries.label = '🌍 All Countries';
  2765. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  2766. countries.forEach(c => {
  2767. const opt = document.createElement('option');
  2768. opt.value = c.code;
  2769. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  2770. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  2771. if (c.code === cleanVal) opt.selected = true;
  2772. grpCountries.appendChild(opt);
  2773. });
  2774. sel.appendChild(grpCountries);
  2775. }
  2776. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  2777. function switchFwRuleTab(tab) {
  2778. state.activeFwRuleTab = tab;
  2779. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  2780. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  2781. btn.classList.add('text-slate-400', 'border-transparent');
  2782. });
  2783. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  2784. if (activeBtn) {
  2785. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  2786. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  2787. }
  2788. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  2789. const activePane = document.getElementById(`fw-pane-${tab}`);
  2790. if (activePane) activePane.classList.remove('hidden');
  2791. if (tab === 'statistics') {
  2792. startFwStatPolling();
  2793. } else {
  2794. stopFwStatPolling();
  2795. }
  2796. }
  2797. function toggleFwField(fieldKey, expand) {
  2798. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  2799. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  2800. if (!plusBtn || !fieldBox) return;
  2801. if (expand) {
  2802. plusBtn.classList.add('hidden');
  2803. fieldBox.classList.remove('hidden');
  2804. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2805. if (valInput) valInput.focus();
  2806. } else {
  2807. fieldBox.classList.add('hidden');
  2808. plusBtn.classList.remove('hidden');
  2809. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2810. if (valInput) {
  2811. if (valInput.tagName === 'SELECT') {
  2812. valInput.selectedIndex = 0;
  2813. } else {
  2814. valInput.value = '';
  2815. }
  2816. }
  2817. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  2818. if (invInput) invInput.checked = false;
  2819. if (fieldKey === 'cs') {
  2820. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  2821. const el = document.getElementById(id);
  2822. if (el) el.checked = false;
  2823. });
  2824. }
  2825. if (fieldKey === 'natstate') {
  2826. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  2827. const el = document.getElementById(id);
  2828. if (el) el.checked = false;
  2829. });
  2830. }
  2831. if (fieldKey === 'days') {
  2832. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  2833. const el = document.getElementById(`fw-day-${d}`);
  2834. if (el) el.checked = true;
  2835. });
  2836. }
  2837. }
  2838. }
  2839. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  2840. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  2841. toggleFwField(fieldKey, true);
  2842. let strVal = String(value);
  2843. if (hasInvert) {
  2844. const inv = strVal.startsWith('!');
  2845. if (inv) strVal = strVal.slice(1);
  2846. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  2847. if (invEl) invEl.checked = inv;
  2848. }
  2849. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  2850. if (valEl) valEl.value = strVal;
  2851. } else {
  2852. toggleFwField(fieldKey, false);
  2853. }
  2854. }
  2855. function getFwFieldVal(fieldKey, hasInvert = false) {
  2856. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  2857. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  2858. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  2859. let v = valEl ? valEl.value.trim() : '';
  2860. if (!v) return '';
  2861. if (hasInvert) {
  2862. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  2863. if (invEl && invEl.checked) {
  2864. v = '!' + v.replace(/^!/, '');
  2865. }
  2866. }
  2867. return v;
  2868. }
  2869. function toggleMaximizeFilterModal() {
  2870. const win = document.getElementById('filter-modal-window');
  2871. if (!win) return;
  2872. if (win.classList.contains('max-w-[720px]')) {
  2873. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  2874. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  2875. } else {
  2876. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  2877. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  2878. }
  2879. }
  2880. function openAddFilterModal() {
  2881. switchFwRuleTab('general');
  2882. const badge = document.getElementById('fw-modal-badge');
  2883. if (badge) badge.innerText = 'New...';
  2884. document.getElementById('filter-modal-id').value = '';
  2885. document.getElementById('filter-modal-enabled').checked = true;
  2886. document.getElementById('filter-modal-comment').value = '';
  2887. document.getElementById('filter-modal-chain').value = 'forward';
  2888. document.getElementById('filter-modal-action').value = 'accept';
  2889. document.getElementById('filter-modal-log').checked = false;
  2890. populateInterfaceSelect('fw-val-iniface');
  2891. populateInterfaceSelect('fw-val-outiface');
  2892. populateAddressListSelect('fw-val-srclist');
  2893. populateAddressListSelect('fw-val-dstlist');
  2894. populateGeoIPSelect('fw-val-srcgeo');
  2895. populateGeoIPSelect('fw-val-dstgeo');
  2896. const allFieldKeys = [
  2897. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  2898. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  2899. 'routingmark', 'conntype', 'cs', 'natstate',
  2900. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  2901. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  2902. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  2903. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  2904. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  2905. ];
  2906. allFieldKeys.forEach(k => toggleFwField(k, false));
  2907. resetCurrentRuleCounters();
  2908. toggleFilterActionFields();
  2909. document.getElementById('filter-modal').classList.remove('hidden');
  2910. }
  2911. function openEditFilterModal(id) {
  2912. const r = (state.filterRules || []).find(rule => rule.id === id);
  2913. if (!r) return;
  2914. switchFwRuleTab('general');
  2915. const badge = document.getElementById('fw-modal-badge');
  2916. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  2917. document.getElementById('filter-modal-id').value = r.id;
  2918. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  2919. document.getElementById('filter-modal-comment').value = r.comment || '';
  2920. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  2921. document.getElementById('filter-modal-action').value = r.action || 'accept';
  2922. document.getElementById('filter-modal-log').checked = !!r.log;
  2923. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  2924. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  2925. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  2926. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  2927. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  2928. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  2929. setFwFieldVal('src', r.src_address, true);
  2930. setFwFieldVal('dst', r.dst_address, true);
  2931. setFwFieldVal('srclist', r.src_address_list, true);
  2932. setFwFieldVal('dstlist', r.dst_address_list, true);
  2933. setFwFieldVal('srcgeo', r.src_geoip, true);
  2934. setFwFieldVal('dstgeo', r.dst_geoip, true);
  2935. if (r.protocol && r.protocol !== 'all') {
  2936. setFwFieldVal('proto', r.protocol, true);
  2937. } else {
  2938. toggleFwField('proto', false);
  2939. }
  2940. setFwFieldVal('sport', r.src_port, true);
  2941. setFwFieldVal('dport', r.dst_port, true);
  2942. setFwFieldVal('anyport', r.any_port, true);
  2943. setFwFieldVal('iniface', r.in_interface, true);
  2944. setFwFieldVal('outiface', r.out_interface, true);
  2945. setFwFieldVal('inifacelist', r.in_interface_list, true);
  2946. setFwFieldVal('outifacelist', r.out_interface_list, true);
  2947. setFwFieldVal('pktmark', r.packet_mark, true);
  2948. setFwFieldVal('connmark', r.connection_mark, true);
  2949. setFwFieldVal('routingmark', r.routing_mark, true);
  2950. setFwFieldVal('conntype', r.connection_type, false);
  2951. const states = r.connection_state || [];
  2952. if (states.length > 0) {
  2953. toggleFwField('cs', true);
  2954. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  2955. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  2956. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  2957. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  2958. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  2959. } else {
  2960. toggleFwField('cs', false);
  2961. }
  2962. const natStates = r.connection_nat_state || [];
  2963. if (natStates.length > 0) {
  2964. toggleFwField('natstate', true);
  2965. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  2966. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  2967. } else {
  2968. toggleFwField('natstate', false);
  2969. }
  2970. // Advanced tab fields
  2971. setFwFieldVal('layer7', r.layer7_protocol, false);
  2972. setFwFieldVal('content', r.content, false);
  2973. setFwFieldVal('connbytes', r.connection_bytes, false);
  2974. setFwFieldVal('connrate', r.connection_rate, false);
  2975. setFwFieldVal('pcc', r.pcc, false);
  2976. setFwFieldVal('srcmac', r.src_mac_address, true);
  2977. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  2978. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  2979. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  2980. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  2981. setFwFieldVal('ipsec', r.ipsec_policy, false);
  2982. setFwFieldVal('tlshost', r.tls_host, false);
  2983. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  2984. setFwFieldVal('priority', r.priority, false);
  2985. setFwFieldVal('dscp', r.dscp, false);
  2986. setFwFieldVal('tcpmss', r.tcp_mss, false);
  2987. if (r.tos) {
  2988. const tosEl = document.getElementById('fw-val-tos');
  2989. if (tosEl) tosEl.value = r.tos;
  2990. }
  2991. setFwFieldVal('pktsize', r.packet_size, false);
  2992. setFwFieldVal('random', r.random, false);
  2993. setFwFieldVal('tcpflags', r.tcp_flags, false);
  2994. setFwFieldVal('icmpoptions', r.icmp_options, false);
  2995. setFwFieldVal('ipv4options', r.ipv4_options, false);
  2996. setFwFieldVal('ttl', r.ttl, false);
  2997. // Extra tab fields
  2998. setFwFieldVal('time', r.time, false);
  2999. if (r.days) {
  3000. toggleFwField('days', true);
  3001. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3002. const chk = document.getElementById(`fw-day-${d}`);
  3003. if (chk) chk.checked = r.days.includes(d);
  3004. });
  3005. } else {
  3006. toggleFwField('days', false);
  3007. }
  3008. setFwFieldVal('limit', r.limit, false);
  3009. setFwFieldVal('dstlimit', r.dst_limit, false);
  3010. setFwFieldVal('psd', r.psd, false);
  3011. // Action fields
  3012. if (r.reject_with) {
  3013. const rwEl = document.getElementById('filter-modal-rejectwith');
  3014. if (rwEl) rwEl.value = r.reject_with;
  3015. }
  3016. if (r.jump_target) {
  3017. const jtEl = document.getElementById('filter-modal-jumptarget');
  3018. if (jtEl) jtEl.value = r.jump_target;
  3019. }
  3020. if (r.address_list) {
  3021. const alEl = document.getElementById('filter-modal-action-addrlist');
  3022. if (alEl) alEl.value = r.address_list;
  3023. }
  3024. if (r.address_list_timeout) {
  3025. const toEl = document.getElementById('filter-modal-action-timeout');
  3026. if (toEl) toEl.value = r.address_list_timeout;
  3027. }
  3028. setFwFieldVal('logprefix', r.log_prefix, false);
  3029. // Statistics
  3030. const bEl = document.getElementById('fw-stat-bytes');
  3031. const pEl = document.getElementById('fw-stat-packets');
  3032. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3033. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3034. state.fwLastBytes = r.bytes || 0;
  3035. state.fwLastPackets = r.packets || 0;
  3036. state.fwLastTimestamp = Date.now();
  3037. state.fwStatRateHistory = new Array(30).fill(0);
  3038. state.fwStatPktHistory = new Array(30).fill(0);
  3039. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3040. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3041. toggleFilterActionFields();
  3042. document.getElementById('filter-modal').classList.remove('hidden');
  3043. }
  3044. function closeFilterModal() {
  3045. stopFwStatPolling();
  3046. document.getElementById('filter-modal').classList.add('hidden');
  3047. }
  3048. function toggleFilterActionFields() {
  3049. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  3050. const rejectBox = document.getElementById('filter-action-reject-box');
  3051. const jumpBox = document.getElementById('filter-action-jump-box');
  3052. const addrBox = document.getElementById('filter-action-addrlist-box');
  3053. if (rejectBox) {
  3054. if (act === 'reject') rejectBox.classList.remove('hidden');
  3055. else rejectBox.classList.add('hidden');
  3056. }
  3057. if (jumpBox) {
  3058. if (act === 'jump') jumpBox.classList.remove('hidden');
  3059. else jumpBox.classList.add('hidden');
  3060. }
  3061. if (addrBox) {
  3062. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  3063. addrBox.classList.remove('hidden');
  3064. } else {
  3065. addrBox.classList.add('hidden');
  3066. }
  3067. }
  3068. if (act === 'log') {
  3069. const logEl = document.getElementById('filter-modal-log');
  3070. if (logEl) logEl.checked = true;
  3071. toggleFwField('logprefix', true);
  3072. }
  3073. }
  3074. function toggleFwLogPrefix() {
  3075. const isLog = document.getElementById('filter-modal-log')?.checked;
  3076. toggleFwField('logprefix', !!isLog);
  3077. }
  3078. function copyFilterRule() {
  3079. document.getElementById('filter-modal-id').value = '';
  3080. const badge = document.getElementById('fw-modal-badge');
  3081. if (badge) badge.innerText = 'New...';
  3082. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  3083. }
  3084. function resetCurrentRuleCounters() {
  3085. state.fwStatRateHistory = new Array(30).fill(0);
  3086. state.fwStatPktHistory = new Array(30).fill(0);
  3087. state.fwLastBytes = 0;
  3088. state.fwLastPackets = 0;
  3089. state.fwLastTimestamp = Date.now();
  3090. const bEl = document.getElementById('fw-stat-bytes');
  3091. const pEl = document.getElementById('fw-stat-packets');
  3092. const rEl = document.getElementById('fw-stat-rate');
  3093. const prEl = document.getElementById('fw-stat-pktrate');
  3094. if (bEl) bEl.value = '0 B';
  3095. if (pEl) pEl.value = '0';
  3096. if (rEl) rEl.value = '0 bps';
  3097. if (prEl) prEl.value = '0 p/s';
  3098. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3099. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3100. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  3101. }
  3102. async function resetAllFwCounters() {
  3103. try {
  3104. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3105. if (res.ok) {
  3106. resetCurrentRuleCounters();
  3107. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  3108. loadFirewall(false);
  3109. }
  3110. } catch (err) {
  3111. showToast('Error', err.message, 'error');
  3112. }
  3113. }
  3114. async function applyFilterRule(closeAfter = false) {
  3115. const id = document.getElementById('filter-modal-id').value;
  3116. const chain = document.getElementById('filter-modal-chain').value;
  3117. const action = document.getElementById('filter-modal-action').value;
  3118. const comment = document.getElementById('filter-modal-comment').value.trim();
  3119. const enabled = document.getElementById('filter-modal-enabled').checked;
  3120. const src = getFwFieldVal('src', true);
  3121. const dst = getFwFieldVal('dst', true);
  3122. const srclist = getFwFieldVal('srclist', true);
  3123. const dstlist = getFwFieldVal('dstlist', true);
  3124. const srcgeo = getFwFieldVal('srcgeo', true);
  3125. const dstgeo = getFwFieldVal('dstgeo', true);
  3126. const proto = getFwFieldVal('proto', true);
  3127. const sport = getFwFieldVal('sport', true);
  3128. const dport = getFwFieldVal('dport', true);
  3129. const anyport = getFwFieldVal('anyport', true);
  3130. const iniface = getFwFieldVal('iniface', true);
  3131. const outiface = getFwFieldVal('outiface', true);
  3132. const inifacelist = getFwFieldVal('inifacelist', true);
  3133. const outifacelist = getFwFieldVal('outifacelist', true);
  3134. const pktmark = getFwFieldVal('pktmark', true);
  3135. const connmark = getFwFieldVal('connmark', true);
  3136. const routingmark = getFwFieldVal('routingmark', true);
  3137. const conntype = getFwFieldVal('conntype', false);
  3138. const states = [];
  3139. const csBox = document.getElementById('fw-field-cs');
  3140. if (csBox && !csBox.classList.contains('hidden')) {
  3141. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  3142. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  3143. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  3144. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  3145. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  3146. }
  3147. const natStates = [];
  3148. const natBox = document.getElementById('fw-field-natstate');
  3149. if (natBox && !natBox.classList.contains('hidden')) {
  3150. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  3151. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  3152. }
  3153. const payload = {
  3154. id,
  3155. chain,
  3156. action,
  3157. protocol: proto || 'all',
  3158. src_address: src,
  3159. dst_address: dst,
  3160. src_port: sport,
  3161. dst_port: dport,
  3162. any_port: anyport,
  3163. in_interface: iniface,
  3164. out_interface: outiface,
  3165. in_interface_list: inifacelist,
  3166. out_interface_list: outifacelist,
  3167. packet_mark: pktmark,
  3168. connection_mark: connmark,
  3169. routing_mark: routingmark,
  3170. connection_type: conntype,
  3171. connection_state: states,
  3172. connection_nat_state: natStates,
  3173. src_address_list: srclist,
  3174. dst_address_list: dstlist,
  3175. src_geoip: srcgeo,
  3176. dst_geoip: dstgeo,
  3177. comment,
  3178. disabled: !enabled,
  3179. // Advanced tab
  3180. layer7_protocol: getFwFieldVal('layer7', false),
  3181. content: getFwFieldVal('content', false),
  3182. connection_bytes: getFwFieldVal('connbytes', false),
  3183. connection_rate: getFwFieldVal('connrate', false),
  3184. pcc: getFwFieldVal('pcc', false),
  3185. src_mac_address: getFwFieldVal('srcmac', true),
  3186. out_bridge_port: getFwFieldVal('outbridgeport', false),
  3187. in_bridge_port: getFwFieldVal('inbridgeport', false),
  3188. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  3189. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  3190. ipsec_policy: getFwFieldVal('ipsec', false),
  3191. tls_host: getFwFieldVal('tlshost', false),
  3192. ingress_priority: getFwFieldVal('ingresspriority', false),
  3193. priority: getFwFieldVal('priority', false),
  3194. dscp: getFwFieldVal('dscp', false),
  3195. tcp_mss: getFwFieldVal('tcpmss', false),
  3196. tos: document.getElementById('fw-val-tos')?.value || '',
  3197. packet_size: getFwFieldVal('pktsize', false),
  3198. random: getFwFieldVal('random', false),
  3199. tcp_flags: getFwFieldVal('tcpflags', false),
  3200. icmp_options: getFwFieldVal('icmpoptions', false),
  3201. ipv4_options: getFwFieldVal('ipv4options', false),
  3202. ttl: getFwFieldVal('ttl', false),
  3203. // Extra tab
  3204. time: getFwFieldVal('time', false),
  3205. limit: getFwFieldVal('limit', false),
  3206. dst_limit: getFwFieldVal('dstlimit', false),
  3207. psd: getFwFieldVal('psd', false),
  3208. // Action tab
  3209. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  3210. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  3211. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  3212. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  3213. log: document.getElementById('filter-modal-log')?.checked || false,
  3214. log_prefix: getFwFieldVal('logprefix', false)
  3215. };
  3216. try {
  3217. const res = await fetch(`${API_BASE}/firewall/filter`, {
  3218. method: 'POST',
  3219. headers: { 'Content-Type': 'application/json' },
  3220. body: JSON.stringify(payload)
  3221. });
  3222. if (res.ok) {
  3223. const data = await res.json();
  3224. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  3225. loadFirewall(false);
  3226. if (closeAfter) {
  3227. closeFilterModal();
  3228. } else {
  3229. if (data.id) {
  3230. document.getElementById('filter-modal-id').value = data.id;
  3231. const badge = document.getElementById('fw-modal-badge');
  3232. if (badge) badge.innerText = `#${data.id}`;
  3233. }
  3234. }
  3235. } else {
  3236. const err = await res.json();
  3237. showToast('Error', err.message || 'Failed to save rule', 'error');
  3238. }
  3239. } catch (err) {
  3240. showToast('Error', err.message, 'error');
  3241. }
  3242. }
  3243. function submitSaveFilterRule(e) {
  3244. if (e && e.preventDefault) e.preventDefault();
  3245. return applyFilterRule(true);
  3246. }
  3247. function startFwStatPolling() {
  3248. stopFwStatPolling();
  3249. pollRuleStats();
  3250. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  3251. }
  3252. function stopFwStatPolling() {
  3253. if (state.fwStatInterval) {
  3254. clearInterval(state.fwStatInterval);
  3255. state.fwStatInterval = null;
  3256. }
  3257. }
  3258. async function pollRuleStats() {
  3259. const id = document.getElementById('filter-modal-id')?.value;
  3260. if (!id) {
  3261. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  3262. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  3263. return;
  3264. }
  3265. try {
  3266. const res = await fetch(`${API_BASE}/firewall/filter`);
  3267. if (!res.ok) return;
  3268. const rules = await res.json();
  3269. const r = rules.find(x => x.id === id);
  3270. if (!r) return;
  3271. const now = Date.now();
  3272. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  3273. state.fwLastTimestamp = now;
  3274. const curBytes = r.bytes || 0;
  3275. const curPackets = r.packets || 0;
  3276. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  3277. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  3278. state.fwLastBytes = curBytes;
  3279. state.fwLastPackets = curPackets;
  3280. const rateBps = Math.round((deltaBytes * 8) / dt);
  3281. const ratePkt = Math.round(deltaPkts / dt);
  3282. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  3283. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  3284. state.fwStatRateHistory.push(rateBps);
  3285. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  3286. state.fwStatPktHistory.push(ratePkt);
  3287. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  3288. const bEl = document.getElementById('fw-stat-bytes');
  3289. const pEl = document.getElementById('fw-stat-packets');
  3290. const rEl = document.getElementById('fw-stat-rate');
  3291. const prEl = document.getElementById('fw-stat-pktrate');
  3292. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  3293. if (pEl) pEl.value = curPackets.toLocaleString();
  3294. if (rEl) rEl.value = formatBps(rateBps);
  3295. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  3296. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3297. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3298. } catch (e) {
  3299. console.error('Error polling rule stats', e);
  3300. }
  3301. }
  3302. function formatBps(bps) {
  3303. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  3304. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  3305. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  3306. return bps + ' bps';
  3307. }
  3308. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  3309. const svg = document.getElementById(svgId);
  3310. if (!svg) return;
  3311. const w = 500;
  3312. const h = 100;
  3313. const paddingRight = 45;
  3314. const graphWidth = w - paddingRight;
  3315. const maxVal = Math.max(5, ...dataArray);
  3316. const currentVal = dataArray[dataArray.length - 1] || 0;
  3317. const leg = document.getElementById(legendId);
  3318. if (leg) {
  3319. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  3320. }
  3321. let gridLines = '';
  3322. for (let i = 0; i <= 5; i++) {
  3323. const y = 8 + (i * (h - 18) / 5);
  3324. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  3325. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  3326. gridLines += `
  3327. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  3328. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  3329. `;
  3330. }
  3331. const step = graphWidth / (dataArray.length - 1);
  3332. const points = dataArray.map((val, idx) => {
  3333. const x = idx * step;
  3334. const y = (h - 10) - (val / maxVal) * (h - 20);
  3335. return `${x.toFixed(1)},${y.toFixed(1)}`;
  3336. });
  3337. const polylineStr = points.join(' ');
  3338. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  3339. svg.innerHTML = `
  3340. ${gridLines}
  3341. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  3342. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  3343. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  3344. `;
  3345. }
  3346. async function moveFilterRule(id, dir) {
  3347. try {
  3348. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  3349. method: 'POST',
  3350. headers: { 'Content-Type': 'application/json' },
  3351. body: JSON.stringify({ direction: dir })
  3352. });
  3353. if (res.ok) loadFirewall(false);
  3354. } catch (err) {
  3355. showToast('Error', err.message, 'error');
  3356. }
  3357. }
  3358. async function toggleFilterRuleState(id, disabled) {
  3359. try {
  3360. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  3361. method: 'POST',
  3362. headers: { 'Content-Type': 'application/json' },
  3363. body: JSON.stringify({ disabled })
  3364. });
  3365. if (res.ok) loadFirewall(false);
  3366. } catch (err) {
  3367. showToast('Error', err.message, 'error');
  3368. }
  3369. }
  3370. async function deleteFilterRule(id) {
  3371. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  3372. try {
  3373. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3374. if (res.ok) {
  3375. showToast('Deleted', 'Filter rule removed', 'success');
  3376. loadFirewall(false);
  3377. }
  3378. } catch (err) {
  3379. showToast('Error', err.message, 'error');
  3380. }
  3381. }
  3382. // ----------------- NAT Rules -----------------
  3383. function renderNATRules() {
  3384. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  3385. const tbody = document.getElementById('nat-table-body');
  3386. const empty = document.getElementById('nat-empty');
  3387. if (!tbody) return;
  3388. tbody.innerHTML = '';
  3389. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3390. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  3391. if (rules.length === 0) {
  3392. empty?.classList.remove('hidden');
  3393. return;
  3394. }
  3395. empty?.classList.add('hidden');
  3396. rules.forEach((r, idx) => {
  3397. const tr = document.createElement('tr');
  3398. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3399. let toTarget = '-';
  3400. if (r.action === 'jump') {
  3401. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  3402. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3403. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  3404. } else if (r.action === 'redirect') {
  3405. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  3406. } else if (r.action === 'masquerade') {
  3407. 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>`;
  3408. } else if (r.action === 'log') {
  3409. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  3410. } else {
  3411. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  3412. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  3413. }
  3414. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  3415. tr.innerHTML = `
  3416. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3417. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3418. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  3419. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3420. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3421. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  3422. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3423. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  3424. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  3425. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3426. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3427. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3428. </td>
  3429. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3430. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3431. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3432. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3433. <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>
  3434. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3435. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3436. </td>
  3437. `;
  3438. tbody.appendChild(tr);
  3439. });
  3440. }
  3441. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3442. function switchNATRuleTab(tab) {
  3443. state.activeNATRuleTab = tab;
  3444. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  3445. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3446. btn.classList.add('text-slate-400', 'border-transparent');
  3447. });
  3448. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  3449. if (activeBtn) {
  3450. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3451. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3452. }
  3453. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  3454. const activePane = document.getElementById(`nat-pane-${tab}`);
  3455. if (activePane) activePane.classList.remove('hidden');
  3456. if (tab === 'statistics') {
  3457. startNATStatPolling();
  3458. } else {
  3459. stopNATStatPolling();
  3460. }
  3461. }
  3462. function toggleNATField(fieldKey, expand) {
  3463. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  3464. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3465. if (!plusBtn || !fieldBox) return;
  3466. if (expand) {
  3467. plusBtn.classList.add('hidden');
  3468. fieldBox.classList.remove('hidden');
  3469. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3470. if (valInput) valInput.focus();
  3471. } else {
  3472. fieldBox.classList.add('hidden');
  3473. plusBtn.classList.remove('hidden');
  3474. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3475. if (valInput) {
  3476. if (valInput.tagName === 'SELECT') {
  3477. valInput.selectedIndex = 0;
  3478. } else {
  3479. valInput.value = '';
  3480. }
  3481. }
  3482. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  3483. if (invInput) invInput.checked = false;
  3484. if (fieldKey === 'days') {
  3485. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3486. const el = document.getElementById(`nat-day-${d}`);
  3487. if (el) el.checked = true;
  3488. });
  3489. }
  3490. }
  3491. }
  3492. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  3493. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3494. toggleNATField(fieldKey, true);
  3495. let strVal = String(value);
  3496. if (hasInvert) {
  3497. const inv = strVal.startsWith('!');
  3498. if (inv) strVal = strVal.slice(1);
  3499. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3500. if (invEl) invEl.checked = inv;
  3501. }
  3502. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3503. if (valEl) valEl.value = strVal;
  3504. } else {
  3505. toggleNATField(fieldKey, false);
  3506. }
  3507. }
  3508. function getNATFieldVal(fieldKey, hasInvert = false) {
  3509. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3510. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3511. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3512. let v = valEl ? valEl.value.trim() : '';
  3513. if (!v) return '';
  3514. if (hasInvert) {
  3515. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3516. if (invEl && invEl.checked) {
  3517. v = '!' + v.replace(/^!/, '');
  3518. }
  3519. }
  3520. return v;
  3521. }
  3522. function toggleMaximizeNATModal() {
  3523. const win = document.getElementById('nat-modal-window');
  3524. if (!win) return;
  3525. if (win.classList.contains('max-w-[720px]')) {
  3526. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3527. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3528. } else {
  3529. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3530. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3531. }
  3532. }
  3533. function handleNATChainChange() {
  3534. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  3535. const actSel = document.getElementById('nat-modal-action');
  3536. if (actSel) {
  3537. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  3538. actSel.value = 'masquerade';
  3539. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  3540. actSel.value = 'dst-nat';
  3541. }
  3542. }
  3543. toggleNATActionFields();
  3544. }
  3545. function toggleNATActionFields() {
  3546. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  3547. const rowAddr = document.getElementById('nat-row-toaddr');
  3548. const rowPort = document.getElementById('nat-row-toport');
  3549. const jumpBox = document.getElementById('nat-action-jump-box');
  3550. const addrBox = document.getElementById('nat-action-addrlist-box');
  3551. // Hide all dynamic rows first
  3552. if (rowAddr) rowAddr.classList.add('hidden');
  3553. if (rowPort) rowPort.classList.add('hidden');
  3554. if (jumpBox) jumpBox.classList.add('hidden');
  3555. if (addrBox) addrBox.classList.add('hidden');
  3556. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  3557. if (rowAddr) rowAddr.classList.remove('hidden');
  3558. if (rowPort) rowPort.classList.remove('hidden');
  3559. } else if (act === 'redirect' || act === 'masquerade') {
  3560. if (rowPort) rowPort.classList.remove('hidden');
  3561. } else if (act === 'jump') {
  3562. if (jumpBox) jumpBox.classList.remove('hidden');
  3563. } else if (act.includes('address-list') || act.includes('address list')) {
  3564. if (addrBox) addrBox.classList.remove('hidden');
  3565. }
  3566. if (act === 'log') {
  3567. const logEl = document.getElementById('nat-modal-log');
  3568. if (logEl) logEl.checked = true;
  3569. toggleNATField('logprefix', true);
  3570. }
  3571. }
  3572. function toggleNATLogPrefix() {
  3573. const isLog = document.getElementById('nat-modal-log')?.checked;
  3574. toggleNATField('logprefix', !!isLog);
  3575. }
  3576. function openAddNATModal() {
  3577. switchNATRuleTab('general');
  3578. const badge = document.getElementById('nat-modal-badge');
  3579. if (badge) badge.innerText = 'New...';
  3580. document.getElementById('nat-modal-id').value = '';
  3581. document.getElementById('nat-modal-enabled').checked = true;
  3582. document.getElementById('nat-modal-comment').value = '';
  3583. document.getElementById('nat-modal-chain').value = 'srcnat';
  3584. document.getElementById('nat-modal-action').value = 'masquerade';
  3585. document.getElementById('nat-modal-toaddr').value = '';
  3586. document.getElementById('nat-modal-toport').value = '';
  3587. document.getElementById('nat-modal-log').checked = false;
  3588. populateInterfaceSelect('nat-val-iniface');
  3589. populateInterfaceSelect('nat-val-outiface');
  3590. populateAddressListSelect('nat-val-srclist');
  3591. populateAddressListSelect('nat-val-dstlist');
  3592. populateGeoIPSelect('nat-val-srcgeo');
  3593. populateGeoIPSelect('nat-val-dstgeo');
  3594. const allFieldKeys = [
  3595. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3596. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3597. 'routingmark', 'conntype',
  3598. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3599. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3600. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3601. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  3602. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3603. ];
  3604. allFieldKeys.forEach(k => toggleNATField(k, false));
  3605. resetCurrentNATRuleCounters();
  3606. toggleNATActionFields();
  3607. document.getElementById('nat-modal').classList.remove('hidden');
  3608. }
  3609. function openEditNATModal(id) {
  3610. const r = (state.natRules || []).find(rule => rule.id === id);
  3611. if (!r) return;
  3612. switchNATRuleTab('general');
  3613. const badge = document.getElementById('nat-modal-badge');
  3614. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3615. document.getElementById('nat-modal-id').value = r.id;
  3616. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  3617. document.getElementById('nat-modal-comment').value = r.comment || '';
  3618. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  3619. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  3620. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  3621. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  3622. document.getElementById('nat-modal-log').checked = !!r.log;
  3623. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3624. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3625. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3626. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3627. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  3628. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  3629. setNATFieldVal('src', r.src_address, true);
  3630. setNATFieldVal('dst', r.dst_address, true);
  3631. setNATFieldVal('srclist', r.src_address_list, true);
  3632. setNATFieldVal('dstlist', r.dst_address_list, true);
  3633. setNATFieldVal('srcgeo', r.src_geoip, true);
  3634. setNATFieldVal('dstgeo', r.dst_geoip, true);
  3635. if (r.protocol && r.protocol !== 'all') {
  3636. setNATFieldVal('proto', r.protocol, true);
  3637. } else {
  3638. toggleNATField('proto', false);
  3639. }
  3640. setNATFieldVal('sport', r.src_port, true);
  3641. setNATFieldVal('dport', r.dst_port, true);
  3642. setNATFieldVal('anyport', r.any_port, true);
  3643. setNATFieldVal('iniface', r.in_interface, true);
  3644. setNATFieldVal('outiface', r.out_interface, true);
  3645. setNATFieldVal('inifacelist', r.in_interface_list, true);
  3646. setNATFieldVal('outifacelist', r.out_interface_list, true);
  3647. setNATFieldVal('pktmark', r.packet_mark, true);
  3648. setNATFieldVal('connmark', r.connection_mark, true);
  3649. setNATFieldVal('routingmark', r.routing_mark, true);
  3650. setNATFieldVal('conntype', r.connection_type, false);
  3651. // Advanced tab fields
  3652. setNATFieldVal('layer7', r.layer7_protocol, false);
  3653. setNATFieldVal('content', r.content, false);
  3654. setNATFieldVal('connbytes', r.connection_bytes, false);
  3655. setNATFieldVal('connrate', r.connection_rate, false);
  3656. setNATFieldVal('pcc', r.pcc, false);
  3657. setNATFieldVal('srcmac', r.src_mac_address, true);
  3658. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  3659. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  3660. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3661. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3662. setNATFieldVal('ipsec', r.ipsec_policy, false);
  3663. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  3664. setNATFieldVal('priority', r.priority, false);
  3665. setNATFieldVal('dscp', r.dscp, false);
  3666. setNATFieldVal('tcpmss', r.tcp_mss, false);
  3667. if (r.tos) {
  3668. const tosEl = document.getElementById('nat-val-tos');
  3669. if (tosEl) tosEl.value = r.tos;
  3670. }
  3671. setNATFieldVal('pktsize', r.packet_size, false);
  3672. setNATFieldVal('random', r.random, false);
  3673. setNATFieldVal('icmpoptions', r.icmp_options, false);
  3674. setNATFieldVal('ipv4options', r.ipv4_options, false);
  3675. setNATFieldVal('ttl', r.ttl, false);
  3676. // Extra tab fields
  3677. setNATFieldVal('time', r.time, false);
  3678. if (r.days) {
  3679. toggleNATField('days', true);
  3680. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3681. const chk = document.getElementById(`nat-day-${d}`);
  3682. if (chk) chk.checked = r.days.includes(d);
  3683. });
  3684. } else {
  3685. toggleNATField('days', false);
  3686. }
  3687. setNATFieldVal('limit', r.limit, false);
  3688. setNATFieldVal('dstlimit', r.dst_limit, false);
  3689. setNATFieldVal('psd', r.psd, false);
  3690. // Action fields
  3691. if (r.jump_target) {
  3692. const jtEl = document.getElementById('nat-modal-jumptarget');
  3693. if (jtEl) jtEl.value = r.jump_target;
  3694. }
  3695. if (r.address_list) {
  3696. const alEl = document.getElementById('nat-modal-action-addrlist');
  3697. if (alEl) alEl.value = r.address_list;
  3698. }
  3699. if (r.address_list_timeout) {
  3700. const toEl = document.getElementById('nat-modal-action-timeout');
  3701. if (toEl) toEl.value = r.address_list_timeout;
  3702. }
  3703. setNATFieldVal('logprefix', r.log_prefix, false);
  3704. // Statistics
  3705. const bEl = document.getElementById('nat-stat-bytes');
  3706. const pEl = document.getElementById('nat-stat-packets');
  3707. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3708. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3709. state.natLastBytes = r.bytes || 0;
  3710. state.natLastPackets = r.packets || 0;
  3711. state.natLastTimestamp = Date.now();
  3712. state.natStatRateHistory = new Array(30).fill(0);
  3713. state.natStatPktHistory = new Array(30).fill(0);
  3714. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3715. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3716. toggleNATActionFields();
  3717. document.getElementById('nat-modal').classList.remove('hidden');
  3718. }
  3719. function closeNATModal() {
  3720. stopNATStatPolling();
  3721. document.getElementById('nat-modal').classList.add('hidden');
  3722. }
  3723. function copyNATRule() {
  3724. document.getElementById('nat-modal-id').value = '';
  3725. const badge = document.getElementById('nat-modal-badge');
  3726. if (badge) badge.innerText = 'New...';
  3727. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  3728. }
  3729. function resetCurrentNATRuleCounters() {
  3730. state.natStatRateHistory = new Array(30).fill(0);
  3731. state.natStatPktHistory = new Array(30).fill(0);
  3732. state.natLastBytes = 0;
  3733. state.natLastPackets = 0;
  3734. state.natLastTimestamp = Date.now();
  3735. const bEl = document.getElementById('nat-stat-bytes');
  3736. const pEl = document.getElementById('nat-stat-packets');
  3737. const rEl = document.getElementById('nat-stat-rate');
  3738. const prEl = document.getElementById('nat-stat-pktrate');
  3739. if (bEl) bEl.value = '0 B';
  3740. if (pEl) pEl.value = '0';
  3741. if (rEl) rEl.value = '0 bps';
  3742. if (prEl) prEl.value = '0 p/s';
  3743. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3744. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3745. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  3746. }
  3747. async function applyNATRule(closeAfter = false) {
  3748. const id = document.getElementById('nat-modal-id').value;
  3749. const chain = document.getElementById('nat-modal-chain').value;
  3750. const action = document.getElementById('nat-modal-action').value;
  3751. const comment = document.getElementById('nat-modal-comment').value.trim();
  3752. const enabled = document.getElementById('nat-modal-enabled').checked;
  3753. const src = getNATFieldVal('src', true);
  3754. const dst = getNATFieldVal('dst', true);
  3755. const srclist = getNATFieldVal('srclist', true);
  3756. const dstlist = getNATFieldVal('dstlist', true);
  3757. const srcgeo = getNATFieldVal('srcgeo', true);
  3758. const dstgeo = getNATFieldVal('dstgeo', true);
  3759. const proto = getNATFieldVal('proto', true);
  3760. const sport = getNATFieldVal('sport', true);
  3761. const dport = getNATFieldVal('dport', true);
  3762. const anyport = getNATFieldVal('anyport', true);
  3763. const iniface = getNATFieldVal('iniface', true);
  3764. const outiface = getNATFieldVal('outiface', true);
  3765. const inifacelist = getNATFieldVal('inifacelist', true);
  3766. const outifacelist = getNATFieldVal('outifacelist', true);
  3767. const pktmark = getNATFieldVal('pktmark', true);
  3768. const connmark = getNATFieldVal('connmark', true);
  3769. const routingmark = getNATFieldVal('routingmark', true);
  3770. const conntype = getNATFieldVal('conntype', false);
  3771. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  3772. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  3773. const payload = {
  3774. id,
  3775. chain,
  3776. action,
  3777. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  3778. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  3779. protocol: proto || 'all',
  3780. src_address: src,
  3781. dst_address: dst,
  3782. src_port: sport,
  3783. dst_port: dport,
  3784. any_port: anyport,
  3785. in_interface: iniface,
  3786. out_interface: outiface,
  3787. in_interface_list: inifacelist,
  3788. out_interface_list: outifacelist,
  3789. packet_mark: pktmark,
  3790. connection_mark: connmark,
  3791. routing_mark: routingmark,
  3792. connection_type: conntype,
  3793. src_address_list: srclist,
  3794. dst_address_list: dstlist,
  3795. src_geoip: srcgeo,
  3796. dst_geoip: dstgeo,
  3797. comment,
  3798. disabled: !enabled,
  3799. // Advanced tab
  3800. layer7_protocol: getNATFieldVal('layer7', false),
  3801. content: getNATFieldVal('content', false),
  3802. connection_bytes: getNATFieldVal('connbytes', false),
  3803. connection_rate: getNATFieldVal('connrate', false),
  3804. pcc: getNATFieldVal('pcc', false),
  3805. src_mac_address: getNATFieldVal('srcmac', true),
  3806. out_bridge_port: getNATFieldVal('outbridgeport', false),
  3807. in_bridge_port: getNATFieldVal('inbridgeport', false),
  3808. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  3809. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  3810. ipsec_policy: getNATFieldVal('ipsec', false),
  3811. ingress_priority: getNATFieldVal('ingresspriority', false),
  3812. priority: getNATFieldVal('priority', false),
  3813. dscp: getNATFieldVal('dscp', false),
  3814. tcp_mss: getNATFieldVal('tcpmss', false),
  3815. tos: document.getElementById('nat-val-tos')?.value || '',
  3816. packet_size: getNATFieldVal('pktsize', false),
  3817. random: getNATFieldVal('random', false),
  3818. icmp_options: getNATFieldVal('icmpoptions', false),
  3819. ipv4_options: getNATFieldVal('ipv4options', false),
  3820. ttl: getNATFieldVal('ttl', false),
  3821. // Extra tab
  3822. time: getNATFieldVal('time', false),
  3823. limit: getNATFieldVal('limit', false),
  3824. dst_limit: getNATFieldVal('dstlimit', false),
  3825. psd: getNATFieldVal('psd', false),
  3826. // Action tab
  3827. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  3828. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  3829. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  3830. log: document.getElementById('nat-modal-log')?.checked || false,
  3831. log_prefix: getNATFieldVal('logprefix', false)
  3832. };
  3833. try {
  3834. const res = await fetch(`${API_BASE}/firewall/nat`, {
  3835. method: 'POST',
  3836. headers: { 'Content-Type': 'application/json' },
  3837. body: JSON.stringify(payload)
  3838. });
  3839. if (res.ok) {
  3840. const data = await res.json();
  3841. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  3842. loadFirewall(false);
  3843. if (closeAfter) {
  3844. closeNATModal();
  3845. } else {
  3846. if (data.id) {
  3847. document.getElementById('nat-modal-id').value = data.id;
  3848. const badge = document.getElementById('nat-modal-badge');
  3849. if (badge) badge.innerText = `#${data.id}`;
  3850. }
  3851. }
  3852. } else {
  3853. const err = await res.json();
  3854. showToast('Error', err.message || 'Failed to save rule', 'error');
  3855. }
  3856. } catch (err) {
  3857. showToast('Error', err.message, 'error');
  3858. }
  3859. }
  3860. function submitSaveNATRule(e) {
  3861. if (e && e.preventDefault) e.preventDefault();
  3862. return applyNATRule(true);
  3863. }
  3864. function startNATStatPolling() {
  3865. stopNATStatPolling();
  3866. pollNATRuleStats();
  3867. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  3868. }
  3869. function stopNATStatPolling() {
  3870. if (state.natStatInterval) {
  3871. clearInterval(state.natStatInterval);
  3872. state.natStatInterval = null;
  3873. }
  3874. }
  3875. async function pollNATRuleStats() {
  3876. const id = document.getElementById('nat-modal-id')?.value;
  3877. if (!id) {
  3878. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  3879. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  3880. return;
  3881. }
  3882. try {
  3883. const res = await fetch(`${API_BASE}/firewall/nat`);
  3884. if (!res.ok) return;
  3885. const rules = await res.json();
  3886. const r = rules.find(x => x.id === id);
  3887. if (!r) return;
  3888. const now = Date.now();
  3889. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  3890. state.natLastTimestamp = now;
  3891. const curBytes = r.bytes || 0;
  3892. const curPackets = r.packets || 0;
  3893. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  3894. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  3895. state.natLastBytes = curBytes;
  3896. state.natLastPackets = curPackets;
  3897. const rateBps = Math.round((deltaBytes * 8) / dt);
  3898. const ratePkt = Math.round(deltaPkts / dt);
  3899. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  3900. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  3901. state.natStatRateHistory.push(rateBps);
  3902. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  3903. state.natStatPktHistory.push(ratePkt);
  3904. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  3905. const bEl = document.getElementById('nat-stat-bytes');
  3906. const pEl = document.getElementById('nat-stat-packets');
  3907. const rEl = document.getElementById('nat-stat-rate');
  3908. const prEl = document.getElementById('nat-stat-pktrate');
  3909. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  3910. if (pEl) pEl.value = curPackets.toLocaleString();
  3911. if (rEl) rEl.value = formatBps(rateBps);
  3912. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  3913. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3914. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3915. } catch (e) {
  3916. console.error('Error polling NAT rule stats', e);
  3917. }
  3918. }
  3919. async function moveNATRule(id, dir) {
  3920. try {
  3921. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  3922. method: 'POST',
  3923. headers: { 'Content-Type': 'application/json' },
  3924. body: JSON.stringify({ direction: dir })
  3925. });
  3926. if (res.ok) loadFirewall(false);
  3927. } catch (err) {
  3928. showToast('Error', err.message, 'error');
  3929. }
  3930. }
  3931. async function toggleNATRuleState(id, disabled) {
  3932. try {
  3933. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  3934. method: 'POST',
  3935. headers: { 'Content-Type': 'application/json' },
  3936. body: JSON.stringify({ disabled })
  3937. });
  3938. if (res.ok) loadFirewall(false);
  3939. } catch (err) {
  3940. showToast('Error', err.message, 'error');
  3941. }
  3942. }
  3943. async function deleteNATRule(id) {
  3944. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  3945. try {
  3946. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3947. if (res.ok) {
  3948. showToast('Deleted', 'NAT rule removed', 'success');
  3949. loadFirewall(false);
  3950. }
  3951. } catch (err) {
  3952. showToast('Error', err.message, 'error');
  3953. }
  3954. }
  3955. // ----------------- Mangle Rules -----------------
  3956. function renderMangleRules() {
  3957. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  3958. const tbody = document.getElementById('mangle-table-body');
  3959. const empty = document.getElementById('mangle-empty');
  3960. if (!tbody) return;
  3961. tbody.innerHTML = '';
  3962. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3963. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  3964. if (rules.length === 0) {
  3965. empty?.classList.remove('hidden');
  3966. return;
  3967. }
  3968. empty?.classList.add('hidden');
  3969. rules.forEach((r, idx) => {
  3970. const tr = document.createElement('tr');
  3971. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3972. let markVal = '<span class="text-slate-500">-</span>';
  3973. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  3974. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  3975. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  3976. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  3977. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  3978. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  3979. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  3980. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  3981. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  3982. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  3983. 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>`;
  3984. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  3985. tr.innerHTML = `
  3986. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3987. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3988. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  3989. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3990. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3991. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  3992. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  3993. <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>
  3994. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3995. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3996. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3997. </td>
  3998. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3999. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4000. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4001. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4002. <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>
  4003. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4004. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4005. </td>
  4006. `;
  4007. tbody.appendChild(tr);
  4008. });
  4009. }
  4010. // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4011. function switchMangleRuleTab(tab) {
  4012. state.activeMangleRuleTab = tab;
  4013. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4014. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4015. btn.classList.add('text-slate-400', 'border-transparent');
  4016. });
  4017. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4018. if (activeBtn) {
  4019. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4020. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4021. }
  4022. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4023. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4024. if (activePane) activePane.classList.remove('hidden');
  4025. if (tab === 'statistics') {
  4026. startMangleStatPolling();
  4027. } else {
  4028. stopMangleStatPolling();
  4029. }
  4030. }
  4031. function toggleMangleField(fieldKey, expand) {
  4032. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4033. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4034. if (!plusBtn || !fieldBox) return;
  4035. if (expand) {
  4036. plusBtn.classList.add('hidden');
  4037. fieldBox.classList.remove('hidden');
  4038. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4039. if (valInput) valInput.focus();
  4040. } else {
  4041. fieldBox.classList.add('hidden');
  4042. plusBtn.classList.remove('hidden');
  4043. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4044. if (valInput) {
  4045. if (valInput.tagName === 'SELECT') {
  4046. valInput.selectedIndex = 0;
  4047. } else {
  4048. valInput.value = '';
  4049. }
  4050. }
  4051. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4052. if (invInput) invInput.checked = false;
  4053. if (fieldKey === 'cs') {
  4054. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4055. const el = document.getElementById(id);
  4056. if (el) el.checked = false;
  4057. });
  4058. }
  4059. if (fieldKey === 'natstate') {
  4060. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4061. const el = document.getElementById(id);
  4062. if (el) el.checked = false;
  4063. });
  4064. }
  4065. }
  4066. }
  4067. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4068. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4069. toggleMangleField(fieldKey, true);
  4070. let strVal = String(value);
  4071. if (hasInvert) {
  4072. const inv = strVal.startsWith('!');
  4073. if (inv) strVal = strVal.slice(1);
  4074. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4075. if (invEl) invEl.checked = inv;
  4076. }
  4077. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4078. if (valEl) valEl.value = strVal;
  4079. } else {
  4080. toggleMangleField(fieldKey, false);
  4081. }
  4082. }
  4083. function getMangleFieldVal(fieldKey, hasInvert = false) {
  4084. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4085. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4086. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4087. let v = valEl ? valEl.value.trim() : '';
  4088. if (!v) return '';
  4089. if (hasInvert) {
  4090. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4091. if (invEl && invEl.checked) {
  4092. v = '!' + v.replace(/^!/, '');
  4093. }
  4094. }
  4095. return v;
  4096. }
  4097. function toggleMaximizeMangleModal() {
  4098. const win = document.getElementById('mangle-modal-window');
  4099. if (!win) return;
  4100. if (win.classList.contains('max-w-[720px]')) {
  4101. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4102. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4103. } else {
  4104. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4105. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4106. }
  4107. }
  4108. function toggleMangleActionFields() {
  4109. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  4110. // Hide all dynamic rows first
  4111. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  4112. const el = document.getElementById(`mangle-row-${id}`);
  4113. if (el) el.classList.add('hidden');
  4114. });
  4115. const jumpBox = document.getElementById('mangle-action-jump-box');
  4116. const addrBox = document.getElementById('mangle-action-addrlist-box');
  4117. if (jumpBox) jumpBox.classList.add('hidden');
  4118. if (addrBox) addrBox.classList.add('hidden');
  4119. // Activate matching rows
  4120. if (act === 'mark-connection') {
  4121. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  4122. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4123. } else if (act === 'mark-routing') {
  4124. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  4125. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4126. } else if (act === 'mark-packet') {
  4127. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  4128. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4129. } else if (act === 'change-mss') {
  4130. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  4131. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4132. } else if (act === 'change-dscp') {
  4133. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  4134. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4135. } else if (act === 'change-ttl') {
  4136. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  4137. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4138. } else if (act === 'set-priority') {
  4139. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  4140. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4141. } else if (act === 'route') {
  4142. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  4143. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4144. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  4145. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  4146. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4147. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  4148. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4149. } else if (act === 'jump') {
  4150. if (jumpBox) jumpBox.classList.remove('hidden');
  4151. } else if (act.includes('address-list') || act.includes('address list')) {
  4152. if (addrBox) addrBox.classList.remove('hidden');
  4153. }
  4154. if (act === 'log') {
  4155. const logEl = document.getElementById('mangle-modal-log');
  4156. if (logEl) logEl.checked = true;
  4157. toggleMangleField('logprefix', true);
  4158. }
  4159. }
  4160. function toggleMangleLogPrefix() {
  4161. const isLog = document.getElementById('mangle-modal-log')?.checked;
  4162. toggleMangleField('logprefix', !!isLog);
  4163. }
  4164. const allMangleFieldKeys = [
  4165. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4166. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4167. 'routingmark', 'conntype', 'cs', 'natstate',
  4168. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4169. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4170. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4171. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  4172. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  4173. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  4174. ];
  4175. function openAddMangleModal() {
  4176. switchMangleRuleTab('general');
  4177. const badge = document.getElementById('mangle-modal-badge');
  4178. if (badge) badge.innerText = 'New...';
  4179. document.getElementById('mangle-modal-id').value = '';
  4180. document.getElementById('mangle-modal-enabled').checked = true;
  4181. document.getElementById('mangle-modal-comment').value = '';
  4182. document.getElementById('mangle-modal-chain').value = 'prerouting';
  4183. document.getElementById('mangle-modal-action').value = 'mark-connection';
  4184. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  4185. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  4186. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  4187. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  4188. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  4189. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  4190. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  4191. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  4192. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  4193. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  4194. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  4195. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  4196. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  4197. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  4198. populateInterfaceSelect('mangle-val-iniface');
  4199. populateInterfaceSelect('mangle-val-outiface');
  4200. populateAddressListSelect('mangle-val-srclist');
  4201. populateAddressListSelect('mangle-val-dstlist');
  4202. populateGeoIPSelect('mangle-val-srcgeo');
  4203. populateGeoIPSelect('mangle-val-dstgeo');
  4204. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  4205. resetCurrentMangleRuleCounters();
  4206. toggleMangleActionFields();
  4207. document.getElementById('mangle-modal').classList.remove('hidden');
  4208. }
  4209. function openEditMangleModal(id) {
  4210. const r = (state.mangleRules || []).find(rule => rule.id === id);
  4211. if (!r) return;
  4212. switchMangleRuleTab('general');
  4213. const badge = document.getElementById('mangle-modal-badge');
  4214. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4215. document.getElementById('mangle-modal-id').value = r.id;
  4216. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  4217. document.getElementById('mangle-modal-comment').value = r.comment || '';
  4218. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  4219. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  4220. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  4221. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  4222. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  4223. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  4224. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  4225. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  4226. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  4227. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  4228. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  4229. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  4230. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  4231. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  4232. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  4233. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  4234. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4235. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4236. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4237. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4238. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  4239. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  4240. setMangleFieldVal('src', r.src_address, true);
  4241. setMangleFieldVal('dst', r.dst_address, true);
  4242. setMangleFieldVal('srclist', r.src_address_list, true);
  4243. setMangleFieldVal('dstlist', r.dst_address_list, true);
  4244. setMangleFieldVal('srcgeo', r.src_geoip, true);
  4245. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  4246. if (r.protocol && r.protocol !== 'all') {
  4247. setMangleFieldVal('proto', r.protocol, true);
  4248. } else {
  4249. toggleMangleField('proto', false);
  4250. }
  4251. setMangleFieldVal('sport', r.src_port, true);
  4252. setMangleFieldVal('dport', r.dst_port, true);
  4253. setMangleFieldVal('anyport', r.any_port, true);
  4254. setMangleFieldVal('iniface', r.in_interface, true);
  4255. setMangleFieldVal('outiface', r.out_interface, true);
  4256. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  4257. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  4258. setMangleFieldVal('pktmark', r.packet_mark, true);
  4259. setMangleFieldVal('connmark', r.connection_mark, true);
  4260. setMangleFieldVal('routingmark', r.routing_mark, true);
  4261. setMangleFieldVal('conntype', r.connection_type, false);
  4262. // Connection State
  4263. const states = r.connection_state || [];
  4264. if (states.length > 0) {
  4265. toggleMangleField('cs', true);
  4266. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4267. const el = document.getElementById(`mangle-modal-cs-${s}`);
  4268. if (el) el.checked = states.includes(s);
  4269. });
  4270. } else {
  4271. toggleMangleField('cs', false);
  4272. }
  4273. // Connection NAT State
  4274. const natStates = r.connection_nat_state || [];
  4275. if (natStates.length > 0) {
  4276. toggleMangleField('natstate', true);
  4277. ['srcnat', 'dstnat'].forEach(s => {
  4278. const el = document.getElementById(`mangle-modal-nat-${s}`);
  4279. if (el) el.checked = natStates.includes(s);
  4280. });
  4281. } else {
  4282. toggleMangleField('natstate', false);
  4283. }
  4284. // Advanced tab fields
  4285. setMangleFieldVal('layer7', r.layer7_protocol, false);
  4286. setMangleFieldVal('content', r.content, false);
  4287. setMangleFieldVal('connbytes', r.connection_bytes, false);
  4288. setMangleFieldVal('connrate', r.connection_rate, false);
  4289. setMangleFieldVal('pcc', r.pcc, false);
  4290. setMangleFieldVal('srcmac', r.src_mac_address, true);
  4291. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  4292. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  4293. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4294. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4295. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  4296. setMangleFieldVal('tlshost', r.tls_host, false);
  4297. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  4298. setMangleFieldVal('priority', r.priority, false);
  4299. setMangleFieldVal('dscp', r.dscp, false);
  4300. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  4301. if (r.tos) {
  4302. const tosEl = document.getElementById('mangle-val-tos');
  4303. if (tosEl) tosEl.value = r.tos;
  4304. }
  4305. setMangleFieldVal('pktsize', r.packet_size, false);
  4306. setMangleFieldVal('random', r.random, false);
  4307. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  4308. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  4309. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  4310. setMangleFieldVal('ttl', r.ttl, false);
  4311. // Extra tab fields
  4312. setMangleFieldVal('nth', r.nth, false);
  4313. setMangleFieldVal('connlimit', r.connection_limit, false);
  4314. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  4315. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  4316. setMangleFieldVal('hotspot', r.hotspot, false);
  4317. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  4318. setMangleFieldVal('limit', r.limit, false);
  4319. setMangleFieldVal('dstlimit', r.dst_limit, false);
  4320. setMangleFieldVal('time', r.time, false);
  4321. setMangleFieldVal('psd', r.psd, false);
  4322. // Action fields
  4323. if (r.jump_target) {
  4324. const jtEl = document.getElementById('mangle-modal-jumptarget');
  4325. if (jtEl) jtEl.value = r.jump_target;
  4326. }
  4327. if (r.address_list) {
  4328. const alEl = document.getElementById('mangle-modal-action-addrlist');
  4329. if (alEl) alEl.value = r.address_list;
  4330. }
  4331. if (r.address_list_timeout) {
  4332. const toEl = document.getElementById('mangle-modal-action-timeout');
  4333. if (toEl) toEl.value = r.address_list_timeout;
  4334. }
  4335. setMangleFieldVal('logprefix', r.log_prefix, false);
  4336. // Statistics
  4337. const bEl = document.getElementById('mangle-stat-bytes');
  4338. const pEl = document.getElementById('mangle-stat-packets');
  4339. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4340. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4341. state.mangleLastBytes = r.bytes || 0;
  4342. state.mangleLastPackets = r.packets || 0;
  4343. state.mangleLastTimestamp = Date.now();
  4344. state.mangleStatRateHistory = new Array(30).fill(0);
  4345. state.mangleStatPktHistory = new Array(30).fill(0);
  4346. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4347. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4348. toggleMangleActionFields();
  4349. document.getElementById('mangle-modal').classList.remove('hidden');
  4350. }
  4351. function closeMangleModal() {
  4352. stopMangleStatPolling();
  4353. document.getElementById('mangle-modal').classList.add('hidden');
  4354. }
  4355. function copyMangleRule() {
  4356. document.getElementById('mangle-modal-id').value = '';
  4357. const badge = document.getElementById('mangle-modal-badge');
  4358. if (badge) badge.innerText = 'New...';
  4359. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  4360. }
  4361. function resetCurrentMangleRuleCounters() {
  4362. state.mangleStatRateHistory = new Array(30).fill(0);
  4363. state.mangleStatPktHistory = new Array(30).fill(0);
  4364. state.mangleLastBytes = 0;
  4365. state.mangleLastPackets = 0;
  4366. state.mangleLastTimestamp = Date.now();
  4367. const bEl = document.getElementById('mangle-stat-bytes');
  4368. const pEl = document.getElementById('mangle-stat-packets');
  4369. const rEl = document.getElementById('mangle-stat-rate');
  4370. const prEl = document.getElementById('mangle-stat-pktrate');
  4371. if (bEl) bEl.value = '0 B';
  4372. if (pEl) pEl.value = '0';
  4373. if (rEl) rEl.value = '0 bps';
  4374. if (prEl) prEl.value = '0 p/s';
  4375. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4376. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4377. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  4378. }
  4379. async function applyMangleRule(closeAfter = false) {
  4380. const id = document.getElementById('mangle-modal-id').value;
  4381. const chain = document.getElementById('mangle-modal-chain').value;
  4382. const action = document.getElementById('mangle-modal-action').value;
  4383. const comment = document.getElementById('mangle-modal-comment').value.trim();
  4384. const enabled = document.getElementById('mangle-modal-enabled').checked;
  4385. const src = getMangleFieldVal('src', true);
  4386. const dst = getMangleFieldVal('dst', true);
  4387. const srclist = getMangleFieldVal('srclist', true);
  4388. const dstlist = getMangleFieldVal('dstlist', true);
  4389. const srcgeo = getMangleFieldVal('srcgeo', true);
  4390. const dstgeo = getMangleFieldVal('dstgeo', true);
  4391. const proto = getMangleFieldVal('proto', true);
  4392. const sport = getMangleFieldVal('sport', true);
  4393. const dport = getMangleFieldVal('dport', true);
  4394. const anyport = getMangleFieldVal('anyport', true);
  4395. const iniface = getMangleFieldVal('iniface', true);
  4396. const outiface = getMangleFieldVal('outiface', true);
  4397. const inifacelist = getMangleFieldVal('inifacelist', true);
  4398. const outifacelist = getMangleFieldVal('outifacelist', true);
  4399. const pktmark = getMangleFieldVal('pktmark', true);
  4400. const connmark = getMangleFieldVal('connmark', true);
  4401. const routingmark = getMangleFieldVal('routingmark', true);
  4402. const conntype = getMangleFieldVal('conntype', false);
  4403. const states = [];
  4404. const csBox = document.getElementById('mangle-field-cs');
  4405. if (csBox && !csBox.classList.contains('hidden')) {
  4406. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4407. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  4408. });
  4409. }
  4410. const natStates = [];
  4411. const natBox = document.getElementById('mangle-field-natstate');
  4412. if (natBox && !natBox.classList.contains('hidden')) {
  4413. ['srcnat', 'dstnat'].forEach(s => {
  4414. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  4415. });
  4416. }
  4417. const payload = {
  4418. id,
  4419. chain,
  4420. action,
  4421. protocol: proto || 'all',
  4422. src_address: src,
  4423. dst_address: dst,
  4424. src_port: sport,
  4425. dst_port: dport,
  4426. any_port: anyport,
  4427. in_interface: iniface,
  4428. out_interface: outiface,
  4429. in_interface_list: inifacelist,
  4430. out_interface_list: outifacelist,
  4431. packet_mark: pktmark,
  4432. connection_mark: connmark,
  4433. routing_mark: routingmark,
  4434. connection_type: conntype,
  4435. connection_state: states,
  4436. connection_nat_state: natStates,
  4437. src_address_list: srclist,
  4438. dst_address_list: dstlist,
  4439. src_geoip: srcgeo,
  4440. dst_geoip: dstgeo,
  4441. comment,
  4442. disabled: !enabled,
  4443. // Advanced tab
  4444. layer7_protocol: getMangleFieldVal('layer7', false),
  4445. content: getMangleFieldVal('content', false),
  4446. connection_bytes: getMangleFieldVal('connbytes', false),
  4447. connection_rate: getMangleFieldVal('connrate', false),
  4448. pcc: getMangleFieldVal('pcc', false),
  4449. src_mac_address: getMangleFieldVal('srcmac', true),
  4450. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  4451. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  4452. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  4453. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  4454. ipsec_policy: getMangleFieldVal('ipsec', false),
  4455. tls_host: getMangleFieldVal('tlshost', false),
  4456. ingress_priority: getMangleFieldVal('ingresspriority', false),
  4457. priority: getMangleFieldVal('priority', false),
  4458. dscp: getMangleFieldVal('dscp', false),
  4459. tcp_mss: getMangleFieldVal('tcpmss', false),
  4460. tos: document.getElementById('mangle-val-tos')?.value || '',
  4461. packet_size: getMangleFieldVal('pktsize', false),
  4462. random: getMangleFieldVal('random', false),
  4463. tcp_flags: getMangleFieldVal('tcpflags', false),
  4464. icmp_options: getMangleFieldVal('icmpoptions', false),
  4465. ipv4_options: getMangleFieldVal('ipv4options', false),
  4466. ttl: getMangleFieldVal('ttl', false),
  4467. // Extra tab
  4468. nth: getMangleFieldVal('nth', false),
  4469. connection_limit: getMangleFieldVal('connlimit', false),
  4470. src_address_type: getMangleFieldVal('srcaddrtype', false),
  4471. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  4472. hotspot: getMangleFieldVal('hotspot', false),
  4473. ip_fragment: getMangleFieldVal('ipfragment', false),
  4474. limit: getMangleFieldVal('limit', false),
  4475. dst_limit: getMangleFieldVal('dstlimit', false),
  4476. time: getMangleFieldVal('time', false),
  4477. psd: getMangleFieldVal('psd', false),
  4478. // Action tab
  4479. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  4480. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  4481. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  4482. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  4483. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  4484. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  4485. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  4486. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  4487. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  4488. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  4489. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  4490. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  4491. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  4492. log: document.getElementById('mangle-modal-log')?.checked || false,
  4493. log_prefix: getMangleFieldVal('logprefix', false)
  4494. };
  4495. try {
  4496. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  4497. method: 'POST',
  4498. headers: { 'Content-Type': 'application/json' },
  4499. body: JSON.stringify(payload)
  4500. });
  4501. if (res.ok) {
  4502. const data = await res.json();
  4503. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  4504. loadFirewall(false);
  4505. if (closeAfter) {
  4506. closeMangleModal();
  4507. } else {
  4508. if (data.id) {
  4509. document.getElementById('mangle-modal-id').value = data.id;
  4510. const badge = document.getElementById('mangle-modal-badge');
  4511. if (badge) badge.innerText = `#${data.id}`;
  4512. }
  4513. }
  4514. } else {
  4515. const err = await res.json();
  4516. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  4517. }
  4518. } catch (err) {
  4519. showToast('Error', err.message, 'error');
  4520. }
  4521. }
  4522. function submitSaveMangleRule(e) {
  4523. if (e && e.preventDefault) e.preventDefault();
  4524. return applyMangleRule(true);
  4525. }
  4526. function startMangleStatPolling() {
  4527. stopMangleStatPolling();
  4528. pollMangleRuleStats();
  4529. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  4530. }
  4531. function stopMangleStatPolling() {
  4532. if (state.mangleStatInterval) {
  4533. clearInterval(state.mangleStatInterval);
  4534. state.mangleStatInterval = null;
  4535. }
  4536. }
  4537. async function pollMangleRuleStats() {
  4538. const id = document.getElementById('mangle-modal-id')?.value;
  4539. if (!id) {
  4540. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  4541. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  4542. return;
  4543. }
  4544. try {
  4545. const res = await fetch(`${API_BASE}/firewall/mangle`);
  4546. if (!res.ok) return;
  4547. const rules = await res.json();
  4548. const r = rules.find(x => x.id === id);
  4549. if (!r) return;
  4550. const now = Date.now();
  4551. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  4552. state.mangleLastTimestamp = now;
  4553. const curBytes = r.bytes || 0;
  4554. const curPackets = r.packets || 0;
  4555. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  4556. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  4557. state.mangleLastBytes = curBytes;
  4558. state.mangleLastPackets = curPackets;
  4559. const rateBps = Math.round((deltaBytes * 8) / dt);
  4560. const ratePkt = Math.round(deltaPkts / dt);
  4561. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  4562. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  4563. state.mangleStatRateHistory.push(rateBps);
  4564. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  4565. state.mangleStatPktHistory.push(ratePkt);
  4566. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  4567. const bEl = document.getElementById('mangle-stat-bytes');
  4568. const pEl = document.getElementById('mangle-stat-packets');
  4569. const rEl = document.getElementById('mangle-stat-rate');
  4570. const prEl = document.getElementById('mangle-stat-pktrate');
  4571. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4572. if (pEl) pEl.value = curPackets.toLocaleString();
  4573. if (rEl) rEl.value = formatBps(rateBps);
  4574. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4575. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4576. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4577. } catch (e) {
  4578. console.error('Error polling Mangle rule stats', e);
  4579. }
  4580. }
  4581. async function moveMangleRule(id, dir) {
  4582. try {
  4583. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  4584. method: 'POST',
  4585. headers: { 'Content-Type': 'application/json' },
  4586. body: JSON.stringify({ direction: dir })
  4587. });
  4588. if (res.ok) loadFirewall(false);
  4589. } catch (err) {
  4590. showToast('Error', err.message, 'error');
  4591. }
  4592. }
  4593. async function toggleMangleRuleState(id, disabled) {
  4594. try {
  4595. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  4596. method: 'POST',
  4597. headers: { 'Content-Type': 'application/json' },
  4598. body: JSON.stringify({ disabled })
  4599. });
  4600. if (res.ok) loadFirewall(false);
  4601. } catch (err) {
  4602. showToast('Error', err.message, 'error');
  4603. }
  4604. }
  4605. async function deleteMangleRule(id) {
  4606. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  4607. try {
  4608. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4609. if (res.ok) {
  4610. showToast('Deleted', 'Mangle rule removed', 'success');
  4611. loadFirewall(false);
  4612. }
  4613. } catch (err) {
  4614. showToast('Error', err.message, 'error');
  4615. }
  4616. }
  4617. // ----------------- Address Lists -----------------
  4618. function renderAddressLists() {
  4619. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  4620. const tbody = document.getElementById('addrlist-table-body');
  4621. const empty = document.getElementById('addrlist-empty');
  4622. if (!tbody) return;
  4623. tbody.innerHTML = '';
  4624. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  4625. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  4626. // Update filter select
  4627. const sel = document.getElementById('addrlist-filter-name');
  4628. if (sel) {
  4629. const cur = sel.value;
  4630. sel.innerHTML = '<option value="">All Lists</option>';
  4631. const set = new Set((state.addressLists || []).map(a => a.name));
  4632. set.forEach(n => {
  4633. const opt = document.createElement('option');
  4634. opt.value = n;
  4635. opt.innerText = n;
  4636. if (n === cur) opt.selected = true;
  4637. sel.appendChild(opt);
  4638. });
  4639. }
  4640. if (entries.length === 0) {
  4641. empty?.classList.remove('hidden');
  4642. return;
  4643. }
  4644. empty?.classList.add('hidden');
  4645. entries.forEach((e, idx) => {
  4646. const tr = document.createElement('tr');
  4647. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  4648. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  4649. tr.innerHTML = `
  4650. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  4651. <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>
  4652. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  4653. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  4654. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  4655. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4656. <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>
  4657. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  4658. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4659. </td>
  4660. `;
  4661. tbody.appendChild(tr);
  4662. });
  4663. populateCommonAddrListDatalist();
  4664. }
  4665. function openAddAddrListModal() {
  4666. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  4667. document.getElementById('addrlist-modal-id').value = '';
  4668. document.getElementById('addrlist-modal-name').value = '';
  4669. document.getElementById('addrlist-modal-addr').value = '';
  4670. document.getElementById('addrlist-modal-comment').value = '';
  4671. document.getElementById('addrlist-modal-disabled').checked = false;
  4672. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4673. if (submitBtn) submitBtn.innerText = 'Add to List';
  4674. document.getElementById('addrlist-modal').classList.remove('hidden');
  4675. }
  4676. function openEditAddrListModal(id) {
  4677. const e = (state.addressLists || []).find(item => item.id === id);
  4678. if (!e) return;
  4679. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  4680. document.getElementById('addrlist-modal-id').value = e.id;
  4681. document.getElementById('addrlist-modal-name').value = e.name;
  4682. document.getElementById('addrlist-modal-addr').value = e.address;
  4683. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  4684. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  4685. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4686. if (submitBtn) submitBtn.innerText = 'Save Changes';
  4687. document.getElementById('addrlist-modal').classList.remove('hidden');
  4688. }
  4689. function closeAddrListModal() {
  4690. document.getElementById('addrlist-modal').classList.add('hidden');
  4691. }
  4692. async function submitSaveAddrList(e) {
  4693. e.preventDefault();
  4694. const id = document.getElementById('addrlist-modal-id').value;
  4695. const name = document.getElementById('addrlist-modal-name').value.trim();
  4696. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  4697. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  4698. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  4699. try {
  4700. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  4701. method: 'POST',
  4702. headers: { 'Content-Type': 'application/json' },
  4703. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  4704. });
  4705. if (res.ok) {
  4706. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  4707. closeAddrListModal();
  4708. loadFirewall(false);
  4709. } else {
  4710. const err = await res.json();
  4711. showToast('Error', err.message || 'Failed to save address list', 'error');
  4712. }
  4713. } catch (err) {
  4714. showToast('Error', err.message, 'error');
  4715. }
  4716. }
  4717. async function toggleAddrListState(id, disabled) {
  4718. try {
  4719. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  4720. method: 'POST',
  4721. headers: { 'Content-Type': 'application/json' },
  4722. body: JSON.stringify({ disabled })
  4723. });
  4724. if (res.ok) {
  4725. loadFirewall(false);
  4726. }
  4727. } catch (err) {
  4728. showToast('Error', err.message, 'error');
  4729. }
  4730. }
  4731. async function deleteAddrList(id) {
  4732. if (!confirm('Are you sure you want to delete this address list item?')) return;
  4733. try {
  4734. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4735. if (res.ok) {
  4736. showToast('Deleted', 'Address list item removed', 'info');
  4737. loadFirewall(false);
  4738. }
  4739. } catch (err) {
  4740. showToast('Error', err.message, 'error');
  4741. }
  4742. }
  4743. // ----------------- Geo-Location IP Management -----------------
  4744. async function loadGeoIP() {
  4745. try {
  4746. const [statusRes, countriesRes] = await Promise.all([
  4747. fetch(`${API_BASE}/firewall/geoip/status`),
  4748. fetch(`${API_BASE}/firewall/geoip/countries`)
  4749. ]);
  4750. if (statusRes.ok) state.geoStatus = await statusRes.json();
  4751. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  4752. updateGeoHeader();
  4753. renderGeoCountries();
  4754. } catch (err) {
  4755. console.error('Failed to load GeoIP:', err);
  4756. }
  4757. }
  4758. function getGeoUsageMap() {
  4759. const usage = {};
  4760. const checkRule = (r, type) => {
  4761. ['src_geoip', 'dst_geoip'].forEach(field => {
  4762. let val = (r && r[field]) || '';
  4763. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  4764. if (code) {
  4765. if (!usage[code]) usage[code] = [];
  4766. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  4767. if (!usage[code].includes(label)) usage[code].push(label);
  4768. }
  4769. });
  4770. };
  4771. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  4772. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  4773. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  4774. return usage;
  4775. }
  4776. function updateGeoHeader() {
  4777. const s = state.geoStatus || {};
  4778. const statusBadge = document.getElementById('geo-status-badge');
  4779. if (statusBadge) {
  4780. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  4781. statusBadge.className = s.auto_update
  4782. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  4783. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  4784. }
  4785. const intervalLabel = document.getElementById('geo-interval-label');
  4786. if (intervalLabel) {
  4787. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  4788. }
  4789. const usageMap = getGeoUsageMap();
  4790. const inUseCount = Object.keys(usageMap).length;
  4791. const activeCountEl = document.getElementById('geo-stat-active-countries');
  4792. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  4793. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  4794. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  4795. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  4796. if (lastSyncEl) {
  4797. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  4798. const d = new Date(s.last_updated);
  4799. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4800. } else {
  4801. lastSyncEl.innerText = 'Never (Sync Pending)';
  4802. }
  4803. }
  4804. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  4805. if (nextSyncEl) {
  4806. if (s.next_update && !s.next_update.startsWith('0001')) {
  4807. const d = new Date(s.next_update);
  4808. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4809. } else {
  4810. nextSyncEl.innerText = '-';
  4811. }
  4812. }
  4813. const badge = document.getElementById('fw-badge-geo');
  4814. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  4815. }
  4816. function renderGeoCountries() {
  4817. const tbody = document.getElementById('geo-table-body');
  4818. const empty = document.getElementById('geo-empty');
  4819. if (!tbody) return;
  4820. tbody.innerHTML = '';
  4821. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  4822. const continent = document.getElementById('geo-continent-filter')?.value || '';
  4823. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  4824. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  4825. const usageMap = getGeoUsageMap();
  4826. const countries = (state.geoCountries || []).filter(c => {
  4827. const isUsed = !!usageMap[c.code];
  4828. if (inUseOnly && !isUsed) return false;
  4829. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  4830. if (continent && c.continent !== continent) return false;
  4831. if (q) {
  4832. const matchCode = c.code.toLowerCase().includes(q);
  4833. const matchName = c.name.toLowerCase().includes(q);
  4834. if (!matchCode && !matchName) return false;
  4835. }
  4836. return true;
  4837. });
  4838. if (countries.length === 0) {
  4839. empty?.classList.remove('hidden');
  4840. return;
  4841. }
  4842. empty?.classList.add('hidden');
  4843. countries.forEach(c => {
  4844. const tr = document.createElement('tr');
  4845. const isUsed = !!usageMap[c.code];
  4846. const rulesUsing = usageMap[c.code] || [];
  4847. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  4848. let statusHtml = '';
  4849. if (isUsed) {
  4850. 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>`;
  4851. } else if (c.subnet_count > 0) {
  4852. 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>';
  4853. } else {
  4854. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  4855. }
  4856. tr.innerHTML = `
  4857. <td class="py-2.5 px-3 text-center">
  4858. <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'}">
  4859. ${c.code}
  4860. </span>
  4861. </td>
  4862. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  4863. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  4864. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  4865. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  4866. </td>
  4867. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  4868. <td class="py-2.5 px-3">
  4869. ${statusHtml}
  4870. </td>
  4871. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4872. <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>
  4873. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  4874. </td>
  4875. `;
  4876. tbody.appendChild(tr);
  4877. });
  4878. }
  4879. function quickFilterGeo(preset) {
  4880. const searchInput = document.getElementById('geo-search-input');
  4881. const continentSel = document.getElementById('geo-continent-filter');
  4882. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  4883. const cachedCheck = document.getElementById('geo-filter-cached-only');
  4884. if (searchInput) searchInput.value = '';
  4885. if (continentSel) continentSel.value = '';
  4886. if (inUseCheck) inUseCheck.checked = false;
  4887. if (cachedCheck) cachedCheck.checked = false;
  4888. if (preset === 'GR') {
  4889. if (searchInput) searchInput.value = 'Greece';
  4890. } else if (preset === 'Europe') {
  4891. if (continentSel) continentSel.value = 'Europe';
  4892. } else if (preset === 'HIGHRISK') {
  4893. if (searchInput) searchInput.value = 'China';
  4894. }
  4895. renderGeoCountries();
  4896. }
  4897. async function toggleGeoCountry(code, enabled) {
  4898. try {
  4899. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  4900. method: 'POST',
  4901. headers: { 'Content-Type': 'application/json' },
  4902. body: JSON.stringify({ enabled })
  4903. });
  4904. if (res.ok) {
  4905. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  4906. loadGeoIP();
  4907. } else {
  4908. const err = await res.json();
  4909. showToast('Error', err.message || 'Failed to toggle country', 'error');
  4910. }
  4911. } catch (err) {
  4912. showToast('Error', err.message, 'error');
  4913. }
  4914. }
  4915. async function updateGeoCountry(code) {
  4916. try {
  4917. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  4918. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  4919. if (res.ok) {
  4920. const data = await res.json();
  4921. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  4922. loadGeoIP();
  4923. } else {
  4924. const err = await res.json();
  4925. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  4926. }
  4927. } catch (err) {
  4928. showToast('Error', err.message, 'error');
  4929. }
  4930. }
  4931. async function triggerGeoUpdateNow() {
  4932. const spinner = document.getElementById('geo-update-spinner');
  4933. if (spinner) spinner.classList.remove('hidden');
  4934. try {
  4935. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  4936. if (res.ok) {
  4937. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  4938. setTimeout(() => {
  4939. loadGeoIP();
  4940. if (spinner) spinner.classList.add('hidden');
  4941. }, 2500);
  4942. } else {
  4943. const err = await res.json();
  4944. showToast('Notice', err.message || 'Update in progress', 'info');
  4945. if (spinner) spinner.classList.add('hidden');
  4946. }
  4947. } catch (err) {
  4948. showToast('Error', err.message, 'error');
  4949. if (spinner) spinner.classList.add('hidden');
  4950. }
  4951. }
  4952. async function applyGeoPreset(preset) {
  4953. try {
  4954. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  4955. method: 'POST',
  4956. headers: { 'Content-Type': 'application/json' },
  4957. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  4958. });
  4959. if (res.ok) {
  4960. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  4961. loadGeoIP();
  4962. }
  4963. } catch (err) {
  4964. showToast('Error', err.message, 'error');
  4965. }
  4966. }
  4967. function openGeoIntervalModal() {
  4968. const s = state.geoStatus || {};
  4969. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  4970. const sel = document.getElementById('geo-cfg-interval');
  4971. const customBox = document.getElementById('geo-cfg-custom-box');
  4972. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  4973. const curHours = s.interval_hours || 24;
  4974. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  4975. if (matchOption) {
  4976. sel.value = String(curHours);
  4977. customBox.classList.add('hidden');
  4978. } else {
  4979. sel.value = 'custom';
  4980. customHoursInput.value = curHours;
  4981. customBox.classList.remove('hidden');
  4982. }
  4983. document.getElementById('geo-interval-modal').classList.remove('hidden');
  4984. }
  4985. function closeGeoIntervalModal() {
  4986. document.getElementById('geo-interval-modal').classList.add('hidden');
  4987. }
  4988. function toggleCustomGeoInterval() {
  4989. const val = document.getElementById('geo-cfg-interval').value;
  4990. const customBox = document.getElementById('geo-cfg-custom-box');
  4991. if (val === 'custom') {
  4992. customBox.classList.remove('hidden');
  4993. } else {
  4994. customBox.classList.add('hidden');
  4995. }
  4996. }
  4997. async function submitGeoIntervalSettings(e) {
  4998. e.preventDefault();
  4999. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5000. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5001. let hours = 24;
  5002. if (intervalVal === 'custom') {
  5003. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5004. } else {
  5005. hours = parseInt(intervalVal, 10) || 24;
  5006. }
  5007. try {
  5008. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5009. method: 'POST',
  5010. headers: { 'Content-Type': 'application/json' },
  5011. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5012. });
  5013. if (res.ok) {
  5014. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5015. closeGeoIntervalModal();
  5016. loadGeoIP();
  5017. } else {
  5018. const err = await res.json();
  5019. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5020. }
  5021. } catch (err) {
  5022. showToast('Error', err.message, 'error');
  5023. }
  5024. }
  5025. async function viewGeoSubnets(code, name) {
  5026. if (!name) {
  5027. const found = (state.geoCountries || []).find(x => x.code === code);
  5028. name = found ? found.name : code;
  5029. }
  5030. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5031. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5032. const listEl = document.getElementById('geo-subnets-list');
  5033. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5034. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5035. try {
  5036. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5037. if (res.ok) {
  5038. const data = await res.json();
  5039. const subnets = data.subnets || [];
  5040. if (subnets.length === 0) {
  5041. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5042. } else {
  5043. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5044. }
  5045. } else {
  5046. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5047. }
  5048. } catch (err) {
  5049. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5050. }
  5051. }
  5052. function closeGeoSubnetsModal() {
  5053. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5054. }
  5055. // ----------------- Active Connections Tracking -----------------
  5056. async function loadConnections() {
  5057. try {
  5058. const res = await fetch(`${API_BASE}/firewall/connections`);
  5059. const data = await res.json();
  5060. state.connections = Array.isArray(data) ? data : [];
  5061. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5062. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5063. renderConnections();
  5064. } catch (err) {
  5065. console.error('Failed to load connections:', err);
  5066. }
  5067. }
  5068. function renderConnections() {
  5069. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  5070. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  5071. const tbody = document.getElementById('conns-table-body');
  5072. const empty = document.getElementById('conns-empty');
  5073. if (!tbody) return;
  5074. tbody.innerHTML = '';
  5075. const conns = (state.connections || []).filter(c => {
  5076. if (protoFilter && c.protocol !== protoFilter) return false;
  5077. if (search) {
  5078. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  5079. if (!line.includes(search)) return false;
  5080. }
  5081. return true;
  5082. });
  5083. if (conns.length === 0) {
  5084. empty?.classList.remove('hidden');
  5085. return;
  5086. }
  5087. empty?.classList.add('hidden');
  5088. conns.slice(0, 150).forEach(c => {
  5089. const tr = document.createElement('tr');
  5090. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5091. let stateColor = 'text-slate-400';
  5092. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  5093. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  5094. tr.innerHTML = `
  5095. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  5096. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  5097. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  5098. <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>
  5099. <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>
  5100. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  5101. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  5102. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  5103. <td class="py-2.5 px-3 text-right font-sans">
  5104. <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>
  5105. </td>
  5106. `;
  5107. tbody.appendChild(tr);
  5108. });
  5109. }
  5110. async function killConnection(protocol, src, sport, dst, dport) {
  5111. try {
  5112. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  5113. method: 'POST',
  5114. headers: { 'Content-Type': 'application/json' },
  5115. body: JSON.stringify({ protocol, src, sport, dst, dport })
  5116. });
  5117. if (res.ok) {
  5118. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  5119. loadConnections();
  5120. }
  5121. } catch (err) {
  5122. showToast('Error', err.message, 'error');
  5123. }
  5124. }
  5125. async function resetFirewallCounters() {
  5126. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  5127. try {
  5128. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  5129. if (res.ok) {
  5130. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  5131. loadFirewall(false);
  5132. }
  5133. } catch (err) {
  5134. showToast('Error', err.message, 'error');
  5135. }
  5136. }
  5137. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  5138. function switchRoutesSubTab(tab) {
  5139. state.routesSubTab = tab;
  5140. const tabs = ['routes', 'rules', 'tables'];
  5141. tabs.forEach(t => {
  5142. const panel = document.getElementById(`routes-subtab-${t}`);
  5143. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  5144. if (panel) {
  5145. if (t === tab) panel.classList.remove('hidden');
  5146. else panel.classList.add('hidden');
  5147. }
  5148. if (btn) {
  5149. if (t === tab) {
  5150. 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';
  5151. } else {
  5152. 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';
  5153. }
  5154. }
  5155. });
  5156. setTimeout(initTableSorting, 50);
  5157. }
  5158. async function loadRoutes() {
  5159. try {
  5160. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  5161. fetch(`${API_BASE}/routes`),
  5162. fetch(`${API_BASE}/routing/rules`),
  5163. fetch(`${API_BASE}/routing/tables`)
  5164. ]);
  5165. if (routesRes.ok) state.routes = await routesRes.json();
  5166. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  5167. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  5168. const bRoutes = document.getElementById('routes-badge-routes');
  5169. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  5170. const showSystem = document.getElementById('prule-show-system')?.checked;
  5171. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5172. const bRules = document.getElementById('routes-badge-rules');
  5173. if (bRules) bRules.innerText = userRules.length;
  5174. const bTables = document.getElementById('routes-badge-tables');
  5175. if (bTables) bTables.innerText = (state.routingTables || []).length;
  5176. const bRoutesCount = document.getElementById('badge-routes-count');
  5177. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  5178. renderRoutesList();
  5179. renderPolicyRules();
  5180. renderRoutingTables();
  5181. } catch (err) {
  5182. console.error('Failed to load routing:', err);
  5183. }
  5184. }
  5185. function renderRoutesList() {
  5186. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  5187. const tbody = document.getElementById('routes-table-body');
  5188. const empty = document.getElementById('routes-empty');
  5189. if (!tbody) return;
  5190. tbody.innerHTML = '';
  5191. // Update table filter select
  5192. const sel = document.getElementById('routes-filter-table');
  5193. if (sel) {
  5194. const cur = sel.value;
  5195. sel.innerHTML = '<option value="">All Tables</option>';
  5196. (state.routingTables || []).forEach(t => {
  5197. const opt = document.createElement('option');
  5198. opt.value = t.name;
  5199. opt.innerText = t.name;
  5200. if (t.name === cur) opt.selected = true;
  5201. sel.appendChild(opt);
  5202. });
  5203. }
  5204. const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
  5205. document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
  5206. if (routes.length === 0) {
  5207. empty?.classList.remove('hidden');
  5208. return;
  5209. }
  5210. empty?.classList.add('hidden');
  5211. routes.forEach(r => {
  5212. const tr = document.createElement('tr');
  5213. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  5214. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  5215. // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
  5216. let flags = '';
  5217. if (r.dynamic) flags += 'D';
  5218. if (r.active) flags += 'A';
  5219. if (r.connect) flags += 'C';
  5220. if (r.static) flags += 'S';
  5221. if (r.disabled) flags += 'X';
  5222. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  5223. tr.innerHTML = `
  5224. <td class="py-2.5 px-3 text-center">
  5225. <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'}">
  5226. ${flags || '-'}
  5227. </span>
  5228. </td>
  5229. <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
  5230. <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>
  5231. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  5232. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  5233. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  5234. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  5235. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5236. ${r.static ? `
  5237. <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>
  5238. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  5239. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5240. ` : `
  5241. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  5242. `}
  5243. </td>
  5244. `;
  5245. tbody.appendChild(tr);
  5246. });
  5247. }
  5248. function openAddRouteModal() {
  5249. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  5250. document.getElementById('route-modal-id').value = '';
  5251. document.getElementById('route-modal-old-dst').value = '';
  5252. document.getElementById('route-modal-old-gw').value = '';
  5253. document.getElementById('route-modal-old-distance').value = '';
  5254. document.getElementById('route-modal-old-table').value = '';
  5255. document.getElementById('route-modal-old-iface').value = '';
  5256. const dstInput = document.getElementById('route-modal-dst');
  5257. const gwInput = document.getElementById('route-modal-gw');
  5258. const distInput = document.getElementById('route-modal-distance');
  5259. const ifaceSelect = document.getElementById('route-modal-iface');
  5260. const tableSelect = document.getElementById('route-modal-table');
  5261. const commentInput = document.getElementById('route-modal-comment');
  5262. const disCheck = document.getElementById('route-modal-disabled');
  5263. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5264. dstInput.disabled = false;
  5265. dstInput.value = '0.0.0.0/0';
  5266. gwInput.disabled = false;
  5267. gwInput.value = '';
  5268. distInput.disabled = false;
  5269. distInput.value = '1';
  5270. ifaceSelect.disabled = false;
  5271. tableSelect.disabled = false;
  5272. commentInput.disabled = false;
  5273. commentInput.value = '';
  5274. disCheck.disabled = false;
  5275. disCheck.checked = false;
  5276. if (saveBtn) saveBtn.classList.remove('hidden');
  5277. populateInterfaceSelect('route-modal-iface');
  5278. // Populate tables
  5279. tableSelect.innerHTML = '';
  5280. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5281. const opt = document.createElement('option');
  5282. opt.value = t.name;
  5283. opt.innerText = t.name;
  5284. if (t.name === 'main') opt.selected = true;
  5285. tableSelect.appendChild(opt);
  5286. });
  5287. document.getElementById('route-modal').classList.remove('hidden');
  5288. }
  5289. function openEditRouteModal(id) {
  5290. const r = (state.routes || []).find(route => route.id === id);
  5291. if (!r) return;
  5292. const isStatic = !!r.static;
  5293. document.getElementById('route-modal-title').innerText = isStatic
  5294. ? `Edit Route: ${r.dst_address}`
  5295. : `Route Properties (Read Only): ${r.dst_address}`;
  5296. document.getElementById('route-modal-id').value = r.id;
  5297. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  5298. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  5299. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  5300. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  5301. document.getElementById('route-modal-old-iface').value = r.interface || '';
  5302. const dstInput = document.getElementById('route-modal-dst');
  5303. const gwInput = document.getElementById('route-modal-gw');
  5304. const distInput = document.getElementById('route-modal-distance');
  5305. const ifaceSelect = document.getElementById('route-modal-iface');
  5306. const tableSelect = document.getElementById('route-modal-table');
  5307. const commentInput = document.getElementById('route-modal-comment');
  5308. const disCheck = document.getElementById('route-modal-disabled');
  5309. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5310. dstInput.value = r.dst_address;
  5311. gwInput.value = r.gateway || '';
  5312. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  5313. commentInput.value = r.comment || '';
  5314. disCheck.checked = !!r.disabled;
  5315. dstInput.disabled = !isStatic;
  5316. gwInput.disabled = !isStatic;
  5317. distInput.disabled = !isStatic;
  5318. ifaceSelect.disabled = !isStatic;
  5319. tableSelect.disabled = !isStatic;
  5320. commentInput.disabled = !isStatic;
  5321. disCheck.disabled = !isStatic;
  5322. if (saveBtn) {
  5323. if (isStatic) {
  5324. saveBtn.classList.remove('hidden');
  5325. } else {
  5326. saveBtn.classList.add('hidden');
  5327. }
  5328. }
  5329. populateInterfaceSelect('route-modal-iface', r.interface);
  5330. tableSelect.innerHTML = '';
  5331. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5332. const opt = document.createElement('option');
  5333. opt.value = t.name;
  5334. opt.innerText = t.name;
  5335. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  5336. tableSelect.appendChild(opt);
  5337. });
  5338. document.getElementById('route-modal').classList.remove('hidden');
  5339. }
  5340. function closeRouteModal() {
  5341. document.getElementById('route-modal').classList.add('hidden');
  5342. }
  5343. async function submitSaveRoute(e) {
  5344. e.preventDefault();
  5345. const id = document.getElementById('route-modal-id').value;
  5346. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  5347. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  5348. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  5349. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  5350. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  5351. const dst = document.getElementById('route-modal-dst').value.trim();
  5352. const gw = document.getElementById('route-modal-gw').value.trim();
  5353. const table = document.getElementById('route-modal-table').value;
  5354. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  5355. const iface = document.getElementById('route-modal-iface').value;
  5356. const comment = document.getElementById('route-modal-comment').value.trim();
  5357. const disabled = document.getElementById('route-modal-disabled').checked;
  5358. if (!dst) {
  5359. showToast('Error', 'Destination address is required', 'error');
  5360. return;
  5361. }
  5362. if (!gw && !iface) {
  5363. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  5364. return;
  5365. }
  5366. const payload = {
  5367. id,
  5368. old_dst_address: oldDst,
  5369. old_gateway: oldGw,
  5370. old_routing_table: oldTable,
  5371. old_interface: oldIface,
  5372. dst_address: dst,
  5373. gateway: gw || iface,
  5374. routing_table: table,
  5375. distance,
  5376. interface: iface,
  5377. comment,
  5378. disabled
  5379. };
  5380. if (oldDistStr !== undefined && oldDistStr !== '') {
  5381. payload.old_distance = parseInt(oldDistStr, 10);
  5382. }
  5383. try {
  5384. const res = await fetch(`${API_BASE}/routes`, {
  5385. method: 'POST',
  5386. headers: { 'Content-Type': 'application/json' },
  5387. body: JSON.stringify(payload)
  5388. });
  5389. if (res.ok) {
  5390. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  5391. closeRouteModal();
  5392. loadRoutes();
  5393. } else {
  5394. const err = await res.json();
  5395. showToast('Error', err.message || 'Failed to save route', 'error');
  5396. }
  5397. } catch (err) {
  5398. showToast('Error', err.message, 'error');
  5399. }
  5400. }
  5401. async function toggleRouteState(id, disabled) {
  5402. try {
  5403. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  5404. method: 'POST',
  5405. headers: { 'Content-Type': 'application/json' },
  5406. body: JSON.stringify({ disabled })
  5407. });
  5408. if (res.ok) loadRoutes();
  5409. } catch (err) {
  5410. showToast('Error', err.message, 'error');
  5411. }
  5412. }
  5413. async function deleteRoute(id) {
  5414. if (!confirm('Are you sure you want to delete this route?')) return;
  5415. try {
  5416. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5417. if (res.ok) {
  5418. showToast('Deleted', 'Route removed', 'success');
  5419. loadRoutes();
  5420. }
  5421. } catch (err) {
  5422. showToast('Error', err.message, 'error');
  5423. }
  5424. }
  5425. // ----------------- Policy Rules (/ip route rule) -----------------
  5426. function renderPolicyRules() {
  5427. const tbody = document.getElementById('rules-table-body');
  5428. const empty = document.getElementById('rules-empty');
  5429. if (!tbody) return;
  5430. tbody.innerHTML = '';
  5431. const showSystem = document.getElementById('prule-show-system')?.checked;
  5432. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5433. const countBadge = document.getElementById('rules-count-badge');
  5434. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  5435. const bRules = document.getElementById('routes-badge-rules');
  5436. if (bRules) bRules.innerText = filtered.length;
  5437. if (filtered.length === 0) {
  5438. empty?.classList.remove('hidden');
  5439. return;
  5440. }
  5441. empty?.classList.add('hidden');
  5442. filtered.forEach(pr => {
  5443. const isSys = pr.is_default || pr.is_system;
  5444. const tr = document.createElement('tr');
  5445. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  5446. tr.innerHTML = `
  5447. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  5448. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  5449. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  5450. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  5451. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  5452. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  5453. <td class="py-2.5 px-3 text-right font-sans">
  5454. ${!pr.is_default ? `
  5455. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5456. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  5457. </td>
  5458. `;
  5459. tbody.appendChild(tr);
  5460. });
  5461. }
  5462. function openAddPolicyRuleModal() {
  5463. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  5464. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  5465. document.getElementById('prule-modal-mark').value = '';
  5466. document.getElementById('prule-modal-src').value = '';
  5467. document.getElementById('prule-modal-dst').value = '';
  5468. const sel = document.getElementById('prule-modal-table');
  5469. sel.innerHTML = '';
  5470. (state.routingTables || []).forEach(t => {
  5471. const opt = document.createElement('option');
  5472. opt.value = t.name;
  5473. opt.innerText = t.name;
  5474. sel.appendChild(opt);
  5475. });
  5476. document.getElementById('prule-modal').classList.remove('hidden');
  5477. }
  5478. function closePolicyRuleModal() {
  5479. document.getElementById('prule-modal').classList.add('hidden');
  5480. }
  5481. async function submitSavePolicyRule(e) {
  5482. e.preventDefault();
  5483. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  5484. const mark = document.getElementById('prule-modal-mark').value.trim();
  5485. const src = document.getElementById('prule-modal-src').value.trim();
  5486. const dst = document.getElementById('prule-modal-dst').value.trim();
  5487. const table = document.getElementById('prule-modal-table').value;
  5488. const action = document.getElementById('prule-modal-action').value;
  5489. try {
  5490. const res = await fetch(`${API_BASE}/routing/rules`, {
  5491. method: 'POST',
  5492. headers: { 'Content-Type': 'application/json' },
  5493. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  5494. });
  5495. if (res.ok) {
  5496. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  5497. closePolicyRuleModal();
  5498. loadRoutes();
  5499. } else {
  5500. const err = await res.json();
  5501. showToast('Error', err.message, 'error');
  5502. }
  5503. } catch (err) {
  5504. showToast('Error', err.message, 'error');
  5505. }
  5506. }
  5507. async function deletePolicyRule(id) {
  5508. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  5509. try {
  5510. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5511. if (res.ok) {
  5512. showToast('Rule Removed', 'Policy rule deleted', 'success');
  5513. loadRoutes();
  5514. }
  5515. } catch (err) {
  5516. showToast('Error', err.message, 'error');
  5517. }
  5518. }
  5519. // ----------------- Routing Tables -----------------
  5520. function renderRoutingTables() {
  5521. const tbody = document.getElementById('tables-table-body');
  5522. if (!tbody) return;
  5523. tbody.innerHTML = '';
  5524. (state.routingTables || []).forEach(t => {
  5525. const tr = document.createElement('tr');
  5526. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5527. tr.innerHTML = `
  5528. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  5529. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  5530. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  5531. `;
  5532. tbody.appendChild(tr);
  5533. });
  5534. }
  5535. function openAddTableModal() {
  5536. document.getElementById('table-modal-name').value = '';
  5537. document.getElementById('table-modal-id').value = '';
  5538. document.getElementById('table-modal-comment').value = '';
  5539. document.getElementById('table-modal').classList.remove('hidden');
  5540. }
  5541. function closeTableModal() {
  5542. document.getElementById('table-modal').classList.add('hidden');
  5543. }
  5544. async function submitSaveTable(e) {
  5545. e.preventDefault();
  5546. const name = document.getElementById('table-modal-name').value.trim();
  5547. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  5548. const comment = document.getElementById('table-modal-comment').value.trim();
  5549. try {
  5550. const res = await fetch(`${API_BASE}/routing/tables`, {
  5551. method: 'POST',
  5552. headers: { 'Content-Type': 'application/json' },
  5553. body: JSON.stringify({ name, table_id: id, comment })
  5554. });
  5555. if (res.ok) {
  5556. showToast('Table Created', `Routing table ${name} registered`, 'success');
  5557. closeTableModal();
  5558. loadRoutes();
  5559. } else {
  5560. const err = await res.json();
  5561. showToast('Error', err.message, 'error');
  5562. }
  5563. } catch (err) {
  5564. showToast('Error', err.message, 'error');
  5565. }
  5566. }
  5567. async function loadDebianConfig() {
  5568. const view = document.getElementById('debian-config-view');
  5569. view.innerText = 'Generating live configuration...';
  5570. try {
  5571. const res = await fetch(`${API_BASE}/debian/config`);
  5572. const data = await res.json();
  5573. view.innerText = data.content || '# Empty config';
  5574. } catch (err) {
  5575. view.innerText = 'Failed to generate Debian network config.';
  5576. }
  5577. }
  5578. async function saveDebianConfig() {
  5579. try {
  5580. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  5581. const data = await res.json();
  5582. if (res.ok) {
  5583. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  5584. loadDebianConfig();
  5585. }
  5586. } catch (err) {
  5587. showToast('Error', err.message, 'error');
  5588. }
  5589. }
  5590. function showToast(title, message, type = 'info') {
  5591. const container = document.getElementById('toast-container');
  5592. const toast = document.createElement('div');
  5593. const borderColors = {
  5594. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  5595. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  5596. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  5597. };
  5598. 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}`;
  5599. toast.innerHTML = `
  5600. <div class="flex-1">
  5601. <div class="font-bold text-xs text-white">${title}</div>
  5602. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  5603. </div>
  5604. `;
  5605. container.appendChild(toast);
  5606. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  5607. setTimeout(() => {
  5608. toast.classList.add('opacity-0', 'translate-y-2');
  5609. setTimeout(() => toast.remove(), 300);
  5610. }, 4000);
  5611. }
  5612. function formatTraffic(bytesPerSec) {
  5613. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  5614. const kb = bytesPerSec / 1024;
  5615. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  5616. const mb = kb / 1024;
  5617. return `${mb.toFixed(2)} MB/s`;
  5618. }
  5619. function toggleSidebar() {
  5620. const sb = document.getElementById('sidebar');
  5621. sb.classList.toggle('-translate-x-full');
  5622. }
  5623. // ======================== EoIP (Ethernet over IP) ========================
  5624. async function loadEoIP(populate = true) {
  5625. try {
  5626. const res = await fetch(`${API_BASE}/vpn/eoip`);
  5627. const data = await res.json();
  5628. state.eoipTunnels = Array.isArray(data) ? data : [];
  5629. const badge = document.getElementById('eoip-count-badge');
  5630. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  5631. const sideBadge = document.getElementById('badge-eoip-count');
  5632. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  5633. renderEoIPTunnels();
  5634. } catch (err) {
  5635. console.error('Failed to load EoIP:', err);
  5636. }
  5637. }
  5638. function renderEoIPTunnels() {
  5639. const tbody = document.getElementById('eoip-table-body');
  5640. const empty = document.getElementById('eoip-empty');
  5641. if (!tbody) return;
  5642. tbody.innerHTML = '';
  5643. const tunnels = state.eoipTunnels || [];
  5644. if (tunnels.length === 0) {
  5645. empty?.classList.remove('hidden');
  5646. return;
  5647. }
  5648. empty?.classList.add('hidden');
  5649. tunnels.forEach(t => {
  5650. const tr = document.createElement('tr');
  5651. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  5652. tr.innerHTML = `
  5653. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  5654. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  5655. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  5656. <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>
  5657. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  5658. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  5659. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  5660. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  5661. <td class="py-2.5 px-3 font-mono text-[11px]">
  5662. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  5663. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  5664. </td>
  5665. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  5666. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5667. <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>
  5668. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5669. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  5670. </td>
  5671. `;
  5672. tbody.appendChild(tr);
  5673. });
  5674. }
  5675. function openAddEoIPModal() {
  5676. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  5677. document.getElementById('eoip-modal-id').value = '';
  5678. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  5679. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  5680. document.getElementById('eoip-modal-remote').value = '';
  5681. document.getElementById('eoip-modal-ip').value = '';
  5682. document.getElementById('eoip-modal-local').value = '';
  5683. document.getElementById('eoip-modal-mac').value = '';
  5684. document.getElementById('eoip-modal-mtu').value = '1500';
  5685. document.getElementById('eoip-modal-comment').value = '';
  5686. document.getElementById('eoip-modal-clampmss').checked = true;
  5687. document.getElementById('eoip-modal-disabled').checked = false;
  5688. document.getElementById('eoip-modal').classList.remove('hidden');
  5689. }
  5690. function openEditEoIPModal(id) {
  5691. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  5692. if (!t) return;
  5693. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  5694. document.getElementById('eoip-modal-id').value = t.id;
  5695. document.getElementById('eoip-modal-name').value = t.name;
  5696. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  5697. document.getElementById('eoip-modal-remote').value = t.remote_address;
  5698. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  5699. document.getElementById('eoip-modal-local').value = t.local_address || '';
  5700. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  5701. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  5702. document.getElementById('eoip-modal-comment').value = t.comment || '';
  5703. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  5704. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  5705. document.getElementById('eoip-modal').classList.remove('hidden');
  5706. }
  5707. function closeEoIPModal() {
  5708. document.getElementById('eoip-modal').classList.add('hidden');
  5709. }
  5710. async function submitSaveEoIP(e) {
  5711. e.preventDefault();
  5712. const id = document.getElementById('eoip-modal-id').value;
  5713. const name = document.getElementById('eoip-modal-name').value.trim();
  5714. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  5715. const remote = document.getElementById('eoip-modal-remote').value.trim();
  5716. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  5717. const local = document.getElementById('eoip-modal-local').value.trim();
  5718. const mac = document.getElementById('eoip-modal-mac').value.trim();
  5719. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  5720. const comment = document.getElementById('eoip-modal-comment').value.trim();
  5721. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  5722. const disabled = document.getElementById('eoip-modal-disabled').checked;
  5723. try {
  5724. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  5725. method: 'POST',
  5726. headers: { 'Content-Type': 'application/json' },
  5727. body: JSON.stringify({
  5728. id,
  5729. name,
  5730. tunnel_id: tunnelId,
  5731. remote_address: remote,
  5732. ip_address: ipAddress,
  5733. local_address: local,
  5734. mac_address: mac,
  5735. mtu,
  5736. clamp_mss: clampMss,
  5737. comment,
  5738. disabled
  5739. })
  5740. });
  5741. if (res.ok) {
  5742. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  5743. closeEoIPModal();
  5744. loadEoIP(false);
  5745. fetchData(false);
  5746. } else {
  5747. const err = await res.json();
  5748. showToast('Error', err.message, 'error');
  5749. }
  5750. } catch (err) {
  5751. showToast('Error', err.message, 'error');
  5752. }
  5753. }
  5754. async function toggleEoIPState(id, disabled) {
  5755. try {
  5756. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  5757. method: 'POST',
  5758. headers: { 'Content-Type': 'application/json' },
  5759. body: JSON.stringify({ disabled })
  5760. });
  5761. if (res.ok) {
  5762. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  5763. loadEoIP(false);
  5764. fetchData(false);
  5765. }
  5766. } catch (err) {
  5767. showToast('Error', err.message, 'error');
  5768. }
  5769. }
  5770. async function deleteEoIP(id) {
  5771. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  5772. try {
  5773. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5774. if (res.ok) {
  5775. showToast('Deleted', 'EoIP tunnel removed', 'success');
  5776. loadEoIP(false);
  5777. fetchData(false);
  5778. }
  5779. } catch (err) {
  5780. showToast('Error', err.message, 'error');
  5781. }
  5782. }
  5783. // ======================== PPP Central Hub & Servers ========================
  5784. function switchPPPSubTab(tab) {
  5785. state.pppSubTab = tab;
  5786. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  5787. tabs.forEach(t => {
  5788. const panel = document.getElementById(`ppp-subtab-${t}`);
  5789. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  5790. if (panel) {
  5791. if (t === tab) panel.classList.remove('hidden');
  5792. else panel.classList.add('hidden');
  5793. }
  5794. if (btn) {
  5795. if (t === tab) {
  5796. 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';
  5797. } else {
  5798. 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';
  5799. }
  5800. }
  5801. });
  5802. const addBtn = document.getElementById('ppp-primary-add-btn');
  5803. if (addBtn) {
  5804. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  5805. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  5806. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  5807. else addBtn.innerHTML = '<span>Save Config</span>';
  5808. }
  5809. if (tab === 'active') loadPPPSessions();
  5810. }
  5811. function openCurrentPPPModal() {
  5812. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  5813. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  5814. else if (state.pppSubTab === 'active') loadPPPSessions();
  5815. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  5816. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  5817. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  5818. }
  5819. async function loadPPP(populateDropdowns = true) {
  5820. await Promise.all([
  5821. loadPPPSecrets(),
  5822. loadPPPProfiles(),
  5823. loadPPPServers(),
  5824. loadPPPSessions()
  5825. ]);
  5826. }
  5827. async function loadPPPSecrets() {
  5828. try {
  5829. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  5830. const data = await res.json();
  5831. state.pppSecrets = Array.isArray(data) ? data : [];
  5832. const b = document.getElementById('ppp-badge-secrets');
  5833. if (b) b.innerText = state.pppSecrets.length;
  5834. const b2 = document.getElementById('secrets-count-badge');
  5835. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  5836. renderPPPSecrets();
  5837. } catch (err) {
  5838. console.error('Failed to load PPP secrets:', err);
  5839. }
  5840. }
  5841. function renderPPPSecrets() {
  5842. const tbody = document.getElementById('secrets-table-body');
  5843. const empty = document.getElementById('secrets-empty');
  5844. if (!tbody) return;
  5845. tbody.innerHTML = '';
  5846. const secrets = state.pppSecrets || [];
  5847. if (secrets.length === 0) {
  5848. empty?.classList.remove('hidden');
  5849. return;
  5850. }
  5851. empty?.classList.add('hidden');
  5852. secrets.forEach(s => {
  5853. const tr = document.createElement('tr');
  5854. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  5855. tr.innerHTML = `
  5856. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  5857. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  5858. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  5859. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  5860. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  5861. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  5862. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  5863. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5864. <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>
  5865. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5866. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  5867. </td>
  5868. `;
  5869. tbody.appendChild(tr);
  5870. });
  5871. }
  5872. async function loadPPPProfiles() {
  5873. try {
  5874. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  5875. const data = await res.json();
  5876. state.pppProfiles = Array.isArray(data) ? data : [];
  5877. const b = document.getElementById('ppp-badge-profiles');
  5878. if (b) b.innerText = state.pppProfiles.length;
  5879. const b2 = document.getElementById('profiles-count-badge');
  5880. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  5881. // Populate profile selects across modals
  5882. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  5883. selects.forEach(sid => {
  5884. const el = document.getElementById(sid);
  5885. if (!el) return;
  5886. const cur = el.value;
  5887. el.innerHTML = '';
  5888. state.pppProfiles.forEach(p => {
  5889. const opt = document.createElement('option');
  5890. opt.value = p.name;
  5891. opt.innerText = `${p.name} (${p.remote_address})`;
  5892. if (p.name === cur) opt.selected = true;
  5893. el.appendChild(opt);
  5894. });
  5895. });
  5896. renderPPPProfiles();
  5897. } catch (err) {
  5898. console.error('Failed to load PPP profiles:', err);
  5899. }
  5900. }
  5901. function renderPPPProfiles() {
  5902. const tbody = document.getElementById('profiles-table-body');
  5903. if (!tbody) return;
  5904. tbody.innerHTML = '';
  5905. (state.pppProfiles || []).forEach(p => {
  5906. const isDefault = p.name.startsWith('default');
  5907. const tr = document.createElement('tr');
  5908. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5909. tr.innerHTML = `
  5910. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  5911. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  5912. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  5913. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  5914. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  5915. <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>
  5916. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  5917. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  5918. ${!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>`}
  5919. </td>
  5920. `;
  5921. tbody.appendChild(tr);
  5922. });
  5923. }
  5924. async function loadPPPServers() {
  5925. try {
  5926. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  5927. fetch(`${API_BASE}/vpn/servers/pppoe`),
  5928. fetch(`${API_BASE}/vpn/servers/pptp`),
  5929. fetch(`${API_BASE}/vpn/servers/l2tp`),
  5930. fetch(`${API_BASE}/vpn/servers/ipsec`)
  5931. ]);
  5932. if (pppoeRes.ok) {
  5933. state.pppoeServer = await pppoeRes.json();
  5934. const s = state.pppoeServer;
  5935. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  5936. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  5937. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  5938. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  5939. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  5940. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  5941. const pill = document.getElementById('pppoe-server-status-pill');
  5942. if (pill) {
  5943. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  5944. 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';
  5945. }
  5946. setDotBadge('ppp-badge-pppoe-state', s.running);
  5947. }
  5948. if (pptpRes.ok) {
  5949. state.pptpServer = await pptpRes.json();
  5950. const s = state.pptpServer;
  5951. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  5952. document.getElementById('pptp-server-port').value = s.port || 1723;
  5953. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  5954. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  5955. const pill = document.getElementById('pptp-server-status-pill');
  5956. if (pill) {
  5957. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  5958. 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';
  5959. }
  5960. setDotBadge('ppp-badge-pptp-state', s.running);
  5961. }
  5962. if (l2tpRes.ok) {
  5963. state.l2tpServer = await l2tpRes.json();
  5964. const s = state.l2tpServer;
  5965. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  5966. document.getElementById('l2tp-server-port').value = s.port || 1701;
  5967. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  5968. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  5969. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  5970. const pill = document.getElementById('l2tp-server-status-pill');
  5971. if (pill) {
  5972. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  5973. 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';
  5974. }
  5975. setDotBadge('ppp-badge-l2tp-state', s.running);
  5976. }
  5977. if (ipsecRes.ok) {
  5978. state.ipsecServer = await ipsecRes.json();
  5979. const s = state.ipsecServer;
  5980. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  5981. if (modalEn) modalEn.checked = !!s.enabled;
  5982. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  5983. if (modalPsk) modalPsk.value = s.preshared_key || '';
  5984. const modalPool = document.getElementById('modal-ipsec-server-pool');
  5985. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  5986. const modalDns = document.getElementById('modal-ipsec-server-dns');
  5987. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  5988. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  5989. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  5990. const pill = document.getElementById('modal-ipsec-server-status');
  5991. if (pill) {
  5992. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  5993. 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';
  5994. }
  5995. }
  5996. } catch (err) {
  5997. console.error('Failed to load VPN servers:', err);
  5998. }
  5999. }
  6000. async function loadPPPSessions() {
  6001. try {
  6002. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  6003. const data = await res.json();
  6004. state.pppActiveSessions = Array.isArray(data) ? data : [];
  6005. const b = document.getElementById('ppp-badge-active');
  6006. if (b) b.innerText = state.pppActiveSessions.length;
  6007. const sideB = document.getElementById('badge-ppp-sessions');
  6008. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  6009. renderPPPSessions();
  6010. } catch (err) {
  6011. console.error('Failed to load active PPP sessions:', err);
  6012. }
  6013. }
  6014. function renderPPPSessions() {
  6015. const tbody = document.getElementById('active-ppp-table-body');
  6016. const empty = document.getElementById('active-ppp-empty');
  6017. if (!tbody) return;
  6018. tbody.innerHTML = '';
  6019. const list = state.pppActiveSessions || [];
  6020. if (list.length === 0) {
  6021. empty?.classList.remove('hidden');
  6022. return;
  6023. }
  6024. empty?.classList.add('hidden');
  6025. list.forEach(s => {
  6026. const tr = document.createElement('tr');
  6027. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6028. tr.innerHTML = `
  6029. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  6030. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  6031. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  6032. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  6033. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  6034. <td class="py-2.5 px-3 text-[11px]">
  6035. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  6036. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  6037. </td>
  6038. <td class="py-2.5 px-3 text-right font-sans">
  6039. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  6040. </td>
  6041. `;
  6042. tbody.appendChild(tr);
  6043. });
  6044. }
  6045. async function disconnectPPPSession(iface) {
  6046. if (!confirm(`Disconnect session ${iface}?`)) return;
  6047. try {
  6048. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  6049. if (res.ok) {
  6050. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  6051. loadPPPSessions();
  6052. }
  6053. } catch (err) {
  6054. showToast('Error', err.message, 'error');
  6055. }
  6056. }
  6057. // PPP Secret Modal handlers
  6058. function openAddPPPSecretModal() {
  6059. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  6060. document.getElementById('secret-modal-id').value = '';
  6061. document.getElementById('secret-modal-name').value = '';
  6062. document.getElementById('secret-modal-password').value = '';
  6063. document.getElementById('secret-modal-service').value = 'any';
  6064. document.getElementById('secret-modal-profile').value = 'default';
  6065. document.getElementById('secret-modal-local').value = '';
  6066. document.getElementById('secret-modal-remote').value = '';
  6067. document.getElementById('secret-modal-comment').value = '';
  6068. document.getElementById('secret-modal-disabled').checked = false;
  6069. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  6070. }
  6071. function openEditPPPSecretModal(id) {
  6072. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  6073. if (!s) return;
  6074. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  6075. document.getElementById('secret-modal-id').value = s.id;
  6076. document.getElementById('secret-modal-name').value = s.name;
  6077. document.getElementById('secret-modal-password').value = s.password;
  6078. document.getElementById('secret-modal-service').value = s.service || 'any';
  6079. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  6080. document.getElementById('secret-modal-local').value = s.local_address || '';
  6081. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  6082. document.getElementById('secret-modal-comment').value = s.comment || '';
  6083. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  6084. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  6085. }
  6086. function closePPPSecretModal() {
  6087. document.getElementById('ppp-secret-modal').classList.add('hidden');
  6088. }
  6089. async function submitSavePPPSecret(e) {
  6090. e.preventDefault();
  6091. const id = document.getElementById('secret-modal-id').value;
  6092. const name = document.getElementById('secret-modal-name').value.trim();
  6093. const password = document.getElementById('secret-modal-password').value.trim();
  6094. const service = document.getElementById('secret-modal-service').value;
  6095. const profile = document.getElementById('secret-modal-profile').value;
  6096. const local = document.getElementById('secret-modal-local').value.trim();
  6097. const remote = document.getElementById('secret-modal-remote').value.trim();
  6098. const comment = document.getElementById('secret-modal-comment').value.trim();
  6099. const disabled = document.getElementById('secret-modal-disabled').checked;
  6100. try {
  6101. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  6102. method: 'POST',
  6103. headers: { 'Content-Type': 'application/json' },
  6104. body: JSON.stringify({
  6105. id,
  6106. name,
  6107. password,
  6108. service,
  6109. profile,
  6110. local_address: local,
  6111. remote_address: remote,
  6112. comment,
  6113. disabled
  6114. })
  6115. });
  6116. if (res.ok) {
  6117. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  6118. closePPPSecretModal();
  6119. loadPPPSecrets();
  6120. } else {
  6121. const err = await res.json();
  6122. showToast('Error', err.message, 'error');
  6123. }
  6124. } catch (err) {
  6125. showToast('Error', err.message, 'error');
  6126. }
  6127. }
  6128. async function togglePPPSecretState(id, disabled) {
  6129. try {
  6130. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  6131. method: 'POST',
  6132. headers: { 'Content-Type': 'application/json' },
  6133. body: JSON.stringify({ disabled })
  6134. });
  6135. if (res.ok) {
  6136. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  6137. loadPPPSecrets();
  6138. }
  6139. } catch (err) {
  6140. showToast('Error', err.message, 'error');
  6141. }
  6142. }
  6143. async function deletePPPSecret(id) {
  6144. if (!confirm('Are you sure you want to delete this secret account?')) return;
  6145. try {
  6146. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6147. if (res.ok) {
  6148. showToast('Deleted', 'Secret account removed', 'success');
  6149. loadPPPSecrets();
  6150. }
  6151. } catch (err) {
  6152. showToast('Error', err.message, 'error');
  6153. }
  6154. }
  6155. // PPP Profile Modal handlers
  6156. function openAddPPPProfileModal() {
  6157. document.getElementById('profile-modal-name').value = '';
  6158. document.getElementById('profile-modal-local').value = '10.10.10.1';
  6159. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  6160. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  6161. document.getElementById('profile-modal-encryption').value = 'required';
  6162. document.getElementById('profile-modal-onlyone').checked = true;
  6163. document.getElementById('profile-modal-comment').value = '';
  6164. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  6165. }
  6166. function closePPPProfileModal() {
  6167. document.getElementById('ppp-profile-modal').classList.add('hidden');
  6168. }
  6169. async function submitSavePPPProfile(e) {
  6170. e.preventDefault();
  6171. const name = document.getElementById('profile-modal-name').value.trim();
  6172. const local = document.getElementById('profile-modal-local').value.trim();
  6173. const remote = document.getElementById('profile-modal-remote').value.trim();
  6174. const dns = document.getElementById('profile-modal-dns').value.trim();
  6175. const enc = document.getElementById('profile-modal-encryption').value;
  6176. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  6177. const comment = document.getElementById('profile-modal-comment').value.trim();
  6178. try {
  6179. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  6180. method: 'POST',
  6181. headers: { 'Content-Type': 'application/json' },
  6182. body: JSON.stringify({
  6183. id: name,
  6184. name,
  6185. local_address: local,
  6186. remote_address: remote,
  6187. dns_servers: dns,
  6188. use_encryption: enc,
  6189. only_one: onlyone,
  6190. comment
  6191. })
  6192. });
  6193. if (res.ok) {
  6194. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  6195. closePPPProfileModal();
  6196. loadPPPProfiles();
  6197. } else {
  6198. const err = await res.json();
  6199. showToast('Error', err.message, 'error');
  6200. }
  6201. } catch (err) {
  6202. showToast('Error', err.message, 'error');
  6203. }
  6204. }
  6205. async function deletePPPProfile(name) {
  6206. if (!confirm(`Delete PPP profile ${name}?`)) return;
  6207. try {
  6208. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  6209. if (res.ok) {
  6210. showToast('Deleted', 'Profile removed', 'success');
  6211. loadPPPProfiles();
  6212. } else {
  6213. const err = await res.json();
  6214. showToast('Error', err.message, 'error');
  6215. }
  6216. } catch (err) {
  6217. showToast('Error', err.message, 'error');
  6218. }
  6219. }
  6220. // Server Config submissions
  6221. async function savePPPoEServerConfig(e) {
  6222. e.preventDefault();
  6223. const enabled = document.getElementById('pppoe-server-enabled').checked;
  6224. const name = document.getElementById('pppoe-server-name').value.trim();
  6225. const iface = document.getElementById('pppoe-server-iface').value;
  6226. const profile = document.getElementById('pppoe-server-profile').value;
  6227. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  6228. const onesession = document.getElementById('pppoe-server-onesession').checked;
  6229. try {
  6230. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  6231. method: 'POST',
  6232. headers: { 'Content-Type': 'application/json' },
  6233. body: JSON.stringify({
  6234. enabled,
  6235. service_name: name,
  6236. interface: iface,
  6237. default_profile: profile,
  6238. max_mtu: mtu,
  6239. max_mru: mtu,
  6240. one_session_per_host: onesession
  6241. })
  6242. });
  6243. if (res.ok) {
  6244. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  6245. loadPPPServers();
  6246. fetchData(false);
  6247. } else {
  6248. const err = await res.json();
  6249. showToast('Error', err.message, 'error');
  6250. }
  6251. } catch (err) {
  6252. showToast('Error', err.message, 'error');
  6253. }
  6254. }
  6255. async function savePPTPServerConfig(e) {
  6256. e.preventDefault();
  6257. const enabled = document.getElementById('pptp-server-enabled').checked;
  6258. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  6259. const profile = document.getElementById('pptp-server-profile').value;
  6260. const mppe = document.getElementById('pptp-server-mppe').checked;
  6261. try {
  6262. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  6263. method: 'POST',
  6264. headers: { 'Content-Type': 'application/json' },
  6265. body: JSON.stringify({
  6266. enabled,
  6267. port,
  6268. default_profile: profile,
  6269. require_mppe: mppe
  6270. })
  6271. });
  6272. if (res.ok) {
  6273. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  6274. loadPPPServers();
  6275. fetchData(false);
  6276. } else {
  6277. const err = await res.json();
  6278. showToast('Error', err.message, 'error');
  6279. }
  6280. } catch (err) {
  6281. showToast('Error', err.message, 'error');
  6282. }
  6283. }
  6284. async function saveL2TPServerConfig(e) {
  6285. e.preventDefault();
  6286. const enabled = document.getElementById('l2tp-server-enabled').checked;
  6287. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  6288. const profile = document.getElementById('l2tp-server-profile').value;
  6289. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  6290. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  6291. try {
  6292. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  6293. method: 'POST',
  6294. headers: { 'Content-Type': 'application/json' },
  6295. body: JSON.stringify({
  6296. enabled,
  6297. port,
  6298. default_profile: profile,
  6299. use_ipsec: useipsec,
  6300. ipsec_secret: psk
  6301. })
  6302. });
  6303. if (res.ok) {
  6304. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  6305. loadPPPServers();
  6306. fetchData(false);
  6307. } else {
  6308. const err = await res.json();
  6309. showToast('Error', err.message, 'error');
  6310. }
  6311. } catch (err) {
  6312. showToast('Error', err.message, 'error');
  6313. }
  6314. }
  6315. // IPSec Server Modal
  6316. function openIPSecServerModal() {
  6317. loadPPPServers();
  6318. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  6319. }
  6320. function closeIPSecServerModal() {
  6321. document.getElementById('ipsec-server-modal').classList.add('hidden');
  6322. }
  6323. async function submitSaveIPSecServer(e) {
  6324. e.preventDefault();
  6325. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  6326. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  6327. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  6328. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  6329. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  6330. try {
  6331. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  6332. method: 'POST',
  6333. headers: { 'Content-Type': 'application/json' },
  6334. body: JSON.stringify({
  6335. enabled,
  6336. preshared_key: psk,
  6337. pool_address: pool,
  6338. dns_servers: dns,
  6339. local_subnet: subnet
  6340. })
  6341. });
  6342. if (res.ok) {
  6343. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  6344. closeIPSecServerModal();
  6345. loadPPPServers();
  6346. fetchData(false);
  6347. } else {
  6348. const err = await res.json();
  6349. showToast('Error', err.message, 'error');
  6350. }
  6351. } catch (err) {
  6352. showToast('Error', err.message, 'error');
  6353. }
  6354. }
  6355. // WireGuard Client Config Viewer
  6356. let currentWGClientConf = '';
  6357. async function openWGClientConfModal(iface, clientIP) {
  6358. try {
  6359. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  6360. method: 'POST',
  6361. headers: { 'Content-Type': 'application/json' },
  6362. body: JSON.stringify({
  6363. interface: iface,
  6364. address: clientIP || '10.10.0.2/32',
  6365. dns: '1.1.1.1, 8.8.8.8'
  6366. })
  6367. });
  6368. if (res.ok) {
  6369. const data = await res.json();
  6370. currentWGClientConf = data.config;
  6371. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  6372. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  6373. } else {
  6374. const err = await res.json();
  6375. showToast('Error', err.message, 'error');
  6376. }
  6377. } catch (err) {
  6378. showToast('Error', err.message, 'error');
  6379. }
  6380. }
  6381. function closeWGClientConfModal() {
  6382. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  6383. }
  6384. function copyWGClientConf() {
  6385. if (!currentWGClientConf) return;
  6386. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  6387. }
  6388. function downloadWGClientConf() {
  6389. if (!currentWGClientConf) return;
  6390. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  6391. const a = document.createElement('a');
  6392. a.href = URL.createObjectURL(blob);
  6393. a.download = 'wireguard-client.conf';
  6394. document.body.appendChild(a);
  6395. a.click();
  6396. document.body.removeChild(a);
  6397. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  6398. }
  6399. // =========================================================================
  6400. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  6401. // =========================================================================
  6402. state.activeDynSubTab = 'bgp-peers';
  6403. state.activeBgpSubTab = 'bgp-peers';
  6404. state.activeOspfTab = 'instances';
  6405. state.bgpInstance = null;
  6406. state.bgpPeers = [];
  6407. state.bgpNets = [];
  6408. state.bgpRoutes = [];
  6409. state.ospfInstance = null;
  6410. state.ospfInstances = [];
  6411. state.ospfAreas = [];
  6412. state.ospfAreaRanges = [];
  6413. state.ospfTemplates = [];
  6414. state.ospfLiveInterfaces = [];
  6415. state.ospfStaticNbrs = [];
  6416. state.ospfNeighbors = [];
  6417. state.ospfLSA = [];
  6418. state.ospfRoutes = [];
  6419. state.selectedOspfRow = {
  6420. instances: null,
  6421. areas: null,
  6422. 'area-ranges': null,
  6423. templates: null,
  6424. interfaces: null,
  6425. 'static-nbrs': null,
  6426. neighbors: null,
  6427. lsa: null,
  6428. };
  6429. state.ospfSort = {
  6430. instances: { col: 'name', asc: true },
  6431. areas: { col: 'name', asc: true },
  6432. ranges: { col: 'area', asc: true },
  6433. templates: { col: 'interfaces', asc: true },
  6434. live_ifaces: { col: 'interface', asc: true },
  6435. snbrs: { col: 'address', asc: true },
  6436. neighbors: { col: 'address', asc: true },
  6437. lsa: { col: 'instance', asc: true },
  6438. };
  6439. function switchBgpSubTab(subTab) {
  6440. state.activeBgpSubTab = subTab;
  6441. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  6442. tabs.forEach(t => {
  6443. const el = document.getElementById(`dyn-subtab-${t}`);
  6444. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  6445. if (el) el.classList.toggle('hidden', t !== subTab);
  6446. if (btn) {
  6447. if (t === subTab) {
  6448. 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';
  6449. } else {
  6450. 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';
  6451. }
  6452. }
  6453. });
  6454. }
  6455. function switchOspfTab(tabName) {
  6456. state.activeOspfTab = tabName;
  6457. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  6458. tabs.forEach(t => {
  6459. const pane = document.getElementById(`ospf-pane-${t}`);
  6460. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  6461. if (pane) pane.classList.toggle('hidden', t !== tabName);
  6462. if (btn) {
  6463. if (t === tabName) {
  6464. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-sky-500 text-white transition flex items-center gap-1.5 whitespace-nowrap';
  6465. } else {
  6466. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-transparent text-slate-400 hover:text-white transition flex items-center gap-1.5 whitespace-nowrap';
  6467. }
  6468. }
  6469. });
  6470. }
  6471. function switchOspfSubTab(tab) {
  6472. // Legacy alias
  6473. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  6474. else if (tab === 'ospf-areas') switchOspfTab('areas');
  6475. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  6476. else switchOspfTab('instances');
  6477. }
  6478. function switchDynSubTab(subTab) {
  6479. if (subTab.startsWith('bgp')) {
  6480. if (state.activeTab !== 'bgp') navigate('bgp');
  6481. switchBgpSubTab(subTab);
  6482. } else if (subTab.startsWith('ospf')) {
  6483. if (state.activeTab !== 'ospf') navigate('ospf');
  6484. switchOspfTab('instances');
  6485. }
  6486. }
  6487. async function loadDynamicRouting(showToastMsg = false) {
  6488. try {
  6489. const fetchSafeJson = async (url) => {
  6490. try {
  6491. const r = await fetch(url);
  6492. return r.ok ? await r.json() : null;
  6493. } catch (e) {
  6494. return null;
  6495. }
  6496. };
  6497. const [
  6498. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  6499. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  6500. selectRules, commLists, asLists
  6501. ] = await Promise.all([
  6502. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  6503. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  6504. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  6505. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  6506. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  6507. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  6508. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  6509. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  6510. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  6511. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  6512. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  6513. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  6514. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  6515. fetchSafeJson(`${API_BASE}/routing/filters`),
  6516. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  6517. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  6518. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  6519. ]);
  6520. if (sum) state.dynSummary = sum;
  6521. if (bgpInst) state.bgpInstance = bgpInst;
  6522. if (bgpPeers) state.bgpPeers = bgpPeers;
  6523. if (bgpNets) state.bgpNets = bgpNets;
  6524. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  6525. if (ospfInsts) state.ospfInstances = ospfInsts;
  6526. if (ospfAreas) state.ospfAreas = ospfAreas;
  6527. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  6528. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  6529. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  6530. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  6531. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  6532. if (ospfLsa) state.ospfLSA = ospfLsa;
  6533. if (filters) state.routingFilters = filters;
  6534. if (selectRules) state.routingSelectRules = selectRules;
  6535. if (commLists) state.routingCommunityLists = commLists;
  6536. if (asLists) state.routingASLists = asLists;
  6537. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  6538. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  6539. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  6540. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  6541. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  6542. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  6543. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  6544. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  6545. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  6546. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  6547. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  6548. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  6549. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  6550. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  6551. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  6552. } catch (err) {
  6553. console.error('Failed to load dynamic routing:', err);
  6554. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  6555. }
  6556. }
  6557. async function loadOspfAll() {
  6558. await loadDynamicRouting(true);
  6559. }
  6560. function renderBgpStatusPill() {
  6561. const pill = document.getElementById('bgp-live-status-pill');
  6562. if (!pill) return;
  6563. const inst = state.bgpInstance;
  6564. if (!inst || !inst.enabled) {
  6565. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  6566. pill.innerText = 'BGP DISABLED';
  6567. } else if (inst.running) {
  6568. 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';
  6569. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  6570. } else {
  6571. 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';
  6572. pill.innerText = 'BGP STARTING...';
  6573. }
  6574. }
  6575. function renderBgpPeers() {
  6576. const tbody = document.getElementById('bgp-peers-table-body');
  6577. if (!tbody) return;
  6578. const empty = document.getElementById('bgp-peers-empty');
  6579. const countBadge = document.getElementById('bgp-peers-count-badge');
  6580. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  6581. const peers = state.bgpPeers || [];
  6582. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  6583. if (navBadge) navBadge.innerText = peers.length;
  6584. if (peers.length === 0) {
  6585. tbody.innerHTML = '';
  6586. if (empty) empty.classList.remove('hidden');
  6587. return;
  6588. }
  6589. if (empty) empty.classList.add('hidden');
  6590. tbody.innerHTML = peers.map(p => {
  6591. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  6592. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  6593. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  6594. let stateBadge = '';
  6595. if (p.disabled) {
  6596. 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>';
  6597. } else if (p.state === 'Established') {
  6598. 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>';
  6599. } else if (p.state === 'Connect' || p.state === 'Active') {
  6600. 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>`;
  6601. } else {
  6602. 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>`;
  6603. }
  6604. return `
  6605. <tr class="hover:bg-slate-800/40 transition">
  6606. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  6607. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  6608. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  6609. <td class="py-2.5 px-3">
  6610. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  6611. ${p.local_as ? `<div class="text-[10px] text-purple-400 font-mono font-semibold" title="Custom Multi-Instance AS">Local: AS ${p.local_as}</div>` : `<div class="text-[10px] text-slate-500 font-mono">Global AS</div>`}
  6612. </td>
  6613. <td class="py-2.5 px-3">${stateBadge}</td>
  6614. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  6615. <td class="py-2.5 px-3 text-slate-300">
  6616. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  6617. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  6618. </td>
  6619. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  6620. ${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> ` : ''}
  6621. ${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>` : ''}
  6622. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  6623. </td>
  6624. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  6625. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  6626. <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'}">
  6627. ${p.disabled ? 'Enable' : 'Disable'}
  6628. </button>
  6629. <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">
  6630. Edit
  6631. </button>
  6632. <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">
  6633. Delete
  6634. </button>
  6635. </td>
  6636. </tr>
  6637. `;
  6638. }).join('');
  6639. }
  6640. function renderBgpNetworks() {
  6641. const tbody = document.getElementById('bgp-nets-table-body');
  6642. if (!tbody) return;
  6643. const empty = document.getElementById('bgp-nets-empty');
  6644. const countBadge = document.getElementById('bgp-nets-count-badge');
  6645. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  6646. const nets = state.bgpNets || [];
  6647. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  6648. if (navBadge) navBadge.innerText = nets.length;
  6649. if (nets.length === 0) {
  6650. tbody.innerHTML = '';
  6651. if (empty) empty.classList.remove('hidden');
  6652. return;
  6653. }
  6654. if (empty) empty.classList.add('hidden');
  6655. tbody.innerHTML = nets.map(n => `
  6656. <tr class="hover:bg-slate-800/40 transition">
  6657. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  6658. <td class="py-2.5 px-3">
  6659. ${n.disabled
  6660. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  6661. : '<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>'}
  6662. </td>
  6663. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  6664. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  6665. <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">
  6666. Delete
  6667. </button>
  6668. </td>
  6669. </tr>
  6670. `).join('');
  6671. }
  6672. function renderBgpRoutes() {
  6673. const tbody = document.getElementById('bgp-routes-table-body');
  6674. if (!tbody) return;
  6675. const empty = document.getElementById('bgp-routes-empty');
  6676. const countBadge = document.getElementById('bgp-routes-count-badge');
  6677. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  6678. const routes = state.bgpRoutes || [];
  6679. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  6680. if (navBadge) navBadge.innerText = routes.length;
  6681. if (routes.length === 0) {
  6682. tbody.innerHTML = '';
  6683. if (empty) empty.classList.remove('hidden');
  6684. return;
  6685. }
  6686. if (empty) empty.classList.add('hidden');
  6687. tbody.innerHTML = routes.map(r => `
  6688. <tr class="hover:bg-slate-800/40 transition">
  6689. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  6690. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  6691. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  6692. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  6693. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  6694. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  6695. </tr>
  6696. `).join('');
  6697. }
  6698. // =========================================================================
  6699. // ROUTEROS v7 OSPF TABLE RENDERING & SORTING
  6700. // =========================================================================
  6701. function sortOspfTable(tab, col) {
  6702. if (!state.ospfSort) state.ospfSort = {};
  6703. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  6704. if (state.ospfSort[tab].col === col) {
  6705. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  6706. } else {
  6707. state.ospfSort[tab].col = col;
  6708. state.ospfSort[tab].asc = true;
  6709. }
  6710. const asc = state.ospfSort[tab].asc;
  6711. let list = [];
  6712. if (tab === 'instances') list = state.ospfInstances || [];
  6713. else if (tab === 'areas') list = state.ospfAreas || [];
  6714. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  6715. else if (tab === 'templates') list = state.ospfTemplates || [];
  6716. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  6717. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  6718. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  6719. else if (tab === 'lsa') list = state.ospfLSA || [];
  6720. list.sort((a, b) => {
  6721. let valA = a[col] ?? '';
  6722. let valB = b[col] ?? '';
  6723. if (typeof valA === 'number' && typeof valB === 'number') {
  6724. return asc ? valA - valB : valB - valA;
  6725. }
  6726. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  6727. });
  6728. if (tab === 'instances') renderOspfInstances();
  6729. else if (tab === 'areas') renderOspfAreas();
  6730. else if (tab === 'ranges') renderOspfAreaRanges();
  6731. else if (tab === 'templates') renderOspfTemplates();
  6732. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  6733. else if (tab === 'snbrs') renderOspfStaticNbrs();
  6734. else if (tab === 'neighbors') renderOspfNeighbors();
  6735. else if (tab === 'lsa') renderOspfLSA();
  6736. }
  6737. function selectOspfRow(tab, id) {
  6738. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  6739. state.selectedOspfRow[tab] = id;
  6740. if (tab === 'instances') {
  6741. renderOspfInstances();
  6742. const btnEn = document.getElementById('btn-ospf-inst-enable');
  6743. const btnDis = document.getElementById('btn-ospf-inst-disable');
  6744. const btnRem = document.getElementById('btn-ospf-inst-remove');
  6745. const btnCom = document.getElementById('btn-ospf-inst-comment');
  6746. if (btnEn) btnEn.disabled = false;
  6747. if (btnDis) btnDis.disabled = false;
  6748. if (btnRem) btnRem.disabled = false;
  6749. if (btnCom) btnCom.disabled = false;
  6750. } else if (tab === 'areas') {
  6751. renderOspfAreas();
  6752. const btnEn = document.getElementById('btn-ospf-area-enable');
  6753. const btnDis = document.getElementById('btn-ospf-area-disable');
  6754. const btnRem = document.getElementById('btn-ospf-area-remove');
  6755. const btnCom = document.getElementById('btn-ospf-area-comment');
  6756. if (btnEn) btnEn.disabled = false;
  6757. if (btnDis) btnDis.disabled = false;
  6758. if (btnRem) btnRem.disabled = false;
  6759. if (btnCom) btnCom.disabled = false;
  6760. } else if (tab === 'ranges') {
  6761. renderOspfAreaRanges();
  6762. const btnEn = document.getElementById('btn-ospf-range-enable');
  6763. const btnDis = document.getElementById('btn-ospf-range-disable');
  6764. const btnRem = document.getElementById('btn-ospf-range-remove');
  6765. const btnCom = document.getElementById('btn-ospf-range-comment');
  6766. if (btnEn) btnEn.disabled = false;
  6767. if (btnDis) btnDis.disabled = false;
  6768. if (btnRem) btnRem.disabled = false;
  6769. if (btnCom) btnCom.disabled = false;
  6770. } else if (tab === 'templates') {
  6771. renderOspfTemplates();
  6772. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  6773. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  6774. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  6775. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  6776. if (btnEn) btnEn.disabled = false;
  6777. if (btnDis) btnDis.disabled = false;
  6778. if (btnRem) btnRem.disabled = false;
  6779. if (btnCom) btnCom.disabled = false;
  6780. } else if (tab === 'snbrs') {
  6781. renderOspfStaticNbrs();
  6782. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  6783. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  6784. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  6785. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  6786. if (btnEn) btnEn.disabled = false;
  6787. if (btnDis) btnDis.disabled = false;
  6788. if (btnRem) btnRem.disabled = false;
  6789. if (btnCom) btnCom.disabled = false;
  6790. }
  6791. }
  6792. // TAB 1: INSTANCES
  6793. function renderOspfInstances() {
  6794. const tbody = document.getElementById('ospf-instances-table-body');
  6795. if (!tbody) return;
  6796. const countEl = document.getElementById('ospf-instances-footer-count');
  6797. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  6798. let list = state.ospfInstances || [];
  6799. if (filter) {
  6800. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  6801. }
  6802. if (countEl) countEl.innerText = list.length;
  6803. const selId = state.selectedOspfRow?.instances;
  6804. tbody.innerHTML = list.map((inst, idx) => {
  6805. const isSel = inst.id === selId;
  6806. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  6807. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  6808. return `
  6809. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  6810. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  6811. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  6812. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  6813. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  6814. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  6815. </td>
  6816. <td class="py-1.5 px-3">${inst.version || 2}</td>
  6817. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  6818. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  6819. </tr>
  6820. `;
  6821. }).join('');
  6822. }
  6823. // TAB 2: AREAS
  6824. function renderOspfAreas() {
  6825. const tbody = document.getElementById('ospf-areas-table-body');
  6826. if (!tbody) return;
  6827. const countEl = document.getElementById('ospf-areas-footer-count');
  6828. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  6829. let list = state.ospfAreas || [];
  6830. if (filter) {
  6831. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  6832. }
  6833. if (countEl) countEl.innerText = list.length;
  6834. const selId = state.selectedOspfRow?.areas;
  6835. tbody.innerHTML = list.map((a, idx) => {
  6836. const isSel = a.id === selId;
  6837. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  6838. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  6839. return `
  6840. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  6841. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  6842. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  6843. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  6844. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  6845. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  6846. </td>
  6847. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  6848. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  6849. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  6850. </tr>
  6851. `;
  6852. }).join('');
  6853. }
  6854. // TAB 3: AREA RANGES
  6855. function renderOspfAreaRanges() {
  6856. const tbody = document.getElementById('ospf-ranges-table-body');
  6857. if (!tbody) return;
  6858. const countEl = document.getElementById('ospf-ranges-footer-count');
  6859. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  6860. let list = state.ospfAreaRanges || [];
  6861. if (filter) {
  6862. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  6863. }
  6864. if (countEl) countEl.innerText = list.length;
  6865. const selId = state.selectedOspfRow?.['area-ranges'];
  6866. tbody.innerHTML = list.map((r, idx) => {
  6867. const isSel = r.id === selId;
  6868. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  6869. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  6870. return `
  6871. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  6872. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  6873. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  6874. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  6875. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  6876. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  6877. <td class="py-1.5 px-3">${r.cost || 1}</td>
  6878. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  6879. </tr>
  6880. `;
  6881. }).join('');
  6882. }
  6883. // TAB 4: INTERFACE TEMPLATES
  6884. function renderOspfTemplates() {
  6885. const tbody = document.getElementById('ospf-templates-table-body');
  6886. if (!tbody) return;
  6887. const countEl = document.getElementById('ospf-templates-footer-count');
  6888. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  6889. let list = state.ospfTemplates || [];
  6890. if (filter) {
  6891. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  6892. }
  6893. if (countEl) countEl.innerText = list.length;
  6894. const selId = state.selectedOspfRow?.templates;
  6895. tbody.innerHTML = list.map((t, idx) => {
  6896. const isSel = t.id === selId;
  6897. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  6898. const ifaces = t.interfaces || t.interface || 'all';
  6899. const nets = t.networks || t.network || '';
  6900. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  6901. return `
  6902. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  6903. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  6904. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  6905. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  6906. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  6907. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  6908. </td>
  6909. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  6910. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  6911. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  6912. <td class="py-1.5 px-3">${t.cost || 1}</td>
  6913. <td class="py-1.5 px-3">${t.priority || 128}</td>
  6914. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  6915. </tr>
  6916. `;
  6917. }).join('');
  6918. }
  6919. // TAB 5: LIVE INTERFACES
  6920. function renderOspfLiveInterfaces() {
  6921. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  6922. if (!tbody) return;
  6923. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  6924. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  6925. let list = state.ospfLiveInterfaces || [];
  6926. if (filter) {
  6927. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  6928. }
  6929. if (countEl) countEl.innerText = list.length;
  6930. tbody.innerHTML = list.map(i => `
  6931. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  6932. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  6933. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  6934. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  6935. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  6936. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  6937. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  6938. <td class="py-1.5 px-3">${i.cost || 1}</td>
  6939. <td class="py-1.5 px-3">${i.priority || 128}</td>
  6940. </tr>
  6941. `).join('');
  6942. }
  6943. // TAB 6: STATIC NEIGHBORS
  6944. function renderOspfStaticNbrs() {
  6945. const tbody = document.getElementById('ospf-snbrs-table-body');
  6946. if (!tbody) return;
  6947. const countEl = document.getElementById('ospf-snbrs-footer-count');
  6948. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  6949. let list = state.ospfStaticNbrs || [];
  6950. if (filter) {
  6951. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  6952. }
  6953. if (countEl) countEl.innerText = list.length;
  6954. const selId = state.selectedOspfRow?.['static-nbrs'];
  6955. tbody.innerHTML = list.map((n, idx) => {
  6956. const isSel = n.id === selId;
  6957. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  6958. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  6959. return `
  6960. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  6961. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  6962. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  6963. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  6964. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  6965. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  6966. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  6967. <td class="py-1.5 px-3">${n.cost || 1}</td>
  6968. </tr>
  6969. `;
  6970. }).join('');
  6971. }
  6972. // TAB 7: LIVE NEIGHBORS
  6973. function renderOspfNeighbors() {
  6974. const tbody = document.getElementById('ospf-neighbors-table-body');
  6975. if (!tbody) return;
  6976. const countEl = document.getElementById('ospf-neighbors-footer-count');
  6977. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  6978. let list = state.ospfNeighbors || [];
  6979. if (filter) {
  6980. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  6981. }
  6982. if (countEl) countEl.innerText = list.length;
  6983. tbody.innerHTML = list.map(n => `
  6984. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  6985. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  6986. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  6987. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  6988. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  6989. </td>
  6990. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  6991. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  6992. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  6993. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  6994. </tr>
  6995. `).join('');
  6996. }
  6997. // TAB 8: LINK-STATE DATABASE (LSA)
  6998. function renderOspfLSA() {
  6999. const tbody = document.getElementById('ospf-lsa-table-body');
  7000. if (!tbody) return;
  7001. const countEl = document.getElementById('ospf-lsa-footer-count');
  7002. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  7003. let list = state.ospfLSA || [];
  7004. if (filter) {
  7005. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  7006. }
  7007. if (countEl) countEl.innerText = list.length;
  7008. tbody.innerHTML = list.map(l => `
  7009. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7010. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  7011. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7012. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  7013. </td>
  7014. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  7015. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  7016. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  7017. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  7018. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  7019. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  7020. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  7021. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  7022. </tr>
  7023. `).join('');
  7024. }
  7025. function renderOspfStatusPill() {
  7026. // Maintained for backward compatibility
  7027. const pill = document.getElementById('ospf-live-status-pill');
  7028. if (!pill) return;
  7029. 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';
  7030. pill.innerText = 'OSPF ACTIVE';
  7031. }
  7032. function renderOspfInterfaces() {
  7033. renderOspfTemplates();
  7034. }
  7035. function renderOspfRoutes() {
  7036. // Routes retained in background
  7037. }
  7038. // BGP Modals & Actions
  7039. function openBgpInstanceModal() {
  7040. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  7041. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  7042. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  7043. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  7044. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  7045. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  7046. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  7047. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  7048. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  7049. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  7050. }
  7051. function closeBgpInstanceModal() {
  7052. document.getElementById('bgp-instance-modal').classList.add('hidden');
  7053. }
  7054. async function submitBgpInstance(e) {
  7055. e.preventDefault();
  7056. const payload = {
  7057. enabled: document.getElementById('modal-bgp-enabled').checked,
  7058. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  7059. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  7060. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  7061. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  7062. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  7063. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  7064. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  7065. };
  7066. try {
  7067. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  7068. method: 'POST',
  7069. headers: { 'Content-Type': 'application/json' },
  7070. body: JSON.stringify(payload)
  7071. });
  7072. if (res.ok) {
  7073. closeBgpInstanceModal();
  7074. showToast('Success', 'BGP instance configuration updated', 'success');
  7075. loadDynamicRouting();
  7076. } else {
  7077. const err = await res.json();
  7078. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  7079. }
  7080. } catch (err) {
  7081. showToast('Error', err.message, 'error');
  7082. }
  7083. }
  7084. // ----------------- BGP Peer Connection Modal (RouterOS v7) -----------------
  7085. function switchBgpPeerModalTab(tab) {
  7086. const tabs = ['general', 'extra', 'attributes', 'filter'];
  7087. tabs.forEach(t => {
  7088. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  7089. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  7090. if (t === tab) {
  7091. if (pane) pane.classList.remove('hidden');
  7092. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  7093. } else {
  7094. if (pane) pane.classList.add('hidden');
  7095. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition';
  7096. }
  7097. });
  7098. }
  7099. function addOutputNetworkRow(val = '') {
  7100. const container = document.getElementById('modal-bgp-output-networks-container');
  7101. if (!container) return;
  7102. const row = document.createElement('div');
  7103. row.className = 'flex items-center gap-2 output-net-row';
  7104. row.innerHTML = `
  7105. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 10.2.51.0/24 or BGP-AWMN" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-cyan-500">
  7106. <button type="button" onclick="this.closest('.output-net-row').remove()" class="w-7 h-7 flex items-center justify-center bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-400 border border-slate-700 rounded-lg text-base font-bold transition" title="Remove network">-</button>
  7107. `;
  7108. container.appendChild(row);
  7109. }
  7110. function parseBgpTime(val) {
  7111. if (!val) return 0;
  7112. val = String(val).trim();
  7113. if (val.includes(':')) {
  7114. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  7115. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  7116. if (parts.length === 2) return parts[0] * 60 + parts[1];
  7117. }
  7118. return parseInt(val, 10) || 0;
  7119. }
  7120. function formatBgpTime(secs) {
  7121. if (!secs || secs <= 0) return '00:00:00';
  7122. const h = Math.floor(secs / 3600);
  7123. const m = Math.floor((secs % 3600) / 60);
  7124. const s = secs % 60;
  7125. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  7126. }
  7127. function populateBgpRoutingTables() {
  7128. const sel = document.getElementById('modal-bgp-peer-routing-table');
  7129. if (!sel) return;
  7130. const cur = sel.value || 'main';
  7131. sel.innerHTML = '<option value="main">main</option>';
  7132. (state.routingTables || []).forEach(t => {
  7133. if (t.name !== 'main') {
  7134. const opt = document.createElement('option');
  7135. opt.value = t.name;
  7136. opt.innerText = t.name;
  7137. sel.appendChild(opt);
  7138. }
  7139. });
  7140. sel.value = cur;
  7141. }
  7142. function openAddBgpPeerModal() {
  7143. document.getElementById('bgp-peer-form').reset();
  7144. document.getElementById('modal-bgp-peer-id').value = '';
  7145. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  7146. // General Tab
  7147. document.getElementById('modal-bgp-peer-enabled').checked = true;
  7148. document.getElementById('modal-bgp-peer-comment').value = '';
  7149. document.getElementById('modal-bgp-peer-name').value = '';
  7150. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  7151. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  7152. document.getElementById('modal-bgp-peer-local-as').value = '';
  7153. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  7154. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  7155. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  7156. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  7157. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  7158. document.getElementById('modal-bgp-peer-router-id').value = '';
  7159. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  7160. document.getElementById('modal-bgp-peer-remote-port').value = '';
  7161. document.getElementById('modal-bgp-peer-remote-as').value = '';
  7162. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  7163. document.getElementById('modal-bgp-peer-local-addr').value = '';
  7164. document.getElementById('modal-bgp-peer-local-port').value = '';
  7165. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  7166. document.getElementById('modal-bgp-peer-password').value = '';
  7167. document.getElementById('modal-bgp-peer-multihop').checked = false;
  7168. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  7169. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  7170. document.getElementById('modal-bgp-peer-connect').checked = true;
  7171. document.getElementById('modal-bgp-peer-listen').checked = true;
  7172. // Extra Tab
  7173. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  7174. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  7175. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  7176. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  7177. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  7178. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  7179. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  7180. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  7181. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  7182. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  7183. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  7184. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  7185. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  7186. // Attributes Tab
  7187. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  7188. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  7189. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  7190. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  7191. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  7192. document.getElementById('modal-bgp-peer-as-override').checked = false;
  7193. // Filter Tab
  7194. document.getElementById('modal-bgp-peer-in-filter').value = '';
  7195. document.getElementById('modal-bgp-peer-out-filter').value = '';
  7196. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  7197. populateBgpRoutingTables();
  7198. const container = document.getElementById('modal-bgp-output-networks-container');
  7199. if (container) {
  7200. container.innerHTML = '';
  7201. addOutputNetworkRow('');
  7202. }
  7203. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7204. if (removeBtn) removeBtn.classList.add('hidden');
  7205. switchBgpPeerModalTab('general');
  7206. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  7207. }
  7208. function openEditBgpPeerModal(id) {
  7209. const p = (state.bgpPeers || []).find(item => item.id === id);
  7210. if (!p) return;
  7211. populateBgpRoutingTables();
  7212. document.getElementById('modal-bgp-peer-id').value = p.id;
  7213. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  7214. // General Tab
  7215. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  7216. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  7217. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  7218. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  7219. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  7220. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  7221. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  7222. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  7223. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  7224. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  7225. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  7226. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  7227. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  7228. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  7229. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  7230. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  7231. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  7232. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  7233. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  7234. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  7235. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  7236. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  7237. // Extra Tab
  7238. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  7239. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  7240. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  7241. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  7242. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  7243. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  7244. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  7245. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  7246. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  7247. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  7248. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  7249. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  7250. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  7251. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  7252. // Attributes Tab
  7253. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  7254. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  7255. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  7256. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = !!p.ignore_as_path_len;
  7257. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  7258. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  7259. // Filter Tab
  7260. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  7261. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  7262. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  7263. // Output Networks
  7264. const container = document.getElementById('modal-bgp-output-networks-container');
  7265. if (container) {
  7266. container.innerHTML = '';
  7267. if (p.output_networks && p.output_networks.length > 0) {
  7268. p.output_networks.forEach(net => addOutputNetworkRow(net));
  7269. } else {
  7270. addOutputNetworkRow('');
  7271. }
  7272. }
  7273. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7274. if (removeBtn) removeBtn.classList.remove('hidden');
  7275. switchBgpPeerModalTab('general');
  7276. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  7277. }
  7278. function copyCurrentBgpPeer() {
  7279. document.getElementById('modal-bgp-peer-id').value = '';
  7280. const nameEl = document.getElementById('modal-bgp-peer-name');
  7281. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  7282. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  7283. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7284. if (removeBtn) removeBtn.classList.add('hidden');
  7285. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  7286. }
  7287. function removeCurrentBgpPeer() {
  7288. const id = document.getElementById('modal-bgp-peer-id')?.value;
  7289. if (!id) return;
  7290. deleteBgpPeer(id);
  7291. closeBgpPeerModal();
  7292. }
  7293. function closeBgpPeerModal() {
  7294. document.getElementById('bgp-peer-modal').classList.add('hidden');
  7295. }
  7296. function getBgpPeerFormData() {
  7297. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  7298. const outputNetworks = [];
  7299. netInputs.forEach(inp => {
  7300. const v = inp.value.trim();
  7301. if (v) outputNetworks.push(v);
  7302. });
  7303. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  7304. return {
  7305. id: document.getElementById('modal-bgp-peer-id').value,
  7306. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  7307. enabled: enabled,
  7308. disabled: !enabled,
  7309. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  7310. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  7311. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  7312. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  7313. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  7314. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  7315. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  7316. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  7317. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  7318. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  7319. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  7320. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  7321. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  7322. password: document.getElementById('modal-bgp-peer-password').value,
  7323. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  7324. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  7325. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  7326. connect: document.getElementById('modal-bgp-peer-connect').checked,
  7327. listen: document.getElementById('modal-bgp-peer-listen').checked,
  7328. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  7329. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  7330. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  7331. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  7332. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  7333. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  7334. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  7335. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  7336. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  7337. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  7338. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  7339. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  7340. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  7341. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  7342. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  7343. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  7344. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  7345. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  7346. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  7347. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  7348. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  7349. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  7350. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  7351. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  7352. output_networks: outputNetworks
  7353. };
  7354. }
  7355. async function submitBgpPeer(e) {
  7356. if (e) e.preventDefault();
  7357. const payload = getBgpPeerFormData();
  7358. try {
  7359. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  7360. method: 'POST',
  7361. headers: { 'Content-Type': 'application/json' },
  7362. body: JSON.stringify(payload)
  7363. });
  7364. if (res.ok) {
  7365. closeBgpPeerModal();
  7366. showToast('Success', 'BGP Connection saved', 'success');
  7367. loadDynamicRouting();
  7368. } else {
  7369. const err = await res.json();
  7370. showToast('Error', err.error || 'Failed to save peer', 'error');
  7371. }
  7372. } catch (err) {
  7373. showToast('Error', err.message, 'error');
  7374. }
  7375. }
  7376. async function applyBgpPeerModal(e) {
  7377. if (e) e.preventDefault();
  7378. const payload = getBgpPeerFormData();
  7379. try {
  7380. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  7381. method: 'POST',
  7382. headers: { 'Content-Type': 'application/json' },
  7383. body: JSON.stringify(payload)
  7384. });
  7385. if (res.ok) {
  7386. const data = await res.json();
  7387. if (data.peer && data.peer.id) {
  7388. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  7389. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  7390. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  7391. }
  7392. showToast('Applied', 'BGP Connection applied', 'success');
  7393. loadDynamicRouting();
  7394. } else {
  7395. const err = await res.json();
  7396. showToast('Error', err.error || 'Failed to apply peer', 'error');
  7397. }
  7398. } catch (err) {
  7399. showToast('Error', err.message, 'error');
  7400. }
  7401. }
  7402. async function deleteBgpPeer(id) {
  7403. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  7404. try {
  7405. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7406. if (res.ok) {
  7407. showToast('Deleted', 'BGP peer removed', 'success');
  7408. loadDynamicRouting();
  7409. }
  7410. } catch (err) {
  7411. showToast('Error', err.message, 'error');
  7412. }
  7413. }
  7414. async function toggleBgpPeerState(id, disabled) {
  7415. try {
  7416. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  7417. method: 'POST',
  7418. headers: { 'Content-Type': 'application/json' },
  7419. body: JSON.stringify({ disabled })
  7420. });
  7421. if (res.ok) {
  7422. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  7423. loadDynamicRouting();
  7424. }
  7425. } catch (err) {
  7426. showToast('Error', err.message, 'error');
  7427. }
  7428. }
  7429. function openAddBgpNetworkModal() {
  7430. document.getElementById('bgp-network-form').reset();
  7431. document.getElementById('modal-bgp-net-id').value = '';
  7432. document.getElementById('bgp-network-modal').classList.remove('hidden');
  7433. }
  7434. function closeBgpNetworkModal() {
  7435. document.getElementById('bgp-network-modal').classList.add('hidden');
  7436. }
  7437. async function submitBgpNetwork(e) {
  7438. e.preventDefault();
  7439. const payload = {
  7440. id: document.getElementById('modal-bgp-net-id').value,
  7441. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  7442. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  7443. disabled: document.getElementById('modal-bgp-net-disabled').checked
  7444. };
  7445. try {
  7446. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  7447. method: 'POST',
  7448. headers: { 'Content-Type': 'application/json' },
  7449. body: JSON.stringify(payload)
  7450. });
  7451. if (res.ok) {
  7452. closeBgpNetworkModal();
  7453. showToast('Success', 'BGP network advertisement saved', 'success');
  7454. loadDynamicRouting();
  7455. } else {
  7456. const err = await res.json();
  7457. showToast('Error', err.error || 'Failed to save network', 'error');
  7458. }
  7459. } catch (err) {
  7460. showToast('Error', err.message, 'error');
  7461. }
  7462. }
  7463. async function deleteBgpNetwork(id) {
  7464. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  7465. try {
  7466. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7467. if (res.ok) {
  7468. showToast('Deleted', 'Network advertisement removed', 'success');
  7469. loadDynamicRouting();
  7470. }
  7471. } catch (err) {
  7472. showToast('Error', err.message, 'error');
  7473. }
  7474. }
  7475. // =========================================================================
  7476. // ROUTEROS v7 OSPF MODALS & ACTIONS
  7477. // =========================================================================
  7478. // --- 1. OSPF INSTANCE ---
  7479. function openOspfInstanceModal(id = null) {
  7480. const isEdit = !!id;
  7481. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  7482. id: '',
  7483. name: 'Default',
  7484. version: 2,
  7485. vrf: 'main',
  7486. router_id: '192.168.131.56',
  7487. routing_table: 'main',
  7488. enabled: true,
  7489. redistribute_connected: false,
  7490. redistribute_static: true,
  7491. redistribute_bgp: false,
  7492. comment: ''
  7493. };
  7494. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  7495. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  7496. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  7497. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  7498. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  7499. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  7500. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  7501. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  7502. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  7503. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  7504. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  7505. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  7506. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  7507. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  7508. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  7509. }
  7510. function openEditOspfInstanceModal(id) {
  7511. openOspfInstanceModal(id);
  7512. }
  7513. function closeOspfInstanceModal() {
  7514. document.getElementById('ospf-instance-modal').classList.add('hidden');
  7515. }
  7516. async function submitOspfInstance(e) {
  7517. if (e) e.preventDefault();
  7518. const payload = {
  7519. id: document.getElementById('modal-ospf-inst-id').value,
  7520. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  7521. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  7522. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  7523. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  7524. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  7525. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  7526. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  7527. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  7528. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  7529. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  7530. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  7531. };
  7532. try {
  7533. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  7534. method: 'POST',
  7535. headers: { 'Content-Type': 'application/json' },
  7536. body: JSON.stringify(payload)
  7537. });
  7538. if (res.ok) {
  7539. closeOspfInstanceModal();
  7540. showToast('Saved', 'OSPF instance updated', 'success');
  7541. loadDynamicRouting();
  7542. } else {
  7543. const err = await res.json();
  7544. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  7545. }
  7546. } catch (err) {
  7547. showToast('Error', err.message, 'error');
  7548. }
  7549. }
  7550. function applyOspfInstanceForm() {
  7551. submitOspfInstance(null);
  7552. }
  7553. function copyOspfInstance() {
  7554. document.getElementById('modal-ospf-inst-id').value = '';
  7555. document.getElementById('modal-ospf-inst-name').value += '-copy';
  7556. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  7557. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  7558. }
  7559. async function deleteCurrentOspfInstance() {
  7560. const id = document.getElementById('modal-ospf-inst-id').value;
  7561. if (!id) return;
  7562. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  7563. try {
  7564. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7565. if (res.ok) {
  7566. closeOspfInstanceModal();
  7567. showToast('Removed', 'OSPF instance deleted', 'success');
  7568. loadDynamicRouting();
  7569. }
  7570. } catch (err) {
  7571. showToast('Error', err.message, 'error');
  7572. }
  7573. }
  7574. async function enableSelectedOspfInstance() {
  7575. const id = state.selectedOspfRow?.instances;
  7576. if (!id) return;
  7577. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  7578. method: 'POST',
  7579. headers: { 'Content-Type': 'application/json' },
  7580. body: JSON.stringify({ disabled: false })
  7581. });
  7582. loadDynamicRouting();
  7583. }
  7584. async function disableSelectedOspfInstance() {
  7585. const id = state.selectedOspfRow?.instances;
  7586. if (!id) return;
  7587. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  7588. method: 'POST',
  7589. headers: { 'Content-Type': 'application/json' },
  7590. body: JSON.stringify({ disabled: true })
  7591. });
  7592. loadDynamicRouting();
  7593. }
  7594. async function removeSelectedOspfInstance() {
  7595. const id = state.selectedOspfRow?.instances;
  7596. if (!id) return;
  7597. if (!confirm('Delete selected OSPF instance?')) return;
  7598. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7599. loadDynamicRouting();
  7600. }
  7601. async function promptCommentOspfInstance() {
  7602. const id = state.selectedOspfRow?.instances;
  7603. if (!id) return;
  7604. const inst = (state.ospfInstances || []).find(i => i.id === id);
  7605. if (!inst) return;
  7606. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  7607. if (comment === null) return;
  7608. inst.comment = comment;
  7609. await fetch(`${API_BASE}/routing/ospf/instances`, {
  7610. method: 'POST',
  7611. headers: { 'Content-Type': 'application/json' },
  7612. body: JSON.stringify(inst)
  7613. });
  7614. loadDynamicRouting();
  7615. }
  7616. // --- 2. OSPF AREA ---
  7617. function populateOspfAreaDropdowns() {
  7618. const instSelect = document.getElementById('modal-ospf-area-instance');
  7619. if (instSelect) {
  7620. const cur = instSelect.value;
  7621. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  7622. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  7623. if (cur) instSelect.value = cur;
  7624. }
  7625. }
  7626. function openOspfAreaModal(id = null) {
  7627. const isEdit = !!id;
  7628. populateOspfAreaDropdowns();
  7629. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  7630. id: '',
  7631. name: 'Default',
  7632. instance: 'Default',
  7633. area_id: '0.0.0.0',
  7634. area_type: 'default',
  7635. default_cost: 1,
  7636. no_summaries: false,
  7637. disabled: false,
  7638. comment: ''
  7639. };
  7640. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  7641. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  7642. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  7643. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  7644. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  7645. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  7646. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  7647. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  7648. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  7649. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  7650. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  7651. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  7652. document.getElementById('ospf-area-modal').classList.remove('hidden');
  7653. }
  7654. function openEditOspfAreaModal(id) {
  7655. openOspfAreaModal(id);
  7656. }
  7657. function closeOspfAreaModal() {
  7658. document.getElementById('ospf-area-modal').classList.add('hidden');
  7659. }
  7660. async function submitOspfArea(e) {
  7661. if (e) e.preventDefault();
  7662. const payload = {
  7663. id: document.getElementById('modal-ospf-area-id').value,
  7664. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  7665. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  7666. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  7667. area_type: document.getElementById('modal-ospf-area-type').value,
  7668. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  7669. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  7670. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  7671. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  7672. };
  7673. try {
  7674. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  7675. method: 'POST',
  7676. headers: { 'Content-Type': 'application/json' },
  7677. body: JSON.stringify(payload)
  7678. });
  7679. if (res.ok) {
  7680. closeOspfAreaModal();
  7681. showToast('Saved', 'OSPF area saved', 'success');
  7682. loadDynamicRouting();
  7683. } else {
  7684. const err = await res.json();
  7685. showToast('Error', err.error || 'Failed to save area', 'error');
  7686. }
  7687. } catch (err) {
  7688. showToast('Error', err.message, 'error');
  7689. }
  7690. }
  7691. function applyOspfAreaForm() {
  7692. submitOspfArea(null);
  7693. }
  7694. function copyOspfArea() {
  7695. document.getElementById('modal-ospf-area-id').value = '';
  7696. document.getElementById('modal-ospf-area-name').value += '-copy';
  7697. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  7698. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  7699. }
  7700. async function deleteCurrentOspfArea() {
  7701. const id = document.getElementById('modal-ospf-area-id').value;
  7702. if (!id) return;
  7703. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  7704. try {
  7705. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7706. if (res.ok) {
  7707. closeOspfAreaModal();
  7708. showToast('Removed', 'OSPF area deleted', 'success');
  7709. loadDynamicRouting();
  7710. }
  7711. } catch (err) {
  7712. showToast('Error', err.message, 'error');
  7713. }
  7714. }
  7715. async function enableSelectedOspfArea() {
  7716. const id = state.selectedOspfRow?.areas;
  7717. if (!id) return;
  7718. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  7719. method: 'POST',
  7720. headers: { 'Content-Type': 'application/json' },
  7721. body: JSON.stringify({ disabled: false })
  7722. });
  7723. loadDynamicRouting();
  7724. }
  7725. async function disableSelectedOspfArea() {
  7726. const id = state.selectedOspfRow?.areas;
  7727. if (!id) return;
  7728. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  7729. method: 'POST',
  7730. headers: { 'Content-Type': 'application/json' },
  7731. body: JSON.stringify({ disabled: true })
  7732. });
  7733. loadDynamicRouting();
  7734. }
  7735. async function removeSelectedOspfArea() {
  7736. const id = state.selectedOspfRow?.areas;
  7737. if (!id) return;
  7738. if (!confirm('Delete selected OSPF area?')) return;
  7739. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7740. loadDynamicRouting();
  7741. }
  7742. async function promptCommentOspfArea() {
  7743. const id = state.selectedOspfRow?.areas;
  7744. if (!id) return;
  7745. const area = (state.ospfAreas || []).find(a => a.id === id);
  7746. if (!area) return;
  7747. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  7748. if (comment === null) return;
  7749. area.comment = comment;
  7750. await fetch(`${API_BASE}/routing/ospf/areas`, {
  7751. method: 'POST',
  7752. headers: { 'Content-Type': 'application/json' },
  7753. body: JSON.stringify(area)
  7754. });
  7755. loadDynamicRouting();
  7756. }
  7757. // --- 3. OSPF AREA RANGE ---
  7758. function populateAreaRangeDropdowns() {
  7759. const select = document.getElementById('modal-ospf-range-area');
  7760. if (select) {
  7761. const cur = select.value;
  7762. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  7763. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  7764. if (cur) select.value = cur;
  7765. }
  7766. }
  7767. function openOspfAreaRangeModal(id = null) {
  7768. const isEdit = !!id;
  7769. populateAreaRangeDropdowns();
  7770. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  7771. id: '',
  7772. area: 'Default',
  7773. prefix: '',
  7774. cost: 1,
  7775. advertise: true,
  7776. disabled: false,
  7777. comment: ''
  7778. };
  7779. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  7780. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  7781. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  7782. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  7783. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  7784. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  7785. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  7786. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  7787. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  7788. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  7789. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  7790. }
  7791. function openEditOspfAreaRangeModal(id) {
  7792. openOspfAreaRangeModal(id);
  7793. }
  7794. function closeOspfAreaRangeModal() {
  7795. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  7796. }
  7797. async function submitOspfAreaRange(e) {
  7798. if (e) e.preventDefault();
  7799. const payload = {
  7800. id: document.getElementById('modal-ospf-range-id').value,
  7801. area: document.getElementById('modal-ospf-range-area').value,
  7802. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  7803. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  7804. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  7805. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  7806. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  7807. };
  7808. try {
  7809. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  7810. method: 'POST',
  7811. headers: { 'Content-Type': 'application/json' },
  7812. body: JSON.stringify(payload)
  7813. });
  7814. if (res.ok) {
  7815. closeOspfAreaRangeModal();
  7816. showToast('Saved', 'Area range saved', 'success');
  7817. loadDynamicRouting();
  7818. } else {
  7819. const err = await res.json();
  7820. showToast('Error', err.error || 'Failed to save area range', 'error');
  7821. }
  7822. } catch (err) {
  7823. showToast('Error', err.message, 'error');
  7824. }
  7825. }
  7826. function applyOspfAreaRangeForm() {
  7827. submitOspfAreaRange(null);
  7828. }
  7829. async function deleteCurrentOspfAreaRange() {
  7830. const id = document.getElementById('modal-ospf-range-id').value;
  7831. if (!id) return;
  7832. if (!confirm('Delete this area range?')) return;
  7833. try {
  7834. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7835. closeOspfAreaRangeModal();
  7836. showToast('Removed', 'Area range removed', 'success');
  7837. loadDynamicRouting();
  7838. } catch (err) {
  7839. showToast('Error', err.message, 'error');
  7840. }
  7841. }
  7842. async function enableSelectedOspfAreaRange() {
  7843. const id = state.selectedOspfRow?.['area-ranges'];
  7844. if (!id) return;
  7845. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  7846. if (!r) return;
  7847. r.disabled = false;
  7848. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  7849. loadDynamicRouting();
  7850. }
  7851. async function disableSelectedOspfAreaRange() {
  7852. const id = state.selectedOspfRow?.['area-ranges'];
  7853. if (!id) return;
  7854. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  7855. if (!r) return;
  7856. r.disabled = true;
  7857. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  7858. loadDynamicRouting();
  7859. }
  7860. async function removeSelectedOspfAreaRange() {
  7861. const id = state.selectedOspfRow?.['area-ranges'];
  7862. if (!id) return;
  7863. if (!confirm('Delete selected area range?')) return;
  7864. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7865. loadDynamicRouting();
  7866. }
  7867. async function promptCommentOspfAreaRange() {
  7868. const id = state.selectedOspfRow?.['area-ranges'];
  7869. if (!id) return;
  7870. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  7871. if (!r) return;
  7872. const comment = prompt('Enter comment for area range:', r.comment || '');
  7873. if (comment === null) return;
  7874. r.comment = comment;
  7875. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  7876. loadDynamicRouting();
  7877. }
  7878. // --- 4. OSPF INTERFACE TEMPLATE ---
  7879. function switchOspfTemplateTab(tab) {
  7880. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  7881. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  7882. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  7883. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  7884. if (tab === 'general') {
  7885. if (tabGen) tabGen.classList.remove('hidden');
  7886. if (tabAuth) tabAuth.classList.add('hidden');
  7887. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  7888. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition';
  7889. } else {
  7890. if (tabGen) tabGen.classList.add('hidden');
  7891. if (tabAuth) tabAuth.classList.remove('hidden');
  7892. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition';
  7893. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  7894. }
  7895. }
  7896. function populateTemplateAreaDropdowns() {
  7897. const select = document.getElementById('modal-ospf-tmpl-area');
  7898. if (select) {
  7899. const cur = select.value;
  7900. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  7901. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  7902. if (cur) select.value = cur;
  7903. }
  7904. }
  7905. function openOspfTemplateModal(id = null) {
  7906. const isEdit = !!id;
  7907. populateTemplateAreaDropdowns();
  7908. switchOspfTemplateTab('general');
  7909. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  7910. id: '',
  7911. interfaces: '',
  7912. area: 'Default',
  7913. networks: '',
  7914. network_type: 'broadcast',
  7915. cost: 1,
  7916. priority: 128,
  7917. passive: false,
  7918. hello_interval: 10,
  7919. dead_interval: 40,
  7920. auth: 'none',
  7921. auth_key: '',
  7922. disabled: false,
  7923. comment: ''
  7924. };
  7925. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  7926. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  7927. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  7928. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  7929. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  7930. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  7931. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  7932. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  7933. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  7934. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  7935. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  7936. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  7937. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  7938. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  7939. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  7940. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  7941. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  7942. document.getElementById('ospf-template-modal').classList.remove('hidden');
  7943. }
  7944. function openEditOspfTemplateModal(id) {
  7945. openOspfTemplateModal(id);
  7946. }
  7947. function closeOspfTemplateModal() {
  7948. document.getElementById('ospf-template-modal').classList.add('hidden');
  7949. }
  7950. async function submitOspfTemplate(e) {
  7951. if (e) e.preventDefault();
  7952. const payload = {
  7953. id: document.getElementById('modal-ospf-tmpl-id').value,
  7954. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  7955. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  7956. area: document.getElementById('modal-ospf-tmpl-area').value,
  7957. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  7958. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  7959. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  7960. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  7961. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  7962. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  7963. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  7964. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  7965. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  7966. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  7967. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  7968. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  7969. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  7970. };
  7971. try {
  7972. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  7973. method: 'POST',
  7974. headers: { 'Content-Type': 'application/json' },
  7975. body: JSON.stringify(payload)
  7976. });
  7977. if (res.ok) {
  7978. closeOspfTemplateModal();
  7979. showToast('Saved', 'Interface template saved', 'success');
  7980. loadDynamicRouting();
  7981. } else {
  7982. const err = await res.json();
  7983. showToast('Error', err.error || 'Failed to save interface template', 'error');
  7984. }
  7985. } catch (err) {
  7986. showToast('Error', err.message, 'error');
  7987. }
  7988. }
  7989. function applyOspfTemplateForm() {
  7990. submitOspfTemplate(null);
  7991. }
  7992. function copyOspfTemplate() {
  7993. document.getElementById('modal-ospf-tmpl-id').value = '';
  7994. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  7995. showToast('Copied', 'Duplicated as new template', 'info');
  7996. }
  7997. async function deleteCurrentOspfTemplate() {
  7998. const id = document.getElementById('modal-ospf-tmpl-id').value;
  7999. if (!id) return;
  8000. if (!confirm('Delete this interface template?')) return;
  8001. try {
  8002. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8003. closeOspfTemplateModal();
  8004. showToast('Removed', 'Interface template deleted', 'success');
  8005. loadDynamicRouting();
  8006. } catch (err) {
  8007. showToast('Error', err.message, 'error');
  8008. }
  8009. }
  8010. async function enableSelectedOspfTemplate() {
  8011. const id = state.selectedOspfRow?.templates;
  8012. if (!id) return;
  8013. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8014. method: 'POST',
  8015. headers: { 'Content-Type': 'application/json' },
  8016. body: JSON.stringify({ disabled: false })
  8017. });
  8018. loadDynamicRouting();
  8019. }
  8020. async function disableSelectedOspfTemplate() {
  8021. const id = state.selectedOspfRow?.templates;
  8022. if (!id) return;
  8023. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8024. method: 'POST',
  8025. headers: { 'Content-Type': 'application/json' },
  8026. body: JSON.stringify({ disabled: true })
  8027. });
  8028. loadDynamicRouting();
  8029. }
  8030. async function removeSelectedOspfTemplate() {
  8031. const id = state.selectedOspfRow?.templates;
  8032. if (!id) return;
  8033. if (!confirm('Delete selected interface template?')) return;
  8034. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8035. loadDynamicRouting();
  8036. }
  8037. async function promptCommentOspfTemplate() {
  8038. const id = state.selectedOspfRow?.templates;
  8039. if (!id) return;
  8040. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  8041. if (!tmpl) return;
  8042. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  8043. if (comment === null) return;
  8044. tmpl.comment = comment;
  8045. await fetch(`${API_BASE}/routing/ospf/templates`, {
  8046. method: 'POST',
  8047. headers: { 'Content-Type': 'application/json' },
  8048. body: JSON.stringify(tmpl)
  8049. });
  8050. loadDynamicRouting();
  8051. }
  8052. // --- 5. OSPF STATIC NEIGHBOR ---
  8053. function populateStaticNbrAreaDropdowns() {
  8054. const select = document.getElementById('modal-ospf-snbr-area');
  8055. if (select) {
  8056. const cur = select.value;
  8057. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8058. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8059. if (cur) select.value = cur;
  8060. }
  8061. }
  8062. function openOspfStaticNbrModal(id = null) {
  8063. const isEdit = !!id;
  8064. populateStaticNbrAreaDropdowns();
  8065. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  8066. id: '',
  8067. address: '',
  8068. area: 'Default',
  8069. poll_interval: 120,
  8070. cost: 1,
  8071. disabled: false,
  8072. comment: ''
  8073. };
  8074. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  8075. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  8076. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  8077. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  8078. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  8079. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  8080. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  8081. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  8082. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  8083. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8084. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  8085. }
  8086. function openEditOspfStaticNbrModal(id) {
  8087. openOspfStaticNbrModal(id);
  8088. }
  8089. function closeOspfStaticNbrModal() {
  8090. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  8091. }
  8092. async function submitOspfStaticNbr(e) {
  8093. if (e) e.preventDefault();
  8094. const payload = {
  8095. id: document.getElementById('modal-ospf-snbr-id').value,
  8096. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  8097. area: document.getElementById('modal-ospf-snbr-area').value,
  8098. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  8099. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  8100. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  8101. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  8102. };
  8103. try {
  8104. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  8105. method: 'POST',
  8106. headers: { 'Content-Type': 'application/json' },
  8107. body: JSON.stringify(payload)
  8108. });
  8109. if (res.ok) {
  8110. closeOspfStaticNbrModal();
  8111. showToast('Saved', 'Static neighbor saved', 'success');
  8112. loadDynamicRouting();
  8113. } else {
  8114. const err = await res.json();
  8115. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  8116. }
  8117. } catch (err) {
  8118. showToast('Error', err.message, 'error');
  8119. }
  8120. }
  8121. function applyOspfStaticNbrForm() {
  8122. submitOspfStaticNbr(null);
  8123. }
  8124. async function deleteCurrentOspfStaticNbr() {
  8125. const id = document.getElementById('modal-ospf-snbr-id').value;
  8126. if (!id) return;
  8127. if (!confirm('Delete this static neighbor?')) return;
  8128. try {
  8129. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8130. closeOspfStaticNbrModal();
  8131. showToast('Removed', 'Static neighbor removed', 'success');
  8132. loadDynamicRouting();
  8133. } catch (err) {
  8134. showToast('Error', err.message, 'error');
  8135. }
  8136. }
  8137. async function enableSelectedOspfStaticNbr() {
  8138. const id = state.selectedOspfRow?.['static-nbrs'];
  8139. if (!id) return;
  8140. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8141. if (!n) return;
  8142. n.disabled = false;
  8143. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8144. loadDynamicRouting();
  8145. }
  8146. async function disableSelectedOspfStaticNbr() {
  8147. const id = state.selectedOspfRow?.['static-nbrs'];
  8148. if (!id) return;
  8149. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8150. if (!n) return;
  8151. n.disabled = true;
  8152. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8153. loadDynamicRouting();
  8154. }
  8155. async function removeSelectedOspfStaticNbr() {
  8156. const id = state.selectedOspfRow?.['static-nbrs'];
  8157. if (!id) return;
  8158. if (!confirm('Delete selected static neighbor?')) return;
  8159. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8160. loadDynamicRouting();
  8161. }
  8162. async function promptCommentOspfStaticNbr() {
  8163. const id = state.selectedOspfRow?.['static-nbrs'];
  8164. if (!id) return;
  8165. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8166. if (!n) return;
  8167. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  8168. if (comment === null) return;
  8169. n.comment = comment;
  8170. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8171. loadDynamicRouting();
  8172. }
  8173. // Backward-compat aliases
  8174. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  8175. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  8176. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  8177. function submitOspfInterface(e) { submitOspfTemplate(e); }
  8178. function deleteOspfInterface(id) {
  8179. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  8180. }
  8181. function toggleOspfInterfaceState(id, disabled) {
  8182. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8183. method: 'POST',
  8184. headers: { 'Content-Type': 'application/json' },
  8185. body: JSON.stringify({ disabled })
  8186. }).then(() => loadDynamicRouting());
  8187. }
  8188. function openAddOspfAreaModal() { openOspfAreaModal(); }
  8189. function deleteOspfArea(id) {
  8190. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  8191. }
  8192. // ============================================================================
  8193. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  8194. // ============================================================================
  8195. function switchBridgeSubTab(tab) {
  8196. state.bridgeSubTab = tab;
  8197. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  8198. tabs.forEach(t => {
  8199. const panel = document.getElementById(`bridge-subtab-${t}`);
  8200. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  8201. if (panel) {
  8202. if (t === tab) panel.classList.remove('hidden');
  8203. else panel.classList.add('hidden');
  8204. }
  8205. if (btn) {
  8206. if (t === tab) {
  8207. 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';
  8208. } else {
  8209. 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';
  8210. }
  8211. }
  8212. });
  8213. const addBtn = document.getElementById('bridge-top-action-btn');
  8214. if (addBtn) {
  8215. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  8216. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  8217. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  8218. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  8219. }
  8220. if (tab === 'hosts') loadBridgeHosts();
  8221. setTimeout(initTableSorting, 50);
  8222. }
  8223. function openCurrentBridgeModal() {
  8224. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  8225. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  8226. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  8227. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  8228. }
  8229. async function loadBridge() {
  8230. try {
  8231. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  8232. fetch(`${API_BASE}/bridge/bridges`),
  8233. fetch(`${API_BASE}/bridge/ports`),
  8234. fetch(`${API_BASE}/bridge/vlans`),
  8235. fetch(`${API_BASE}/bridge/summary`),
  8236. fetch(`${API_BASE}/vpn/eoip`),
  8237. fetch(`${API_BASE}/vlans`)
  8238. ]);
  8239. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  8240. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  8241. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  8242. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  8243. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  8244. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  8245. // Badges & Stats
  8246. const bBridges = document.getElementById('bridge-badge-bridges');
  8247. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  8248. const bPorts = document.getElementById('bridge-badge-ports');
  8249. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  8250. const bVlans = document.getElementById('bridge-badge-vlans');
  8251. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  8252. const bHosts = document.getElementById('bridge-badge-hosts');
  8253. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  8254. const sBr = document.getElementById('bridge-stat-bridges');
  8255. if (sBr) sBr.innerText = (state.bridges || []).length;
  8256. const sPorts = document.getElementById('bridge-stat-ports');
  8257. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  8258. const sHosts = document.getElementById('bridge-stat-hosts');
  8259. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  8260. renderBridges();
  8261. renderBridgePorts();
  8262. renderBridgeVLANs();
  8263. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  8264. } catch (err) {
  8265. console.error('Failed to load bridge subsystem:', err);
  8266. }
  8267. }
  8268. // ----------------- Bridges -----------------
  8269. function renderBridges() {
  8270. const tbody = document.getElementById('bridge-table-body');
  8271. const empty = document.getElementById('bridge-empty-bridges');
  8272. const countBadge = document.getElementById('bridge-count-badge');
  8273. if (!tbody) return;
  8274. tbody.innerHTML = '';
  8275. const bridges = state.bridges || [];
  8276. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  8277. if (bridges.length === 0) {
  8278. empty?.classList.remove('hidden');
  8279. return;
  8280. }
  8281. empty?.classList.add('hidden');
  8282. bridges.forEach((b, idx) => {
  8283. const tr = document.createElement('tr');
  8284. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  8285. // Format IP addresses pill list
  8286. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  8287. if (b.ip_addresses && b.ip_addresses.length > 0) {
  8288. ipsHtml = b.ip_addresses.map(ip => `
  8289. <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">
  8290. <span>${ip}</span>
  8291. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  8292. </span>
  8293. `).join(' ');
  8294. }
  8295. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  8296. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  8297. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  8298. tr.innerHTML = `
  8299. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  8300. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  8301. <td class="py-2.5 px-3 font-bold text-white text-sm">
  8302. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  8303. </td>
  8304. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  8305. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  8306. <td class="py-2.5 px-3">
  8307. <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>
  8308. </td>
  8309. <td class="py-2.5 px-3 text-center">
  8310. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  8311. </td>
  8312. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  8313. <td class="py-2.5 px-3">
  8314. <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>
  8315. </td>
  8316. <td class="py-2.5 px-3">
  8317. <div class="flex items-center gap-1.5 flex-wrap">
  8318. ${ipsHtml}
  8319. <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>
  8320. </div>
  8321. </td>
  8322. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  8323. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  8324. </td>
  8325. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  8326. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8327. <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>
  8328. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8329. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  8330. </td>
  8331. `;
  8332. tbody.appendChild(tr);
  8333. });
  8334. }
  8335. function openAddBridgeModal() {
  8336. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  8337. document.getElementById('bridge-modal-id').value = '';
  8338. document.getElementById('bridge-modal-name').value = 'bridge1';
  8339. document.getElementById('bridge-modal-name').disabled = false;
  8340. document.getElementById('bridge-modal-mtu').value = '1500';
  8341. document.getElementById('bridge-modal-mac').value = '';
  8342. document.getElementById('bridge-modal-stp').value = 'rstp';
  8343. document.getElementById('bridge-modal-priority').value = '32768';
  8344. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  8345. document.getElementById('bridge-modal-pvid').value = '1';
  8346. document.getElementById('bridge-modal-fastforward').checked = true;
  8347. document.getElementById('bridge-modal-comment').value = '';
  8348. document.getElementById('bridge-modal-disabled').checked = false;
  8349. toggleBridgeModalVlanFiltering();
  8350. document.getElementById('bridge-modal').classList.remove('hidden');
  8351. }
  8352. function openEditBridgeModal(id) {
  8353. const b = (state.bridges || []).find(x => x.id === id);
  8354. if (!b) return;
  8355. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  8356. document.getElementById('bridge-modal-id').value = b.id;
  8357. document.getElementById('bridge-modal-name').value = b.name;
  8358. document.getElementById('bridge-modal-name').disabled = true;
  8359. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  8360. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  8361. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  8362. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  8363. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  8364. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  8365. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  8366. document.getElementById('bridge-modal-comment').value = b.comment || '';
  8367. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  8368. toggleBridgeModalVlanFiltering();
  8369. document.getElementById('bridge-modal').classList.remove('hidden');
  8370. }
  8371. function closeBridgeModal() {
  8372. document.getElementById('bridge-modal').classList.add('hidden');
  8373. }
  8374. function toggleBridgeModalVlanFiltering() {
  8375. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  8376. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  8377. if (pvidBox) {
  8378. if (chk) pvidBox.classList.remove('opacity-40');
  8379. else pvidBox.classList.add('opacity-40');
  8380. }
  8381. }
  8382. async function submitSaveBridge(e) {
  8383. e.preventDefault();
  8384. const id = document.getElementById('bridge-modal-id').value;
  8385. const name = document.getElementById('bridge-modal-name').value.trim();
  8386. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  8387. const mac = document.getElementById('bridge-modal-mac').value.trim();
  8388. const stp = document.getElementById('bridge-modal-stp').value;
  8389. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  8390. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  8391. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  8392. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  8393. const comment = document.getElementById('bridge-modal-comment').value.trim();
  8394. const disabled = document.getElementById('bridge-modal-disabled').checked;
  8395. try {
  8396. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  8397. method: 'POST',
  8398. headers: { 'Content-Type': 'application/json' },
  8399. body: JSON.stringify({
  8400. id,
  8401. name,
  8402. mtu,
  8403. mac_address: mac,
  8404. stp,
  8405. priority,
  8406. vlan_filtering: vlanFiltering,
  8407. pvid,
  8408. fast_forward: fastForward,
  8409. comment,
  8410. disabled
  8411. })
  8412. });
  8413. if (res.ok) {
  8414. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  8415. closeBridgeModal();
  8416. loadBridge();
  8417. fetchData(false);
  8418. } else {
  8419. const err = await res.json();
  8420. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  8421. }
  8422. } catch (err) {
  8423. showToast('Error', err.message, 'error');
  8424. }
  8425. }
  8426. async function toggleBridgeState(id, disabled) {
  8427. try {
  8428. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  8429. method: 'POST',
  8430. headers: { 'Content-Type': 'application/json' },
  8431. body: JSON.stringify({ disabled })
  8432. });
  8433. if (res.ok) {
  8434. loadBridge();
  8435. fetchData(false);
  8436. }
  8437. } catch (err) {
  8438. showToast('Error', err.message, 'error');
  8439. }
  8440. }
  8441. async function deleteBridge(id) {
  8442. const b = (state.bridges || []).find(x => x.id === id);
  8443. const name = b ? b.name : id;
  8444. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  8445. try {
  8446. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8447. if (res.ok) {
  8448. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  8449. loadBridge();
  8450. fetchData(false);
  8451. } else {
  8452. const err = await res.json();
  8453. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  8454. }
  8455. } catch (err) {
  8456. showToast('Error', err.message, 'error');
  8457. }
  8458. }
  8459. // ----------------- Bridge IP Assignments -----------------
  8460. function openAddBridgeIPModal(id, name) {
  8461. document.getElementById('bridge-ip-modal-id').value = id;
  8462. document.getElementById('bridge-ip-modal-sub').innerText = name;
  8463. document.getElementById('bridge-ip-modal-cidr').value = '';
  8464. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  8465. }
  8466. function closeBridgeIPModal() {
  8467. document.getElementById('bridge-ip-modal').classList.add('hidden');
  8468. }
  8469. async function submitAddBridgeIP(e) {
  8470. e.preventDefault();
  8471. const id = document.getElementById('bridge-ip-modal-id').value;
  8472. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  8473. try {
  8474. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  8475. method: 'POST',
  8476. headers: { 'Content-Type': 'application/json' },
  8477. body: JSON.stringify({ ip })
  8478. });
  8479. if (res.ok) {
  8480. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  8481. closeBridgeIPModal();
  8482. loadBridge();
  8483. fetchData(false);
  8484. } else {
  8485. const err = await res.json();
  8486. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  8487. }
  8488. } catch (err) {
  8489. showToast('Error', err.message, 'error');
  8490. }
  8491. }
  8492. async function deleteBridgeIP(id, ip) {
  8493. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  8494. try {
  8495. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  8496. method: 'DELETE',
  8497. headers: { 'Content-Type': 'application/json' },
  8498. body: JSON.stringify({ ip })
  8499. });
  8500. if (res.ok) {
  8501. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  8502. loadBridge();
  8503. fetchData(false);
  8504. }
  8505. } catch (err) {
  8506. showToast('Error', err.message, 'error');
  8507. }
  8508. }
  8509. // ----------------- Bridge Ports -----------------
  8510. function renderBridgePorts() {
  8511. const tbody = document.getElementById('bridge-ports-table-body');
  8512. const empty = document.getElementById('bridge-empty-ports');
  8513. const countBadge = document.getElementById('bridge-ports-count-badge');
  8514. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  8515. if (!tbody) return;
  8516. tbody.innerHTML = '';
  8517. // Update filter select
  8518. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  8519. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  8520. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  8521. if (ports.length === 0) {
  8522. empty?.classList.remove('hidden');
  8523. return;
  8524. }
  8525. empty?.classList.add('hidden');
  8526. ports.forEach((p, idx) => {
  8527. const tr = document.createElement('tr');
  8528. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  8529. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  8530. tr.innerHTML = `
  8531. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  8532. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  8533. <td class="py-2.5 px-3 font-bold text-white text-sm">
  8534. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  8535. </td>
  8536. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  8537. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  8538. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  8539. <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>
  8540. <td class="py-2.5 px-3">
  8541. ${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>'}
  8542. </td>
  8543. <td class="py-2.5 px-3">
  8544. <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>
  8545. </td>
  8546. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  8547. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8548. <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>
  8549. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8550. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  8551. </td>
  8552. `;
  8553. tbody.appendChild(tr);
  8554. });
  8555. }
  8556. function openAddBridgePortModal() {
  8557. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  8558. document.getElementById('bridge-port-modal-id').value = '';
  8559. populateBridgeSelect('bridge-port-modal-bridge');
  8560. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  8561. document.getElementById('bridge-port-modal-pvid').value = '1';
  8562. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  8563. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  8564. document.getElementById('bridge-port-modal-horizon').value = '0';
  8565. document.getElementById('bridge-port-modal-pathcost').value = '10';
  8566. document.getElementById('bridge-port-modal-priority').value = '128';
  8567. document.getElementById('bridge-port-modal-learn').checked = true;
  8568. document.getElementById('bridge-port-modal-comment').value = '';
  8569. document.getElementById('bridge-port-modal-disabled').checked = false;
  8570. document.getElementById('bridge-port-modal').classList.remove('hidden');
  8571. }
  8572. function openEditBridgePortModal(id) {
  8573. const p = (state.bridgePorts || []).find(x => x.id === id);
  8574. if (!p) return;
  8575. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  8576. document.getElementById('bridge-port-modal-id').value = p.id;
  8577. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  8578. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  8579. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  8580. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  8581. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  8582. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  8583. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  8584. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  8585. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  8586. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  8587. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  8588. document.getElementById('bridge-port-modal').classList.remove('hidden');
  8589. }
  8590. function closeBridgePortModal() {
  8591. document.getElementById('bridge-port-modal').classList.add('hidden');
  8592. }
  8593. async function submitSaveBridgePort(e) {
  8594. e.preventDefault();
  8595. const id = document.getElementById('bridge-port-modal-id').value;
  8596. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  8597. const iface = document.getElementById('bridge-port-modal-interface').value;
  8598. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  8599. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  8600. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  8601. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  8602. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  8603. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  8604. const learn = document.getElementById('bridge-port-modal-learn').checked;
  8605. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  8606. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  8607. try {
  8608. const res = await fetch(`${API_BASE}/bridge/ports`, {
  8609. method: 'POST',
  8610. headers: { 'Content-Type': 'application/json' },
  8611. body: JSON.stringify({
  8612. id,
  8613. bridge,
  8614. interface: iface,
  8615. pvid,
  8616. frame_types: frameTypes,
  8617. ingress_filtering: ingressFiltering,
  8618. horizon,
  8619. path_cost: pathCost,
  8620. priority,
  8621. learn,
  8622. comment,
  8623. disabled
  8624. })
  8625. });
  8626. if (res.ok) {
  8627. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  8628. closeBridgePortModal();
  8629. loadBridge();
  8630. fetchData(false);
  8631. } else {
  8632. const err = await res.json();
  8633. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  8634. }
  8635. } catch (err) {
  8636. showToast('Error', err.message, 'error');
  8637. }
  8638. }
  8639. async function toggleBridgePortState(id, disabled) {
  8640. try {
  8641. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  8642. method: 'POST',
  8643. headers: { 'Content-Type': 'application/json' },
  8644. body: JSON.stringify({ disabled })
  8645. });
  8646. if (res.ok) {
  8647. loadBridge();
  8648. fetchData(false);
  8649. }
  8650. } catch (err) {
  8651. showToast('Error', err.message, 'error');
  8652. }
  8653. }
  8654. async function deleteBridgePort(id) {
  8655. const p = (state.bridgePorts || []).find(x => x.id === id);
  8656. const iface = p ? p.interface : id;
  8657. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  8658. try {
  8659. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8660. if (res.ok) {
  8661. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  8662. loadBridge();
  8663. fetchData(false);
  8664. }
  8665. } catch (err) {
  8666. showToast('Error', err.message, 'error');
  8667. }
  8668. }
  8669. // ----------------- Bridge VLANs -----------------
  8670. function renderBridgeVLANs() {
  8671. const tbody = document.getElementById('bridge-vlans-table-body');
  8672. const empty = document.getElementById('bridge-empty-vlans');
  8673. const countBadge = document.getElementById('bridge-vlans-count-badge');
  8674. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  8675. if (!tbody) return;
  8676. tbody.innerHTML = '';
  8677. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  8678. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  8679. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  8680. if (vlans.length === 0) {
  8681. empty?.classList.remove('hidden');
  8682. return;
  8683. }
  8684. empty?.classList.add('hidden');
  8685. vlans.forEach((v, idx) => {
  8686. const tr = document.createElement('tr');
  8687. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  8688. const taggedHtml = (v.tagged && v.tagged.length > 0)
  8689. ? 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(' ')
  8690. : '<span class="text-slate-600">none</span>';
  8691. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  8692. ? 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(' ')
  8693. : '<span class="text-slate-600">none</span>';
  8694. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  8695. tr.innerHTML = `
  8696. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  8697. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  8698. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  8699. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  8700. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  8701. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  8702. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  8703. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8704. <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>
  8705. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8706. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  8707. </td>
  8708. `;
  8709. tbody.appendChild(tr);
  8710. });
  8711. }
  8712. function openAddBridgeVLANModal() {
  8713. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  8714. document.getElementById('bridge-vlan-modal-id').value = '';
  8715. populateBridgeSelect('bridge-vlan-modal-bridge');
  8716. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  8717. document.getElementById('bridge-vlan-modal-comment').value = '';
  8718. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  8719. updateBridgeVlanPortCheckboxes();
  8720. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  8721. }
  8722. function openEditBridgeVLANModal(id) {
  8723. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  8724. if (!v) return;
  8725. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  8726. document.getElementById('bridge-vlan-modal-id').value = v.id;
  8727. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  8728. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  8729. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  8730. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  8731. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  8732. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  8733. }
  8734. function closeBridgeVlanModal() {
  8735. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  8736. }
  8737. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  8738. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  8739. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  8740. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  8741. if (!taggedBox || !untaggedBox) return;
  8742. // Ports belonging to the selected bridge
  8743. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  8744. if (memberPorts.length === 0) {
  8745. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  8746. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  8747. return;
  8748. }
  8749. taggedBox.innerHTML = memberPorts.map(p => `
  8750. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  8751. <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">
  8752. <span>${p.interface}</span>
  8753. </label>
  8754. `).join('');
  8755. untaggedBox.innerHTML = memberPorts.map(p => `
  8756. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  8757. <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">
  8758. <span>${p.interface}</span>
  8759. </label>
  8760. `).join('');
  8761. }
  8762. async function submitSaveBridgeVLAN(e) {
  8763. e.preventDefault();
  8764. const id = document.getElementById('bridge-vlan-modal-id').value;
  8765. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  8766. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  8767. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  8768. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  8769. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  8770. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  8771. try {
  8772. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  8773. method: 'POST',
  8774. headers: { 'Content-Type': 'application/json' },
  8775. body: JSON.stringify({
  8776. id,
  8777. bridge,
  8778. vlan_ids: vlanIDs,
  8779. tagged,
  8780. untagged,
  8781. comment,
  8782. disabled
  8783. })
  8784. });
  8785. if (res.ok) {
  8786. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  8787. closeBridgeVlanModal();
  8788. loadBridge();
  8789. } else {
  8790. const err = await res.json();
  8791. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  8792. }
  8793. } catch (err) {
  8794. showToast('Error', err.message, 'error');
  8795. }
  8796. }
  8797. async function toggleBridgeVLANState(id, disabled) {
  8798. try {
  8799. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  8800. method: 'POST',
  8801. headers: { 'Content-Type': 'application/json' },
  8802. body: JSON.stringify({ disabled })
  8803. });
  8804. if (res.ok) loadBridge();
  8805. } catch (err) {
  8806. showToast('Error', err.message, 'error');
  8807. }
  8808. }
  8809. async function deleteBridgeVLAN(id) {
  8810. if (!confirm('Delete this bridge VLAN entry?')) return;
  8811. try {
  8812. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8813. if (res.ok) {
  8814. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  8815. loadBridge();
  8816. }
  8817. } catch (err) {
  8818. showToast('Error', err.message, 'error');
  8819. }
  8820. }
  8821. // ----------------- Hosts / MAC Table -----------------
  8822. async function loadBridgeHosts() {
  8823. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  8824. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  8825. try {
  8826. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  8827. const res = await fetch(url);
  8828. if (res.ok) {
  8829. state.bridgeHosts = await res.json();
  8830. renderBridgeHosts();
  8831. }
  8832. } catch (err) {
  8833. console.error('Failed to load bridge hosts:', err);
  8834. }
  8835. }
  8836. function renderBridgeHosts() {
  8837. const tbody = document.getElementById('bridge-hosts-table-body');
  8838. const empty = document.getElementById('bridge-empty-hosts');
  8839. const countBadge = document.getElementById('bridge-hosts-count-badge');
  8840. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  8841. if (!tbody) return;
  8842. tbody.innerHTML = '';
  8843. const hosts = (state.bridgeHosts || []).filter(h => {
  8844. if (!search) return true;
  8845. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  8846. });
  8847. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  8848. if (hosts.length === 0) {
  8849. empty?.classList.remove('hidden');
  8850. return;
  8851. }
  8852. empty?.classList.add('hidden');
  8853. hosts.forEach(h => {
  8854. const tr = document.createElement('tr');
  8855. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  8856. let flagBadges = '';
  8857. 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>';
  8858. 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>';
  8859. 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>';
  8860. tr.innerHTML = `
  8861. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  8862. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  8863. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  8864. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  8865. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  8866. <td class="py-2.5 px-3">${flagBadges}</td>
  8867. `;
  8868. tbody.appendChild(tr);
  8869. });
  8870. }
  8871. async function flushBridgeHosts() {
  8872. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  8873. if (!selBridge) {
  8874. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  8875. return;
  8876. }
  8877. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  8878. try {
  8879. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  8880. method: 'POST',
  8881. headers: { 'Content-Type': 'application/json' },
  8882. body: JSON.stringify({ bridge: selBridge })
  8883. });
  8884. if (res.ok) {
  8885. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  8886. loadBridgeHosts();
  8887. }
  8888. } catch (err) {
  8889. showToast('Error', err.message, 'error');
  8890. }
  8891. }
  8892. // ----------------- Helpers -----------------
  8893. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  8894. const sel = document.getElementById(selectId);
  8895. if (!sel) return;
  8896. const prevVal = currentVal || sel.value;
  8897. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  8898. (state.bridges || []).forEach(b => {
  8899. const opt = document.createElement('option');
  8900. opt.value = b.name;
  8901. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  8902. if (b.name === prevVal) opt.selected = true;
  8903. sel.appendChild(opt);
  8904. });
  8905. }
  8906. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  8907. const sel = document.getElementById(selectId);
  8908. if (!sel) return;
  8909. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  8910. // 1. Physical Interfaces
  8911. const grpPhys = document.createElement('optgroup');
  8912. grpPhys.label = 'Physical Interfaces';
  8913. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  8914. const opt = document.createElement('option');
  8915. opt.value = i.name;
  8916. opt.innerText = `${i.name} (${i.role || i.type})`;
  8917. if (i.name === currentVal) opt.selected = true;
  8918. grpPhys.appendChild(opt);
  8919. });
  8920. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  8921. // 2. VLAN Sub-interfaces
  8922. const grpVlans = document.createElement('optgroup');
  8923. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  8924. (state.vlans || []).forEach(v => {
  8925. const opt = document.createElement('option');
  8926. opt.value = v.name;
  8927. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  8928. if (v.name === currentVal) opt.selected = true;
  8929. grpVlans.appendChild(opt);
  8930. });
  8931. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  8932. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  8933. const grpEoip = document.createElement('optgroup');
  8934. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  8935. (state.eoipTunnels || []).forEach(t => {
  8936. const opt = document.createElement('option');
  8937. opt.value = t.name;
  8938. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  8939. if (t.name === currentVal) opt.selected = true;
  8940. grpEoip.appendChild(opt);
  8941. });
  8942. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  8943. }
  8944. // -------------------------------------------------------------
  8945. // RouterOS v7 Routing Filters Management (/routing filter)
  8946. // -------------------------------------------------------------
  8947. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  8948. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  8949. if (!state.rfSort) state.rfSort = {};
  8950. function switchRoutingFilterTab(tab) {
  8951. state.activeRoutingFilterTab = tab;
  8952. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  8953. tabs.forEach(t => {
  8954. const btn = document.getElementById(`tab-rf-${t}`);
  8955. const content = document.getElementById(`tab-content-rf-${t}`);
  8956. if (btn) {
  8957. if (t === tab) {
  8958. btn.className = 'px-3 py-1 text-xs font-semibold rounded bg-emerald-600/20 text-emerald-300 border border-emerald-500/30 transition shadow-sm';
  8959. } else {
  8960. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  8961. }
  8962. }
  8963. if (content) {
  8964. if (t === tab) content.classList.remove('hidden');
  8965. else content.classList.add('hidden');
  8966. }
  8967. });
  8968. const chainContainer = document.getElementById('rf-chain-filter-container');
  8969. if (chainContainer) {
  8970. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  8971. else chainContainer.classList.add('hidden');
  8972. }
  8973. renderRoutingFilters();
  8974. }
  8975. function selectFilterRow(tab, id) {
  8976. if (state.selectedFilterRow[tab] === id) {
  8977. delete state.selectedFilterRow[tab];
  8978. } else {
  8979. state.selectedFilterRow[tab] = id;
  8980. }
  8981. if (tab === 'rules') renderRoutingFilterRules();
  8982. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  8983. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  8984. else if (tab === 'as-lists') renderRoutingFilterASLists();
  8985. }
  8986. function openRoutingFilterNewModal() {
  8987. const tab = state.activeRoutingFilterTab || 'rules';
  8988. if (tab === 'rules') openAddRoutingFilterModal();
  8989. else if (tab === 'select-rules') openAddSelectRuleModal();
  8990. else if (tab === 'community-lists') openAddCommunityListModal();
  8991. else if (tab === 'as-lists') openAddASListModal();
  8992. }
  8993. function toggleSelectedRoutingFilter(disabled) {
  8994. const tab = state.activeRoutingFilterTab || 'rules';
  8995. const id = state.selectedFilterRow[tab];
  8996. if (!id) {
  8997. showToast('Select Row', 'Please click on a row to select it first', 'info');
  8998. return;
  8999. }
  9000. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  9001. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  9002. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  9003. else if (tab === 'as-lists') toggleASListState(id, disabled);
  9004. }
  9005. function removeSelectedRoutingFilter() {
  9006. const tab = state.activeRoutingFilterTab || 'rules';
  9007. const id = state.selectedFilterRow[tab];
  9008. if (!id) {
  9009. showToast('Select Row', 'Please click on a row to select it first', 'info');
  9010. return;
  9011. }
  9012. if (tab === 'rules') deleteRoutingFilter(id);
  9013. else if (tab === 'select-rules') deleteSelectRule(id);
  9014. else if (tab === 'community-lists') deleteCommunityList(id);
  9015. else if (tab === 'as-lists') deleteASList(id);
  9016. }
  9017. function searchRoutingFilters(q) {
  9018. state.rfSearchQuery = (q || '').trim().toLowerCase();
  9019. renderRoutingFilters();
  9020. }
  9021. function sortFilterTable(tab, col) {
  9022. if (!state.rfSort) state.rfSort = {};
  9023. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  9024. if (state.rfSort[tab].col === col) {
  9025. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  9026. } else {
  9027. state.rfSort[tab].col = col;
  9028. state.rfSort[tab].asc = true;
  9029. }
  9030. const asc = state.rfSort[tab].asc;
  9031. let list = [];
  9032. if (tab === 'rules') list = state.routingFilters || [];
  9033. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  9034. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  9035. else if (tab === 'as-lists') list = state.routingASLists || [];
  9036. list.sort((a, b) => {
  9037. let valA = a[col] ?? '';
  9038. let valB = b[col] ?? '';
  9039. if (col === 'flags') {
  9040. valA = a.disabled ? 'X' : 'A';
  9041. valB = b.disabled ? 'X' : 'A';
  9042. }
  9043. if (typeof valA === 'number' && typeof valB === 'number') {
  9044. return asc ? valA - valB : valB - valA;
  9045. }
  9046. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  9047. });
  9048. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  9049. allCols.forEach(c => {
  9050. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  9051. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  9052. });
  9053. if (tab === 'rules') renderRoutingFilterRules();
  9054. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  9055. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  9056. else if (tab === 'as-lists') renderRoutingFilterASLists();
  9057. }
  9058. function renderRoutingFilters() {
  9059. const navBadge = document.getElementById('badge-filters-count');
  9060. const allRules = state.routingFilters || [];
  9061. if (navBadge) navBadge.innerText = allRules.length;
  9062. // Populate chain filter select options and datalist
  9063. const chainSelect = document.getElementById('routing-filter-chain-select');
  9064. const chainDatalist = document.getElementById('dl-routing-chains');
  9065. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  9066. if (chainSelect) {
  9067. const currentVal = state.filterChainSelected || 'all';
  9068. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  9069. uniqueChains.map(ch => {
  9070. const count = allRules.filter(r => r.chain === ch).length;
  9071. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  9072. }).join('');
  9073. chainSelect.value = currentVal;
  9074. }
  9075. if (chainDatalist) {
  9076. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  9077. }
  9078. renderRoutingFilterRules();
  9079. renderRoutingFilterSelectRules();
  9080. renderRoutingFilterCommunityLists();
  9081. renderRoutingFilterASLists();
  9082. }
  9083. function filterRoutingFiltersByChain(chain) {
  9084. state.filterChainSelected = chain;
  9085. renderRoutingFilters();
  9086. }
  9087. // -------------------------------------------------------------
  9088. // TAB 1: RULES (/routing filter rule)
  9089. // -------------------------------------------------------------
  9090. function renderRoutingFilterRules() {
  9091. const tbody = document.getElementById('routing-filter-rules-tbody');
  9092. if (!tbody) return;
  9093. const empty = document.getElementById('rf-rules-empty');
  9094. const statusCount = document.getElementById('rf-status-count');
  9095. let list = (state.routingFilters || []).slice();
  9096. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  9097. list = list.filter(r => r.chain === state.filterChainSelected);
  9098. }
  9099. const q = state.rfSearchQuery;
  9100. if (q) {
  9101. list = list.filter(r =>
  9102. (r.chain && r.chain.toLowerCase().includes(q)) ||
  9103. (r.rule && r.rule.toLowerCase().includes(q)) ||
  9104. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  9105. (r.comment && r.comment.toLowerCase().includes(q))
  9106. );
  9107. }
  9108. if (!state.rfSort?.['rules']) {
  9109. list.sort((a, b) => {
  9110. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  9111. return (a.rule_order || 0) - (b.rule_order || 0);
  9112. });
  9113. }
  9114. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  9115. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9116. }
  9117. if (list.length === 0) {
  9118. tbody.innerHTML = '';
  9119. if (empty) empty.classList.remove('hidden');
  9120. return;
  9121. }
  9122. if (empty) empty.classList.add('hidden');
  9123. tbody.innerHTML = list.map(r => {
  9124. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  9125. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  9126. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9127. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  9128. let ruleDisplay = '';
  9129. if (r.rule && r.rule.trim() !== '') {
  9130. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  9131. } else {
  9132. let conds = [];
  9133. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  9134. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  9135. let act = r.action || 'accept';
  9136. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  9137. }
  9138. return `
  9139. <tr onclick="selectFilterRow('rules', '${r.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  9140. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  9141. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  9142. <td class="py-2 px-3">
  9143. <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>
  9144. </td>
  9145. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  9146. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  9147. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9148. <button onclick="moveRoutingFilterOrder('${r.id}', -1)" title="Move Up" class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700">▲</button>
  9149. <button onclick="moveRoutingFilterOrder('${r.id}', 1)" title="Move Down" class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700">▼</button>
  9150. <button onclick="toggleRoutingFilterState('${r.id}', ${!r.disabled})" class="px-2 py-0.5 rounded text-[10px] ${r.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  9151. ${r.disabled ? 'Enable' : 'Disable'}
  9152. </button>
  9153. <button onclick="openEditRoutingFilterModal('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  9154. Edit
  9155. </button>
  9156. <button onclick="deleteRoutingFilter('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  9157. ✕
  9158. </button>
  9159. </td>
  9160. </tr>
  9161. `;
  9162. }).join('');
  9163. }
  9164. // -------------------------------------------------------------
  9165. // TAB 2: SELECT RULES (/routing filter select-rule)
  9166. // -------------------------------------------------------------
  9167. function renderRoutingFilterSelectRules() {
  9168. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  9169. if (!tbody) return;
  9170. const empty = document.getElementById('rf-select-rules-empty');
  9171. const statusCount = document.getElementById('rf-status-count');
  9172. let list = (state.routingSelectRules || []).slice();
  9173. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  9174. list = list.filter(r => r.chain === state.filterChainSelected);
  9175. }
  9176. const q = state.rfSearchQuery;
  9177. if (q) {
  9178. list = list.filter(r =>
  9179. (r.chain && r.chain.toLowerCase().includes(q)) ||
  9180. (r.rule && r.rule.toLowerCase().includes(q)) ||
  9181. (r.comment && r.comment.toLowerCase().includes(q))
  9182. );
  9183. }
  9184. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  9185. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9186. }
  9187. if (list.length === 0) {
  9188. tbody.innerHTML = '';
  9189. if (empty) empty.classList.remove('hidden');
  9190. return;
  9191. }
  9192. if (empty) empty.classList.add('hidden');
  9193. tbody.innerHTML = list.map(r => {
  9194. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  9195. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9196. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9197. return `
  9198. <tr onclick="selectFilterRow('select-rules', '${r.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  9199. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9200. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  9201. <td class="py-2 px-3">
  9202. <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>
  9203. </td>
  9204. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  9205. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  9206. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9207. <button onclick="toggleSelectRuleState('${r.id}', ${!r.disabled})" class="px-2 py-0.5 rounded text-[10px] ${r.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  9208. ${r.disabled ? 'Enable' : 'Disable'}
  9209. </button>
  9210. <button onclick="openEditSelectRuleModal('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  9211. Edit
  9212. </button>
  9213. <button onclick="deleteSelectRule('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  9214. ✕
  9215. </button>
  9216. </td>
  9217. </tr>
  9218. `;
  9219. }).join('');
  9220. }
  9221. // -------------------------------------------------------------
  9222. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  9223. // -------------------------------------------------------------
  9224. function renderRoutingFilterCommunityLists() {
  9225. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  9226. if (!tbody) return;
  9227. const empty = document.getElementById('rf-comm-lists-empty');
  9228. const statusCount = document.getElementById('rf-status-count');
  9229. let list = (state.routingCommunityLists || []).slice();
  9230. const q = state.rfSearchQuery;
  9231. if (q) {
  9232. list = list.filter(cl =>
  9233. (cl.name && cl.name.toLowerCase().includes(q)) ||
  9234. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  9235. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  9236. );
  9237. }
  9238. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  9239. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9240. }
  9241. if (list.length === 0) {
  9242. tbody.innerHTML = '';
  9243. if (empty) empty.classList.remove('hidden');
  9244. return;
  9245. }
  9246. if (empty) empty.classList.add('hidden');
  9247. tbody.innerHTML = list.map(cl => {
  9248. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  9249. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9250. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9251. const commBadges = (cl.communities || []).map(c =>
  9252. `<span class="px-1.5 py-0.5 rounded text-[10px] bg-indigo-950 text-indigo-300 border border-indigo-800/40 font-mono">${escapeHtml(c)}</span>`
  9253. ).join(' ');
  9254. return `
  9255. <tr onclick="selectFilterRow('community-lists', '${cl.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  9256. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9257. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  9258. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  9259. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  9260. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  9261. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9262. <button onclick="toggleCommunityListState('${cl.id}', ${!cl.disabled})" class="px-2 py-0.5 rounded text-[10px] ${cl.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  9263. ${cl.disabled ? 'Enable' : 'Disable'}
  9264. </button>
  9265. <button onclick="openEditCommunityListModal('${cl.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  9266. Edit
  9267. </button>
  9268. <button onclick="deleteCommunityList('${cl.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  9269. ✕
  9270. </button>
  9271. </td>
  9272. </tr>
  9273. `;
  9274. }).join('');
  9275. }
  9276. // -------------------------------------------------------------
  9277. // TAB 4: AS LISTS (/routing filter num-list)
  9278. // -------------------------------------------------------------
  9279. function renderRoutingFilterASLists() {
  9280. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  9281. if (!tbody) return;
  9282. const empty = document.getElementById('rf-as-lists-empty');
  9283. const statusCount = document.getElementById('rf-status-count');
  9284. let list = (state.routingASLists || []).slice();
  9285. const q = state.rfSearchQuery;
  9286. if (q) {
  9287. list = list.filter(al =>
  9288. (al.name && al.name.toLowerCase().includes(q)) ||
  9289. (al.range && al.range.toLowerCase().includes(q)) ||
  9290. (al.comment && al.comment.toLowerCase().includes(q))
  9291. );
  9292. }
  9293. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  9294. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9295. }
  9296. if (list.length === 0) {
  9297. tbody.innerHTML = '';
  9298. if (empty) empty.classList.remove('hidden');
  9299. return;
  9300. }
  9301. if (empty) empty.classList.add('hidden');
  9302. tbody.innerHTML = list.map(al => {
  9303. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  9304. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9305. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9306. return `
  9307. <tr onclick="selectFilterRow('as-lists', '${al.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  9308. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9309. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  9310. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  9311. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  9312. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9313. <button onclick="toggleASListState('${al.id}', ${!al.disabled})" class="px-2 py-0.5 rounded text-[10px] ${al.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  9314. ${al.disabled ? 'Enable' : 'Disable'}
  9315. </button>
  9316. <button onclick="openEditASListModal('${al.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  9317. Edit
  9318. </button>
  9319. <button onclick="deleteASList('${al.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  9320. ✕
  9321. </button>
  9322. </td>
  9323. </tr>
  9324. `;
  9325. }).join('');
  9326. }
  9327. // -------------------------------------------------------------
  9328. // SNIPPETS & WIZARD HELPERS
  9329. // -------------------------------------------------------------
  9330. function insertRuleSnippet(type) {
  9331. const textarea = document.getElementById('modal-rf-rule');
  9332. if (!textarea) return;
  9333. let snippet = '';
  9334. switch (type) {
  9335. case 'accept-default':
  9336. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  9337. break;
  9338. case 'drop-rfc1918':
  9339. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  9340. break;
  9341. case 'len-24':
  9342. snippet = 'if (dst-len > 24) { reject; }';
  9343. break;
  9344. case 'local-pref-150':
  9345. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  9346. break;
  9347. case 'as-prepend-2':
  9348. snippet = 'set bgp-path-prepend 2; accept;';
  9349. break;
  9350. case 'set-comm':
  9351. snippet = 'set bgp-communities.add 65000:100; accept;';
  9352. break;
  9353. case 'match-comm':
  9354. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  9355. break;
  9356. case 'reject-all':
  9357. snippet = 'reject;';
  9358. break;
  9359. }
  9360. if (!snippet) return;
  9361. if (!textarea.value.trim()) {
  9362. textarea.value = snippet;
  9363. } else {
  9364. textarea.value = textarea.value.trim() + '\n' + snippet;
  9365. }
  9366. }
  9367. function generateScriptFromWizard() {
  9368. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  9369. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  9370. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  9371. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  9372. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  9373. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  9374. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  9375. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  9376. const conds = [];
  9377. if (pfx) {
  9378. if (pfxLen) {
  9379. if (pfxLen.includes('-')) {
  9380. const parts = pfxLen.split('-');
  9381. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  9382. } else {
  9383. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  9384. }
  9385. } else {
  9386. conds.push(`dst in ${pfx}`);
  9387. }
  9388. }
  9389. if (proto && proto !== 'any') {
  9390. conds.push(`protocol ${proto}`);
  9391. }
  9392. if (asp) {
  9393. conds.push(`bgp-as-path "${asp}"`);
  9394. }
  9395. if (comm) {
  9396. conds.push(`bgp-communities includes ${comm}`);
  9397. }
  9398. const actions = [];
  9399. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  9400. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  9401. actions.push(`${act};`);
  9402. let code = '';
  9403. if (conds.length > 0) {
  9404. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  9405. } else {
  9406. code = actions.join(' ');
  9407. }
  9408. const textarea = document.getElementById('modal-rf-rule');
  9409. if (textarea) textarea.value = code;
  9410. }
  9411. // -------------------------------------------------------------
  9412. // MODAL CRUD: RULES (/routing filter rule)
  9413. // -------------------------------------------------------------
  9414. function openAddRoutingFilterModal(defaultChain = '') {
  9415. const form = document.getElementById('routing-filter-form');
  9416. if (form) form.reset();
  9417. const idEl = document.getElementById('modal-rf-id');
  9418. if (idEl) idEl.value = '';
  9419. const titleEl = document.getElementById('modal-rf-title');
  9420. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  9421. const chainEl = document.getElementById('modal-rf-chain');
  9422. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  9423. const orderEl = document.getElementById('modal-rf-order');
  9424. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  9425. const ruleEl = document.getElementById('modal-rf-rule');
  9426. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  9427. const disEl = document.getElementById('modal-rf-disabled');
  9428. if (disEl) disEl.checked = false;
  9429. const modal = document.getElementById('modal-routing-filter');
  9430. if (modal) modal.classList.remove('hidden');
  9431. }
  9432. function openEditRoutingFilterModal(id) {
  9433. const r = (state.routingFilters || []).find(item => item.id === id);
  9434. if (!r) return;
  9435. const idEl = document.getElementById('modal-rf-id');
  9436. if (idEl) idEl.value = r.id;
  9437. const titleEl = document.getElementById('modal-rf-title');
  9438. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  9439. const chainEl = document.getElementById('modal-rf-chain');
  9440. if (chainEl) chainEl.value = r.chain || '';
  9441. const orderEl = document.getElementById('modal-rf-order');
  9442. if (orderEl) orderEl.value = r.rule_order || 10;
  9443. const ruleEl = document.getElementById('modal-rf-rule');
  9444. if (ruleEl) {
  9445. if (r.rule) {
  9446. ruleEl.value = r.rule;
  9447. } else {
  9448. let conds = [];
  9449. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  9450. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  9451. let act = r.action || 'accept';
  9452. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  9453. }
  9454. }
  9455. const comEl = document.getElementById('modal-rf-comment');
  9456. if (comEl) comEl.value = r.comment || '';
  9457. const disEl = document.getElementById('modal-rf-disabled');
  9458. if (disEl) disEl.checked = !!r.disabled;
  9459. const modal = document.getElementById('modal-routing-filter');
  9460. if (modal) modal.classList.remove('hidden');
  9461. }
  9462. function closeRoutingFilterModal() {
  9463. const modal = document.getElementById('modal-routing-filter');
  9464. if (modal) modal.classList.add('hidden');
  9465. }
  9466. async function submitRoutingFilter(e) {
  9467. if (e) e.preventDefault();
  9468. const payload = {
  9469. id: document.getElementById('modal-rf-id').value,
  9470. chain: document.getElementById('modal-rf-chain').value.trim(),
  9471. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  9472. rule: document.getElementById('modal-rf-rule').value.trim(),
  9473. comment: document.getElementById('modal-rf-comment').value.trim(),
  9474. disabled: document.getElementById('modal-rf-disabled').checked
  9475. };
  9476. try {
  9477. const res = await fetch(`${API_BASE}/routing/filters`, {
  9478. method: 'POST',
  9479. headers: { 'Content-Type': 'application/json' },
  9480. body: JSON.stringify(payload)
  9481. });
  9482. if (res.ok) {
  9483. closeRoutingFilterModal();
  9484. showToast('Success', 'Routing filter rule saved', 'success');
  9485. loadDynamicRouting();
  9486. } else {
  9487. const err = await res.json();
  9488. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  9489. }
  9490. } catch (err) {
  9491. showToast('Error', err.message, 'error');
  9492. }
  9493. }
  9494. async function applyRoutingFilterForm() {
  9495. const payload = {
  9496. id: document.getElementById('modal-rf-id').value,
  9497. chain: document.getElementById('modal-rf-chain').value.trim(),
  9498. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  9499. rule: document.getElementById('modal-rf-rule').value.trim(),
  9500. comment: document.getElementById('modal-rf-comment').value.trim(),
  9501. disabled: document.getElementById('modal-rf-disabled').checked
  9502. };
  9503. try {
  9504. const res = await fetch(`${API_BASE}/routing/filters`, {
  9505. method: 'POST',
  9506. headers: { 'Content-Type': 'application/json' },
  9507. body: JSON.stringify(payload)
  9508. });
  9509. if (res.ok) {
  9510. const data = await res.json();
  9511. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  9512. showToast('Applied', 'Routing filter configuration applied', 'success');
  9513. loadDynamicRouting();
  9514. } else {
  9515. const err = await res.json();
  9516. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  9517. }
  9518. } catch (err) {
  9519. showToast('Error', err.message, 'error');
  9520. }
  9521. }
  9522. async function moveRoutingFilterOrder(id, delta) {
  9523. const list = state.routingFilters || [];
  9524. const idx = list.findIndex(r => r.id === id);
  9525. if (idx < 0) return;
  9526. const targetIdx = idx + delta;
  9527. if (targetIdx < 0 || targetIdx >= list.length) return;
  9528. const currentOrder = list[idx].rule_order || 10;
  9529. const targetOrder = list[targetIdx].rule_order || 20;
  9530. list[idx].rule_order = targetOrder;
  9531. list[targetIdx].rule_order = currentOrder;
  9532. try {
  9533. await fetch(`${API_BASE}/routing/filters`, {
  9534. method: 'POST',
  9535. headers: { 'Content-Type': 'application/json' },
  9536. body: JSON.stringify(list[idx])
  9537. });
  9538. await fetch(`${API_BASE}/routing/filters`, {
  9539. method: 'POST',
  9540. headers: { 'Content-Type': 'application/json' },
  9541. body: JSON.stringify(list[targetIdx])
  9542. });
  9543. loadDynamicRouting();
  9544. } catch (e) {
  9545. console.error('Reorder error:', e);
  9546. }
  9547. }
  9548. async function deleteRoutingFilter(id) {
  9549. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  9550. try {
  9551. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9552. if (res.ok) {
  9553. showToast('Deleted', 'Routing filter rule removed', 'info');
  9554. loadDynamicRouting();
  9555. } else {
  9556. const err = await res.json();
  9557. showToast('Error', err.error || 'Failed to delete rule', 'error');
  9558. }
  9559. } catch (err) {
  9560. showToast('Error', err.message, 'error');
  9561. }
  9562. }
  9563. async function toggleRoutingFilterState(id, disabled) {
  9564. try {
  9565. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  9566. method: 'POST',
  9567. headers: { 'Content-Type': 'application/json' },
  9568. body: JSON.stringify({ disabled })
  9569. });
  9570. if (res.ok) {
  9571. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  9572. loadDynamicRouting();
  9573. } else {
  9574. const err = await res.json();
  9575. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  9576. }
  9577. } catch (err) {
  9578. showToast('Error', err.message, 'error');
  9579. }
  9580. }
  9581. // -------------------------------------------------------------
  9582. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  9583. // -------------------------------------------------------------
  9584. function openAddSelectRuleModal() {
  9585. document.getElementById('modal-rf-sr-id').value = '';
  9586. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  9587. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  9588. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  9589. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  9590. document.getElementById('modal-rf-sr-comment').value = '';
  9591. document.getElementById('modal-rf-sr-disabled').checked = false;
  9592. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  9593. }
  9594. function openEditSelectRuleModal(id) {
  9595. const r = (state.routingSelectRules || []).find(item => item.id === id);
  9596. if (!r) return;
  9597. document.getElementById('modal-rf-sr-id').value = r.id;
  9598. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  9599. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  9600. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  9601. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  9602. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  9603. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  9604. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  9605. }
  9606. function closeSelectRuleModal() {
  9607. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  9608. }
  9609. async function submitSelectRule(e) {
  9610. e.preventDefault();
  9611. const payload = {
  9612. id: document.getElementById('modal-rf-sr-id').value,
  9613. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  9614. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  9615. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  9616. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  9617. disabled: document.getElementById('modal-rf-sr-disabled').checked
  9618. };
  9619. try {
  9620. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  9621. method: 'POST',
  9622. headers: { 'Content-Type': 'application/json' },
  9623. body: JSON.stringify(payload)
  9624. });
  9625. if (res.ok) {
  9626. closeSelectRuleModal();
  9627. showToast('Success', 'Select rule saved', 'success');
  9628. loadDynamicRouting();
  9629. } else {
  9630. const err = await res.json();
  9631. showToast('Error', err.error || 'Failed to save select rule', 'error');
  9632. }
  9633. } catch (err) {
  9634. showToast('Error', err.message, 'error');
  9635. }
  9636. }
  9637. async function deleteSelectRule(id) {
  9638. if (!confirm('Are you sure you want to delete this select rule?')) return;
  9639. try {
  9640. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9641. if (res.ok) {
  9642. showToast('Deleted', 'Select rule removed', 'info');
  9643. loadDynamicRouting();
  9644. } else {
  9645. const err = await res.json();
  9646. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  9647. }
  9648. } catch (err) {
  9649. showToast('Error', err.message, 'error');
  9650. }
  9651. }
  9652. async function toggleSelectRuleState(id, disabled) {
  9653. try {
  9654. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  9655. method: 'POST',
  9656. headers: { 'Content-Type': 'application/json' },
  9657. body: JSON.stringify({ disabled })
  9658. });
  9659. if (res.ok) {
  9660. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  9661. loadDynamicRouting();
  9662. } else {
  9663. const err = await res.json();
  9664. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  9665. }
  9666. } catch (err) {
  9667. showToast('Error', err.message, 'error');
  9668. }
  9669. }
  9670. // -------------------------------------------------------------
  9671. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  9672. // -------------------------------------------------------------
  9673. function openAddCommunityListModal() {
  9674. document.getElementById('modal-rf-cl-id').value = '';
  9675. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  9676. document.getElementById('modal-rf-cl-name').value = '';
  9677. document.getElementById('modal-rf-cl-communities').value = '';
  9678. document.getElementById('modal-rf-cl-regexp').value = '';
  9679. document.getElementById('modal-rf-cl-comment').value = '';
  9680. document.getElementById('modal-rf-cl-disabled').checked = false;
  9681. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  9682. }
  9683. function openEditCommunityListModal(id) {
  9684. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  9685. if (!cl) return;
  9686. document.getElementById('modal-rf-cl-id').value = cl.id;
  9687. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  9688. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  9689. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  9690. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  9691. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  9692. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  9693. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  9694. }
  9695. function closeCommunityListModal() {
  9696. document.getElementById('modal-rf-community-list').classList.add('hidden');
  9697. }
  9698. async function submitCommunityList(e) {
  9699. e.preventDefault();
  9700. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  9701. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  9702. const payload = {
  9703. id: document.getElementById('modal-rf-cl-id').value,
  9704. name: document.getElementById('modal-rf-cl-name').value.trim(),
  9705. communities: comms,
  9706. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  9707. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  9708. disabled: document.getElementById('modal-rf-cl-disabled').checked
  9709. };
  9710. try {
  9711. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  9712. method: 'POST',
  9713. headers: { 'Content-Type': 'application/json' },
  9714. body: JSON.stringify(payload)
  9715. });
  9716. if (res.ok) {
  9717. closeCommunityListModal();
  9718. showToast('Success', 'Community list saved', 'success');
  9719. loadDynamicRouting();
  9720. } else {
  9721. const err = await res.json();
  9722. showToast('Error', err.error || 'Failed to save community list', 'error');
  9723. }
  9724. } catch (err) {
  9725. showToast('Error', err.message, 'error');
  9726. }
  9727. }
  9728. async function deleteCommunityList(id) {
  9729. if (!confirm('Are you sure you want to delete this community list?')) return;
  9730. try {
  9731. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9732. if (res.ok) {
  9733. showToast('Deleted', 'Community list removed', 'info');
  9734. loadDynamicRouting();
  9735. } else {
  9736. const err = await res.json();
  9737. showToast('Error', err.error || 'Failed to delete community list', 'error');
  9738. }
  9739. } catch (err) {
  9740. showToast('Error', err.message, 'error');
  9741. }
  9742. }
  9743. async function toggleCommunityListState(id, disabled) {
  9744. try {
  9745. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  9746. method: 'POST',
  9747. headers: { 'Content-Type': 'application/json' },
  9748. body: JSON.stringify({ disabled })
  9749. });
  9750. if (res.ok) {
  9751. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  9752. loadDynamicRouting();
  9753. } else {
  9754. const err = await res.json();
  9755. showToast('Error', err.error || 'Failed to update community list state', 'error');
  9756. }
  9757. } catch (err) {
  9758. showToast('Error', err.message, 'error');
  9759. }
  9760. }
  9761. // -------------------------------------------------------------
  9762. // MODAL CRUD: AS LISTS (/routing filter num-list)
  9763. // -------------------------------------------------------------
  9764. function openAddASListModal() {
  9765. document.getElementById('modal-rf-al-id').value = '';
  9766. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  9767. document.getElementById('modal-rf-al-name').value = '';
  9768. document.getElementById('modal-rf-al-range').value = '';
  9769. document.getElementById('modal-rf-al-comment').value = '';
  9770. document.getElementById('modal-rf-al-disabled').checked = false;
  9771. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  9772. }
  9773. function openEditASListModal(id) {
  9774. const al = (state.routingASLists || []).find(item => item.id === id);
  9775. if (!al) return;
  9776. document.getElementById('modal-rf-al-id').value = al.id;
  9777. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  9778. document.getElementById('modal-rf-al-name').value = al.name || '';
  9779. document.getElementById('modal-rf-al-range').value = al.range || '';
  9780. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  9781. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  9782. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  9783. }
  9784. function closeASListModal() {
  9785. document.getElementById('modal-rf-as-list').classList.add('hidden');
  9786. }
  9787. async function submitASList(e) {
  9788. e.preventDefault();
  9789. const payload = {
  9790. id: document.getElementById('modal-rf-al-id').value,
  9791. name: document.getElementById('modal-rf-al-name').value.trim(),
  9792. range: document.getElementById('modal-rf-al-range').value.trim(),
  9793. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  9794. disabled: document.getElementById('modal-rf-al-disabled').checked
  9795. };
  9796. try {
  9797. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  9798. method: 'POST',
  9799. headers: { 'Content-Type': 'application/json' },
  9800. body: JSON.stringify(payload)
  9801. });
  9802. if (res.ok) {
  9803. closeASListModal();
  9804. showToast('Success', 'AS number list saved', 'success');
  9805. loadDynamicRouting();
  9806. } else {
  9807. const err = await res.json();
  9808. showToast('Error', err.error || 'Failed to save AS list', 'error');
  9809. }
  9810. } catch (err) {
  9811. showToast('Error', err.message, 'error');
  9812. }
  9813. }
  9814. async function deleteASList(id) {
  9815. if (!confirm('Are you sure you want to delete this AS list?')) return;
  9816. try {
  9817. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9818. if (res.ok) {
  9819. showToast('Deleted', 'AS list removed', 'info');
  9820. loadDynamicRouting();
  9821. } else {
  9822. const err = await res.json();
  9823. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  9824. }
  9825. } catch (err) {
  9826. showToast('Error', err.message, 'error');
  9827. }
  9828. }
  9829. async function toggleASListState(id, disabled) {
  9830. try {
  9831. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  9832. method: 'POST',
  9833. headers: { 'Content-Type': 'application/json' },
  9834. body: JSON.stringify({ disabled })
  9835. });
  9836. if (res.ok) {
  9837. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  9838. loadDynamicRouting();
  9839. } else {
  9840. const err = await res.json();
  9841. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  9842. }
  9843. } catch (err) {
  9844. showToast('Error', err.message, 'error');
  9845. }
  9846. }
  9847. // ==========================================
  9848. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  9849. // ==========================================
  9850. function loadToolsView() {
  9851. populateToolsInterfaces();
  9852. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  9853. }
  9854. function populateToolsInterfaces() {
  9855. const pingSel = document.getElementById('tools-ping-iface');
  9856. const traceSel = document.getElementById('tools-tr-iface');
  9857. let opts = '<option value="">Auto (Default Route)</option>';
  9858. if (Array.isArray(state.interfaces)) {
  9859. state.interfaces.forEach(iface => {
  9860. if (iface.name) {
  9861. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  9862. }
  9863. });
  9864. }
  9865. if (pingSel) {
  9866. const cur = pingSel.value;
  9867. pingSel.innerHTML = opts;
  9868. if (cur) pingSel.value = cur;
  9869. }
  9870. if (traceSel) {
  9871. const cur = traceSel.value;
  9872. traceSel.innerHTML = opts;
  9873. if (cur) traceSel.value = cur;
  9874. }
  9875. }
  9876. function switchToolsSubTab(subTab) {
  9877. state.activeToolsSubTab = subTab;
  9878. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  9879. tabs.forEach(t => {
  9880. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  9881. const view = document.getElementById(`tools-view-${t}`);
  9882. if (btn) {
  9883. if (t === subTab) {
  9884. 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';
  9885. } else {
  9886. 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';
  9887. }
  9888. }
  9889. if (view) {
  9890. if (t === subTab) {
  9891. view.classList.remove('hidden');
  9892. } else {
  9893. view.classList.add('hidden');
  9894. }
  9895. }
  9896. });
  9897. }
  9898. function setPortPreset(port) {
  9899. const input = document.getElementById('tools-port-num');
  9900. if (input) input.value = port;
  9901. }
  9902. let pingAbortController = null;
  9903. let tracerouteAbortController = null;
  9904. function clearPingTable() {
  9905. const tbody = document.getElementById('tools-ping-tbody');
  9906. if (tbody) tbody.innerHTML = '';
  9907. const rawEl = document.getElementById('tools-ping-raw');
  9908. if (rawEl) rawEl.innerText = '';
  9909. const sentEl = document.getElementById('tools-ping-stat-sent');
  9910. if (sentEl) sentEl.innerText = '0';
  9911. const recvEl = document.getElementById('tools-ping-stat-recv');
  9912. if (recvEl) recvEl.innerText = '0';
  9913. const lossEl = document.getElementById('tools-ping-stat-loss');
  9914. if (lossEl) lossEl.innerText = '0%';
  9915. const avgEl = document.getElementById('tools-ping-stat-avg');
  9916. if (avgEl) avgEl.innerText = '0 ms';
  9917. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  9918. if (minMaxEl) minMaxEl.innerText = '-';
  9919. const badge = document.getElementById('tools-ping-status-badge');
  9920. if (badge) {
  9921. badge.className = '';
  9922. badge.innerText = '';
  9923. }
  9924. }
  9925. function clearTracerouteTable() {
  9926. const tbody = document.getElementById('tools-tr-tbody');
  9927. if (tbody) tbody.innerHTML = '';
  9928. const rawEl = document.getElementById('tools-tr-raw');
  9929. if (rawEl) rawEl.innerText = '';
  9930. const statHops = document.getElementById('tools-tr-hops-count');
  9931. if (statHops) statHops.innerText = '0 Hops';
  9932. }
  9933. function resetPingButton() {
  9934. const btn = document.getElementById('tools-ping-btn');
  9935. const btnText = document.getElementById('tools-ping-btn-text');
  9936. const spinner = document.getElementById('tools-ping-spinner');
  9937. if (btn) {
  9938. btn.disabled = false;
  9939. 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';
  9940. }
  9941. if (btnText) btnText.innerText = 'Start Ping';
  9942. if (spinner) spinner.classList.add('hidden');
  9943. }
  9944. function setPingRunningButton() {
  9945. const btn = document.getElementById('tools-ping-btn');
  9946. const btnText = document.getElementById('tools-ping-btn-text');
  9947. const spinner = document.getElementById('tools-ping-spinner');
  9948. if (btn) {
  9949. btn.disabled = false;
  9950. 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';
  9951. }
  9952. if (btnText) btnText.innerText = 'Stop Ping';
  9953. if (spinner) spinner.classList.remove('hidden');
  9954. }
  9955. function resetTracerouteButton() {
  9956. const btn = document.getElementById('tools-tr-btn');
  9957. const btnText = document.getElementById('tools-tr-btn-text');
  9958. const spinner = document.getElementById('tools-tr-spinner');
  9959. if (btn) {
  9960. btn.disabled = false;
  9961. 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';
  9962. }
  9963. if (btnText) btnText.innerText = 'Start Traceroute';
  9964. if (spinner) spinner.classList.add('hidden');
  9965. }
  9966. function setTracerouteRunningButton() {
  9967. const btn = document.getElementById('tools-tr-btn');
  9968. const btnText = document.getElementById('tools-tr-btn-text');
  9969. const spinner = document.getElementById('tools-tr-spinner');
  9970. if (btn) {
  9971. btn.disabled = false;
  9972. 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';
  9973. }
  9974. if (btnText) btnText.innerText = 'Stop Traceroute';
  9975. if (spinner) spinner.classList.remove('hidden');
  9976. }
  9977. async function executePing(e) {
  9978. if (e) e.preventDefault();
  9979. // If already running, clicking the button stops the stream!
  9980. if (pingAbortController) {
  9981. pingAbortController.abort();
  9982. pingAbortController = null;
  9983. resetPingButton();
  9984. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  9985. return;
  9986. }
  9987. const target = document.getElementById('tools-ping-target')?.value?.trim();
  9988. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  9989. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  9990. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  9991. const iface = document.getElementById('tools-ping-iface')?.value || '';
  9992. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  9993. if (!target) {
  9994. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  9995. return;
  9996. }
  9997. clearPingTable();
  9998. const resCard = document.getElementById('tools-ping-results');
  9999. if (resCard) resCard.classList.remove('hidden');
  10000. pingAbortController = new AbortController();
  10001. setPingRunningButton();
  10002. try {
  10003. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  10004. method: 'POST',
  10005. headers: { 'Content-Type': 'application/json' },
  10006. body: JSON.stringify({
  10007. target,
  10008. count,
  10009. size,
  10010. timeout,
  10011. interface: iface,
  10012. dont_frag: dontFrag
  10013. }),
  10014. signal: pingAbortController.signal
  10015. });
  10016. if (!res.ok) {
  10017. const errText = await res.text();
  10018. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  10019. resetPingButton();
  10020. pingAbortController = null;
  10021. return;
  10022. }
  10023. const reader = res.body.getReader();
  10024. const decoder = new TextDecoder('utf-8');
  10025. let buffer = '';
  10026. while (true) {
  10027. const { done, value } = await reader.read();
  10028. if (done) break;
  10029. buffer += decoder.decode(value, { stream: true });
  10030. const blocks = buffer.split('\n\n');
  10031. buffer = blocks.pop() || '';
  10032. for (const block of blocks) {
  10033. const trimmed = block.trim();
  10034. if (!trimmed) continue;
  10035. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  10036. try {
  10037. const evt = JSON.parse(line);
  10038. handleLivePingEvent(evt);
  10039. } catch (parseErr) {
  10040. console.warn('Ping SSE parse error:', parseErr, line);
  10041. }
  10042. }
  10043. }
  10044. } catch (err) {
  10045. if (err.name === 'AbortError') {
  10046. // User aborted normally
  10047. } else {
  10048. showToast('Ping Error', err.message, 'error');
  10049. }
  10050. } finally {
  10051. pingAbortController = null;
  10052. resetPingButton();
  10053. }
  10054. }
  10055. function handleLivePingEvent(evt) {
  10056. const sentEl = document.getElementById('tools-ping-stat-sent');
  10057. const recvEl = document.getElementById('tools-ping-stat-recv');
  10058. const lossEl = document.getElementById('tools-ping-stat-loss');
  10059. const avgEl = document.getElementById('tools-ping-stat-avg');
  10060. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  10061. const badge = document.getElementById('tools-ping-status-badge');
  10062. const tbody = document.getElementById('tools-ping-tbody');
  10063. const rawEl = document.getElementById('tools-ping-raw');
  10064. if (evt.raw && rawEl) {
  10065. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  10066. rawEl.scrollTop = rawEl.scrollHeight;
  10067. }
  10068. if (evt.type === 'reply') {
  10069. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10070. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  10071. if (lossEl && evt.packet_loss_pct !== undefined) {
  10072. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10073. lossEl.className = evt.packet_loss_pct === 0
  10074. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  10075. : (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');
  10076. }
  10077. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  10078. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  10079. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  10080. }
  10081. if (badge) {
  10082. if (evt.packet_loss_pct === 0) {
  10083. 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';
  10084. badge.innerText = '100% OK';
  10085. } else {
  10086. 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';
  10087. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  10088. }
  10089. }
  10090. if (tbody) {
  10091. const tr = document.createElement('tr');
  10092. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  10093. tr.innerHTML = `
  10094. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  10095. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  10096. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  10097. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  10098. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  10099. <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>
  10100. `;
  10101. tbody.appendChild(tr);
  10102. }
  10103. } else if (evt.type === 'timeout') {
  10104. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10105. if (lossEl && evt.packet_loss_pct !== undefined) {
  10106. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10107. 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';
  10108. }
  10109. if (badge) {
  10110. 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';
  10111. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  10112. }
  10113. if (tbody) {
  10114. const tr = document.createElement('tr');
  10115. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  10116. tr.innerHTML = `
  10117. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  10118. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  10119. <td class="py-2 px-3 text-slate-600">--</td>
  10120. <td class="py-2 px-3 text-slate-600">--</td>
  10121. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  10122. <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>
  10123. `;
  10124. tbody.appendChild(tr);
  10125. }
  10126. } else if (evt.type === 'unreach') {
  10127. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10128. if (lossEl && evt.packet_loss_pct !== undefined) {
  10129. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10130. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  10131. }
  10132. if (badge) {
  10133. 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';
  10134. badge.innerText = 'UNREACHABLE';
  10135. }
  10136. if (tbody) {
  10137. const tr = document.createElement('tr');
  10138. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  10139. tr.innerHTML = `
  10140. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  10141. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  10142. <td class="py-2 px-3 text-slate-600">--</td>
  10143. <td class="py-2 px-3 text-slate-600">--</td>
  10144. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  10145. <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>
  10146. `;
  10147. tbody.appendChild(tr);
  10148. }
  10149. } else if (evt.type === 'stats') {
  10150. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10151. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  10152. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10153. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  10154. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  10155. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  10156. }
  10157. } else if (evt.type === 'done') {
  10158. 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');
  10159. }
  10160. }
  10161. async function executeTraceroute(e) {
  10162. if (e) e.preventDefault();
  10163. if (tracerouteAbortController) {
  10164. tracerouteAbortController.abort();
  10165. tracerouteAbortController = null;
  10166. resetTracerouteButton();
  10167. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  10168. return;
  10169. }
  10170. const target = document.getElementById('tools-tr-target')?.value?.trim();
  10171. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  10172. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  10173. const iface = document.getElementById('tools-tr-iface')?.value || '';
  10174. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  10175. if (!target) {
  10176. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10177. return;
  10178. }
  10179. clearTracerouteTable();
  10180. const resCard = document.getElementById('tools-tr-results');
  10181. if (resCard) resCard.classList.remove('hidden');
  10182. tracerouteAbortController = new AbortController();
  10183. setTracerouteRunningButton();
  10184. try {
  10185. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  10186. method: 'POST',
  10187. headers: { 'Content-Type': 'application/json' },
  10188. body: JSON.stringify({
  10189. target,
  10190. max_hops: maxHops,
  10191. protocol,
  10192. interface: iface,
  10193. resolve
  10194. }),
  10195. signal: tracerouteAbortController.signal
  10196. });
  10197. if (!res.ok) {
  10198. const errText = await res.text();
  10199. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  10200. resetTracerouteButton();
  10201. tracerouteAbortController = null;
  10202. return;
  10203. }
  10204. const reader = res.body.getReader();
  10205. const decoder = new TextDecoder('utf-8');
  10206. let buffer = '';
  10207. while (true) {
  10208. const { done, value } = await reader.read();
  10209. if (done) break;
  10210. buffer += decoder.decode(value, { stream: true });
  10211. const blocks = buffer.split('\n\n');
  10212. buffer = blocks.pop() || '';
  10213. for (const block of blocks) {
  10214. const trimmed = block.trim();
  10215. if (!trimmed) continue;
  10216. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  10217. try {
  10218. const evt = JSON.parse(line);
  10219. handleLiveTracerouteEvent(evt);
  10220. } catch (parseErr) {
  10221. console.warn('Traceroute SSE parse error:', parseErr, line);
  10222. }
  10223. }
  10224. }
  10225. } catch (err) {
  10226. if (err.name === 'AbortError') {
  10227. // User aborted normally
  10228. } else {
  10229. showToast('Traceroute Error', err.message, 'error');
  10230. }
  10231. } finally {
  10232. tracerouteAbortController = null;
  10233. resetTracerouteButton();
  10234. }
  10235. }
  10236. function handleLiveTracerouteEvent(evt) {
  10237. const statHops = document.getElementById('tools-tr-hops-count');
  10238. const tbody = document.getElementById('tools-tr-tbody');
  10239. const rawEl = document.getElementById('tools-tr-raw');
  10240. if (evt.raw && rawEl) {
  10241. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  10242. rawEl.scrollTop = rawEl.scrollHeight;
  10243. }
  10244. if (evt.hops_count !== undefined && statHops) {
  10245. statHops.innerText = `${evt.hops_count} Hops`;
  10246. }
  10247. if (evt.type === 'hop' && evt.hop && tbody) {
  10248. const h = evt.hop;
  10249. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  10250. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  10251. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  10252. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  10253. const tr = document.createElement('tr');
  10254. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  10255. tr.innerHTML = `
  10256. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  10257. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  10258. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  10259. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  10260. <td class="py-2.5 px-3 text-right">
  10261. ${isTimeout
  10262. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  10263. : '<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>'}
  10264. </td>
  10265. `;
  10266. tbody.appendChild(tr);
  10267. } else if (evt.type === 'done') {
  10268. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  10269. }
  10270. }
  10271. async function executeMTR(e) {
  10272. if (e) e.preventDefault();
  10273. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  10274. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  10275. if (!target) {
  10276. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10277. return;
  10278. }
  10279. const btn = document.getElementById('tools-mtr-btn');
  10280. const spinner = document.getElementById('tools-mtr-spinner');
  10281. if (btn) btn.disabled = true;
  10282. if (spinner) spinner.classList.remove('hidden');
  10283. try {
  10284. const res = await fetch(`${API_BASE}/tools/mtr`, {
  10285. method: 'POST',
  10286. headers: { 'Content-Type': 'application/json' },
  10287. body: JSON.stringify({ target, count: cycles })
  10288. });
  10289. const data = await res.json();
  10290. if (!res.ok) {
  10291. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  10292. return;
  10293. }
  10294. const resCard = document.getElementById('tools-mtr-results');
  10295. if (resCard) resCard.classList.remove('hidden');
  10296. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  10297. const statHops = document.getElementById('tools-mtr-hops-count');
  10298. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  10299. const tbody = document.getElementById('tools-mtr-tbody');
  10300. if (tbody) {
  10301. if (hopsCount > 0) {
  10302. tbody.innerHTML = data.hops.map(h => {
  10303. 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');
  10304. return `
  10305. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  10306. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  10307. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  10308. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  10309. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  10310. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  10311. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  10312. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  10313. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  10314. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  10315. </tr>
  10316. `;
  10317. }).join('');
  10318. } else {
  10319. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  10320. }
  10321. }
  10322. const rawEl = document.getElementById('tools-mtr-raw');
  10323. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  10324. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  10325. } catch (err) {
  10326. showToast('MTR Error', err.message, 'error');
  10327. } finally {
  10328. if (btn) btn.disabled = false;
  10329. if (spinner) spinner.classList.add('hidden');
  10330. }
  10331. }
  10332. async function executeDNS(e) {
  10333. if (e) e.preventDefault();
  10334. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  10335. const type = document.getElementById('tools-dns-type')?.value || 'A';
  10336. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  10337. if (!domain) {
  10338. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  10339. return;
  10340. }
  10341. const btn = document.getElementById('tools-dns-btn');
  10342. const spinner = document.getElementById('tools-dns-spinner');
  10343. if (btn) btn.disabled = true;
  10344. if (spinner) spinner.classList.remove('hidden');
  10345. try {
  10346. const res = await fetch(`${API_BASE}/tools/dns`, {
  10347. method: 'POST',
  10348. headers: { 'Content-Type': 'application/json' },
  10349. body: JSON.stringify({ domain, type, server })
  10350. });
  10351. const data = await res.json();
  10352. if (!res.ok) {
  10353. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  10354. return;
  10355. }
  10356. const resCard = document.getElementById('tools-dns-results');
  10357. if (resCard) resCard.classList.remove('hidden');
  10358. const metaEl = document.getElementById('tools-dns-meta');
  10359. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  10360. const tbody = document.getElementById('tools-dns-tbody');
  10361. if (tbody) {
  10362. if (Array.isArray(data.records) && data.records.length > 0) {
  10363. tbody.innerHTML = data.records.map(r => `
  10364. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  10365. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  10366. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  10367. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  10368. <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>
  10369. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  10370. </tr>
  10371. `).join('');
  10372. } else {
  10373. 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>`;
  10374. }
  10375. }
  10376. const rawEl = document.getElementById('tools-dns-raw');
  10377. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  10378. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  10379. } catch (err) {
  10380. showToast('DNS Error', err.message, 'error');
  10381. } finally {
  10382. if (btn) btn.disabled = false;
  10383. if (spinner) spinner.classList.add('hidden');
  10384. }
  10385. }
  10386. async function executePortProbe(e) {
  10387. if (e) e.preventDefault();
  10388. const target = document.getElementById('tools-port-target')?.value?.trim();
  10389. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  10390. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  10391. if (!target || !port) {
  10392. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  10393. return;
  10394. }
  10395. const btn = document.getElementById('tools-port-btn');
  10396. const spinner = document.getElementById('tools-port-spinner');
  10397. if (btn) btn.disabled = true;
  10398. if (spinner) spinner.classList.remove('hidden');
  10399. try {
  10400. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  10401. method: 'POST',
  10402. headers: { 'Content-Type': 'application/json' },
  10403. body: JSON.stringify({ target, port, timeout })
  10404. });
  10405. const data = await res.json();
  10406. if (!res.ok) {
  10407. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  10408. return;
  10409. }
  10410. const resCard = document.getElementById('tools-port-results');
  10411. if (resCard) resCard.classList.remove('hidden');
  10412. const banner = document.getElementById('tools-port-banner');
  10413. const icon = document.getElementById('tools-port-icon');
  10414. const title = document.getElementById('tools-port-title');
  10415. const sub = document.getElementById('tools-port-sub');
  10416. const latency = document.getElementById('tools-port-latency');
  10417. if (data.open) {
  10418. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  10419. if (icon) {
  10420. 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';
  10421. icon.innerText = '✓';
  10422. }
  10423. if (title) {
  10424. title.className = 'text-sm font-bold text-emerald-300';
  10425. title.innerText = `PORT ${port} OPEN / LISTENING`;
  10426. }
  10427. if (sub) {
  10428. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  10429. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  10430. }
  10431. if (latency) {
  10432. latency.className = 'text-base font-bold font-mono text-emerald-300';
  10433. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  10434. }
  10435. } else {
  10436. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  10437. if (icon) {
  10438. 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';
  10439. icon.innerText = '✕';
  10440. }
  10441. if (title) {
  10442. title.className = 'text-sm font-bold text-rose-300';
  10443. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  10444. }
  10445. if (sub) {
  10446. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  10447. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  10448. }
  10449. if (latency) {
  10450. latency.className = 'text-base font-bold font-mono text-slate-500';
  10451. latency.innerText = '--';
  10452. }
  10453. }
  10454. const rawEl = document.getElementById('tools-port-raw');
  10455. 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'}`);
  10456. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  10457. } catch (err) {
  10458. showToast('Probe Error', err.message, 'error');
  10459. } finally {
  10460. if (btn) btn.disabled = false;
  10461. if (spinner) spinner.classList.add('hidden');
  10462. }
  10463. }
  10464. // ==========================================
  10465. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  10466. // ==========================================
  10467. async function loadDHCPClients(showToastMsg = false) {
  10468. try {
  10469. const [clientsRes, sumRes] = await Promise.all([
  10470. fetch(`${API_BASE}/dhcp/clients`),
  10471. fetch(`${API_BASE}/dhcp/clients/summary`)
  10472. ]);
  10473. if (clientsRes.ok) {
  10474. state.dhcpClients = await clientsRes.json();
  10475. }
  10476. if (sumRes.ok) {
  10477. state.dhcpSummary = await sumRes.json();
  10478. }
  10479. renderDHCPClients();
  10480. updateDHCPSummaryCards();
  10481. const bDhcp = document.getElementById('badge-dhcp-client-count');
  10482. if (bDhcp && state.dhcpSummary) {
  10483. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  10484. }
  10485. if (showToastMsg) {
  10486. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  10487. }
  10488. } catch (err) {
  10489. console.error('Failed to load DHCP clients:', err);
  10490. if (showToastMsg) {
  10491. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  10492. }
  10493. }
  10494. }
  10495. function updateDHCPSummaryCards() {
  10496. const sum = state.dhcpSummary || {
  10497. total_clients: (state.dhcpClients || []).length,
  10498. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  10499. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  10500. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  10501. };
  10502. const totalEl = document.getElementById('dhcp-stat-total');
  10503. const boundEl = document.getElementById('dhcp-stat-bound');
  10504. const searchEl = document.getElementById('dhcp-stat-searching');
  10505. const disEl = document.getElementById('dhcp-stat-disabled');
  10506. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  10507. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  10508. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  10509. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  10510. }
  10511. function renderDHCPClients() {
  10512. const tbody = document.getElementById('dhcp-clients-tbody');
  10513. const emptyState = document.getElementById('dhcp-clients-empty');
  10514. if (!tbody) return;
  10515. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  10516. if (clients.length === 0) {
  10517. tbody.innerHTML = '';
  10518. if (emptyState) emptyState.classList.remove('hidden');
  10519. return;
  10520. }
  10521. if (emptyState) emptyState.classList.add('hidden');
  10522. tbody.innerHTML = clients.map(c => {
  10523. let statusBadge = '';
  10524. if (!c.enabled) {
  10525. 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>';
  10526. } else if (c.status === 'bound') {
  10527. 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>';
  10528. } else if (c.status === 'searching') {
  10529. 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>';
  10530. } else if (c.status === 'stopped') {
  10531. 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>';
  10532. } else {
  10533. 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>`;
  10534. }
  10535. 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>';
  10536. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  10537. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  10538. 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>';
  10539. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  10540. // Option flags
  10541. const flags = [];
  10542. 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>');
  10543. 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>');
  10544. 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>');
  10545. 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>`);
  10546. return `
  10547. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  10548. <td class="py-3 px-4">
  10549. <div class="flex items-center gap-2">
  10550. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  10551. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  10552. </div>
  10553. </td>
  10554. <td class="py-3 px-4">${statusBadge}</td>
  10555. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  10556. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  10557. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  10558. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  10559. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  10560. <td class="py-3 px-4">
  10561. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  10562. </td>
  10563. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  10564. ${c.enabled ? `
  10565. <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>
  10566. <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>
  10567. <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>
  10568. ` : `
  10569. <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>
  10570. `}
  10571. <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>
  10572. <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>
  10573. </td>
  10574. </tr>
  10575. `;
  10576. }).join('');
  10577. }
  10578. function openDHCPClientModal(clientId = null) {
  10579. const modal = document.getElementById('modal-dhcp-client');
  10580. if (!modal) return;
  10581. const title = document.getElementById('modal-dhcp-title');
  10582. const idInput = document.getElementById('modal-dhcp-id');
  10583. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  10584. const distInput = document.getElementById('modal-dhcp-distance');
  10585. const commentInput = document.getElementById('modal-dhcp-comment');
  10586. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  10587. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  10588. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  10589. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  10590. // Populate interfaces
  10591. if (ifaceSelect) {
  10592. let opts = '<option value="">Select interface...</option>';
  10593. const allIfaces = state.interfaces || [];
  10594. const allVlans = state.vlans || [];
  10595. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  10596. // Group 1: Physical & Bridge Interfaces
  10597. opts += '<optgroup label="Physical & Bridge Interfaces">';
  10598. allIfaces.forEach(i => {
  10599. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  10600. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  10601. });
  10602. opts += '</optgroup>';
  10603. // Group 2: VLAN Interfaces
  10604. if (allVlans.length > 0) {
  10605. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  10606. allVlans.forEach(v => {
  10607. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  10608. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  10609. });
  10610. opts += '</optgroup>';
  10611. }
  10612. ifaceSelect.innerHTML = opts;
  10613. }
  10614. if (clientId) {
  10615. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  10616. if (client) {
  10617. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  10618. if (idInput) idInput.value = client.id;
  10619. if (ifaceSelect) {
  10620. ifaceSelect.value = client.interface;
  10621. ifaceSelect.disabled = true; // interface cannot be changed on edit
  10622. }
  10623. if (distInput) distInput.value = client.default_route_distance || 1;
  10624. if (commentInput) commentInput.value = client.comment || '';
  10625. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  10626. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  10627. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  10628. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  10629. }
  10630. } else {
  10631. if (title) title.innerText = 'Add DHCP Client';
  10632. if (idInput) idInput.value = '';
  10633. if (ifaceSelect) {
  10634. ifaceSelect.value = '';
  10635. ifaceSelect.disabled = false;
  10636. }
  10637. if (distInput) distInput.value = 1;
  10638. if (commentInput) commentInput.value = '';
  10639. if (defRouteCheck) defRouteCheck.checked = true;
  10640. if (peerDnsCheck) peerDnsCheck.checked = true;
  10641. if (peerNtpCheck) peerNtpCheck.checked = true;
  10642. if (enabledCheck) enabledCheck.checked = true;
  10643. }
  10644. modal.classList.remove('hidden');
  10645. }
  10646. function openDHCPClientModalForIface(ifaceName) {
  10647. openDHCPClientModal();
  10648. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  10649. if (ifaceSelect && ifaceName) {
  10650. ifaceSelect.value = ifaceName;
  10651. }
  10652. }
  10653. function closeDHCPClientModal() {
  10654. const modal = document.getElementById('modal-dhcp-client');
  10655. if (modal) modal.classList.add('hidden');
  10656. }
  10657. async function submitSaveDHCPClient(e) {
  10658. if (e) e.preventDefault();
  10659. const id = document.getElementById('modal-dhcp-id')?.value;
  10660. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  10661. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  10662. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  10663. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  10664. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  10665. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  10666. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  10667. if (!id && !iface) {
  10668. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  10669. return;
  10670. }
  10671. try {
  10672. let res;
  10673. if (id) {
  10674. // PUT update
  10675. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  10676. method: 'PUT',
  10677. headers: { 'Content-Type': 'application/json' },
  10678. body: JSON.stringify({
  10679. enabled,
  10680. add_default_route: defRoute,
  10681. default_route_distance: distance,
  10682. use_peer_dns: peerDns,
  10683. use_peer_ntp: peerNtp,
  10684. comment
  10685. })
  10686. });
  10687. } else {
  10688. // POST create
  10689. res = await fetch(`${API_BASE}/dhcp/clients`, {
  10690. method: 'POST',
  10691. headers: { 'Content-Type': 'application/json' },
  10692. body: JSON.stringify({
  10693. interface: iface,
  10694. enabled,
  10695. add_default_route: defRoute,
  10696. default_route_distance: distance,
  10697. use_peer_dns: peerDns,
  10698. use_peer_ntp: peerNtp,
  10699. comment
  10700. })
  10701. });
  10702. }
  10703. const data = await res.json();
  10704. if (!res.ok) {
  10705. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  10706. return;
  10707. }
  10708. closeDHCPClientModal();
  10709. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  10710. await loadDHCPClients();
  10711. fetchData(); // refresh interfaces list with new lease/status
  10712. } catch (err) {
  10713. showToast('Error', err.message, 'error');
  10714. }
  10715. }
  10716. async function toggleDHCPClientState(id, enabled) {
  10717. try {
  10718. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  10719. method: 'POST',
  10720. headers: { 'Content-Type': 'application/json' },
  10721. body: JSON.stringify({ enabled })
  10722. });
  10723. const data = await res.json();
  10724. if (!res.ok) {
  10725. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  10726. return;
  10727. }
  10728. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  10729. await loadDHCPClients();
  10730. fetchData();
  10731. } catch (err) {
  10732. showToast('Error', err.message, 'error');
  10733. }
  10734. }
  10735. async function renewDHCPClient(id) {
  10736. try {
  10737. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  10738. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  10739. method: 'POST'
  10740. });
  10741. const data = await res.json();
  10742. if (!res.ok) {
  10743. showToast('Error', data.error || 'Failed to renew lease', 'error');
  10744. return;
  10745. }
  10746. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  10747. setTimeout(() => {
  10748. loadDHCPClients();
  10749. fetchData();
  10750. }, 1500);
  10751. } catch (err) {
  10752. showToast('Error', err.message, 'error');
  10753. }
  10754. }
  10755. async function releaseDHCPClient(id) {
  10756. try {
  10757. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  10758. method: 'POST'
  10759. });
  10760. const data = await res.json();
  10761. if (!res.ok) {
  10762. showToast('Error', data.error || 'Failed to release lease', 'error');
  10763. return;
  10764. }
  10765. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  10766. await loadDHCPClients();
  10767. fetchData();
  10768. } catch (err) {
  10769. showToast('Error', err.message, 'error');
  10770. }
  10771. }
  10772. async function deleteDHCPClient(id, ifaceName) {
  10773. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  10774. return;
  10775. }
  10776. try {
  10777. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  10778. method: 'DELETE'
  10779. });
  10780. const data = await res.json();
  10781. if (!res.ok) {
  10782. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  10783. return;
  10784. }
  10785. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  10786. await loadDHCPClients();
  10787. fetchData();
  10788. } catch (err) {
  10789. showToast('Error', err.message, 'error');
  10790. }
  10791. }
  10792. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  10793. function initTableSorting() {
  10794. document.querySelectorAll('table').forEach(setupSortableTable);
  10795. }
  10796. function setupSortableTable(table) {
  10797. const thead = table.querySelector('thead');
  10798. const tbody = table.querySelector('tbody');
  10799. if (!thead || !tbody) return;
  10800. const headerRows = thead.querySelectorAll('tr');
  10801. if (headerRows.length === 0) return;
  10802. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  10803. ths.forEach((th, colIdx) => {
  10804. if (th._sortBound) return;
  10805. th._sortBound = true;
  10806. const rawText = th.innerText.trim().toLowerCase();
  10807. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  10808. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  10809. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  10810. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  10811. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  10812. return;
  10813. }
  10814. th.classList.add('table-sortable', 'group');
  10815. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  10816. let icon = th.querySelector('.table-sort-icon');
  10817. if (!icon) {
  10818. icon = document.createElement('span');
  10819. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  10820. icon.innerHTML = '⇅';
  10821. th.appendChild(icon);
  10822. }
  10823. th.addEventListener('click', (e) => {
  10824. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  10825. handleHeaderClick(table, th, colIdx);
  10826. });
  10827. });
  10828. if (!tbody._sortObserved) {
  10829. tbody._sortObserved = true;
  10830. let sortDebounceTimer = null;
  10831. const observer = new MutationObserver((mutations) => {
  10832. if (tbody._isSorting) return;
  10833. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  10834. if (!hasChildChanges) return;
  10835. clearTimeout(sortDebounceTimer);
  10836. sortDebounceTimer = setTimeout(() => {
  10837. if (tbody._isSorting) return;
  10838. if (table._activeSort && table._activeSort.dir !== 'none') {
  10839. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  10840. } else {
  10841. tagOriginalRowOrder(tbody);
  10842. }
  10843. }, 10);
  10844. });
  10845. observer.observe(tbody, { childList: true });
  10846. }
  10847. tagOriginalRowOrder(tbody);
  10848. }
  10849. function tagOriginalRowOrder(tbody) {
  10850. let idx = 0;
  10851. Array.from(tbody.children).forEach(tr => {
  10852. if (!tr.querySelector('td[colspan]')) {
  10853. if (!tr.hasAttribute('data-orig-idx')) {
  10854. tr.setAttribute('data-orig-idx', idx++);
  10855. }
  10856. }
  10857. });
  10858. }
  10859. function handleHeaderClick(table, th, colIdx) {
  10860. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  10861. let newDir = 'asc';
  10862. if (currentSort.colIdx === colIdx) {
  10863. if (currentSort.dir === 'asc') newDir = 'desc';
  10864. else if (currentSort.dir === 'desc') newDir = 'none';
  10865. else newDir = 'asc';
  10866. } else {
  10867. newDir = 'asc';
  10868. }
  10869. table._activeSort = { colIdx, dir: newDir };
  10870. updateHeaderIcons(table, colIdx, newDir);
  10871. applyTableSort(table, colIdx, newDir, true);
  10872. }
  10873. function updateHeaderIcons(table, activeColIdx, dir) {
  10874. const thead = table.querySelector('thead');
  10875. if (!thead) return;
  10876. const ths = thead.querySelectorAll('th');
  10877. ths.forEach((th, idx) => {
  10878. const icon = th.querySelector('.table-sort-icon');
  10879. if (!icon) return;
  10880. if (idx === activeColIdx && dir !== 'none') {
  10881. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  10882. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  10883. th.classList.add('table-sorted-active');
  10884. } else {
  10885. icon.innerHTML = '⇅';
  10886. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  10887. th.classList.remove('table-sorted-active');
  10888. }
  10889. });
  10890. }
  10891. function applyTableSort(table, colIdx, dir, userInitiated) {
  10892. const tbody = table.querySelector('tbody');
  10893. if (!tbody || tbody.children.length <= 1) return;
  10894. tbody._isSorting = true;
  10895. tagOriginalRowOrder(tbody);
  10896. // Group parent rows and any attached drawer/sub-rows
  10897. const groups = [];
  10898. let currentGroup = null;
  10899. Array.from(tbody.children).forEach(tr => {
  10900. if (tr.querySelector('td[colspan]')) {
  10901. if (currentGroup) {
  10902. currentGroup.subRows.push(tr);
  10903. } else {
  10904. groups.push({ mainRow: tr, subRows: [] });
  10905. }
  10906. } else {
  10907. currentGroup = { mainRow: tr, subRows: [] };
  10908. groups.push(currentGroup);
  10909. }
  10910. });
  10911. if (dir === 'none') {
  10912. groups.sort((a, b) => {
  10913. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  10914. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  10915. return idxA - idxB;
  10916. });
  10917. } else {
  10918. groups.sort((a, b) => {
  10919. const cellA = a.mainRow.children[colIdx];
  10920. const cellB = b.mainRow.children[colIdx];
  10921. const res = compareTableCells(cellA, cellB);
  10922. return dir === 'asc' ? res : -res;
  10923. });
  10924. }
  10925. // Re-append rows in sorted order
  10926. groups.forEach(g => {
  10927. tbody.appendChild(g.mainRow);
  10928. g.subRows.forEach(sub => tbody.appendChild(sub));
  10929. });
  10930. tbody._isSorting = false;
  10931. }
  10932. function getCellRawText(cell) {
  10933. if (!cell) return '';
  10934. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  10935. const input = cell.querySelector('input, select');
  10936. if (input) {
  10937. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  10938. return input.value;
  10939. }
  10940. return cell.innerText.trim();
  10941. }
  10942. function parseTrafficToNumber(str) {
  10943. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  10944. if (!m) return null;
  10945. const num = parseFloat(m[1].replace(/,/g, ''));
  10946. if (isNaN(num)) return null;
  10947. const unit = m[2].toUpperCase();
  10948. let mult = 1;
  10949. if (unit.startsWith('K')) mult = 1024;
  10950. else if (unit.startsWith('M')) mult = 1024 * 1024;
  10951. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  10952. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  10953. return num * mult;
  10954. }
  10955. function parseIpToNumber(str) {
  10956. const clean = str.replace(/^[!~]/, '').trim();
  10957. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  10958. if (!m) return null;
  10959. const o1 = parseInt(m[1], 10);
  10960. const o2 = parseInt(m[2], 10);
  10961. const o3 = parseInt(m[3], 10);
  10962. const o4 = parseInt(m[4], 10);
  10963. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  10964. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  10965. }
  10966. function parseCompoundPackets(str) {
  10967. const m = str.match(/^([\d,]+)p/);
  10968. if (!m) return null;
  10969. return parseInt(m[1].replace(/,/g, ''), 10);
  10970. }
  10971. function compareTableCells(cellA, cellB) {
  10972. const a = getCellRawText(cellA);
  10973. const b = getCellRawText(cellB);
  10974. if (a === '' && b !== '') return 1;
  10975. if (b === '' && a !== '') return -1;
  10976. if (a === b) return 0;
  10977. // 1. IP Addresses / CIDR
  10978. const ipA = parseIpToNumber(a);
  10979. const ipB = parseIpToNumber(b);
  10980. if (ipA !== null && ipB !== null) return ipA - ipB;
  10981. // 2. Packet counts (e.g. "1,250p / 45 KB")
  10982. const pktA = parseCompoundPackets(a);
  10983. const pktB = parseCompoundPackets(b);
  10984. if (pktA !== null && pktB !== null) return pktA - pktB;
  10985. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  10986. const trafA = parseTrafficToNumber(a);
  10987. const trafB = parseTrafficToNumber(b);
  10988. if (trafA !== null && trafB !== null) return trafA - trafB;
  10989. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  10990. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  10991. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  10992. const numA = Number(cleanNumA);
  10993. const numB = Number(cleanNumB);
  10994. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  10995. return numA - numB;
  10996. }
  10997. // 5. Natural case-insensitive string compare
  10998. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  10999. }
  11000. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  11001. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  11002. const docTableObserver = new MutationObserver((mutations) => {
  11003. let needsInit = false;
  11004. for (const m of mutations) {
  11005. for (const node of m.addedNodes) {
  11006. if (node.nodeType === 1) {
  11007. if (node.tagName === 'TABLE' || (node.querySelector && node.querySelector('table'))) {
  11008. needsInit = true;
  11009. break;
  11010. }
  11011. }
  11012. }
  11013. if (needsInit) break;
  11014. }
  11015. if (needsInit) {
  11016. initTableSorting();
  11017. }
  11018. });
  11019. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  11020. }