app.js 525 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453
  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. // ======================== PPP Profiles Shared Helper ========================
  898. async function fetchPPPProfilesList() {
  899. try {
  900. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  901. if (res.ok) {
  902. state.pppProfiles = await res.json();
  903. }
  904. } catch (err) {
  905. console.error('Failed to load PPP profiles:', err);
  906. }
  907. }
  908. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  909. const sel = document.getElementById(selectId);
  910. if (!sel) return;
  911. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  912. { name: 'default', use_encryption: 'no' },
  913. { name: 'default-encryption', use_encryption: 'required' }
  914. ];
  915. sel.innerHTML = '';
  916. profiles.forEach(p => {
  917. const opt = document.createElement('option');
  918. opt.value = p.name;
  919. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  920. opt.innerText = `${p.name}${encBadge}`;
  921. sel.appendChild(opt);
  922. });
  923. if (selectedVal) {
  924. sel.value = selectedVal;
  925. } else {
  926. sel.value = defaultVal;
  927. }
  928. if (!sel.value && sel.options.length > 0) {
  929. sel.selectedIndex = 0;
  930. }
  931. }
  932. // ======================== PPPoE Multi-Instance ========================
  933. async function loadPPPoE(populateInputs = true) {
  934. try {
  935. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  936. await fetchPPPProfilesList();
  937. }
  938. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  939. const list = await res.json();
  940. state.pppoeList = Array.isArray(list) ? list : [];
  941. const badge = document.getElementById('pppoe-count-badge');
  942. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  943. const tbody = document.getElementById('pppoe-table-body');
  944. const empty = document.getElementById('pppoe-empty');
  945. if (!tbody) return;
  946. tbody.innerHTML = '';
  947. if (state.pppoeList.length === 0) {
  948. if (empty) empty.classList.remove('hidden');
  949. } else {
  950. if (empty) empty.classList.add('hidden');
  951. state.pppoeList.forEach(inst => {
  952. const tr = document.createElement('tr');
  953. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  954. tr.innerHTML = `
  955. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  956. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  957. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  958. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  959. <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default')}</span></td>
  960. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  961. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  962. <td class="py-2.5 px-3 text-center">
  963. <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'}">
  964. ${inst.default_route ? 'Yes' : 'No'}
  965. </span>
  966. </td>
  967. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  968. ${inst.running ? `
  969. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  970. ` : `
  971. <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>
  972. `}
  973. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  974. ${inst.disabled ? 'Enable' : 'Disable'}
  975. </button>
  976. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  977. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  978. </td>
  979. `;
  980. tbody.appendChild(tr);
  981. });
  982. }
  983. } catch (err) {
  984. console.error('Failed to load PPPoE:', err);
  985. }
  986. }
  987. function openAddPPPoEModal() {
  988. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  989. document.getElementById('pppoe-modal-edit-orig').value = '';
  990. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  991. document.getElementById('pppoe-modal-name').readOnly = false;
  992. document.getElementById('pppoe-modal-user').value = '';
  993. document.getElementById('pppoe-modal-pass').value = '';
  994. document.getElementById('pppoe-modal-service').value = '';
  995. document.getElementById('pppoe-modal-mtu').value = '1492';
  996. document.getElementById('pppoe-modal-defroute').checked = true;
  997. document.getElementById('pppoe-modal-reconnect').checked = true;
  998. document.getElementById('pppoe-modal-disabled').checked = false;
  999. // Populate profiles
  1000. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1001. // Populate interfaces
  1002. const sel = document.getElementById('pppoe-modal-iface');
  1003. sel.innerHTML = '';
  1004. (state.interfaces || []).forEach(i => {
  1005. if (i.name === 'lo') return;
  1006. const opt = document.createElement('option');
  1007. opt.value = i.name;
  1008. opt.innerText = `${i.name} (${i.role || i.type})`;
  1009. sel.appendChild(opt);
  1010. });
  1011. document.getElementById('pppoe-modal').classList.remove('hidden');
  1012. }
  1013. function openEditPPPoEModal(name) {
  1014. const inst = (state.pppoeList || []).find(i => i.name === name);
  1015. if (!inst) return;
  1016. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1017. document.getElementById('pppoe-modal-edit-orig').value = name;
  1018. document.getElementById('pppoe-modal-name').value = inst.name;
  1019. document.getElementById('pppoe-modal-name').readOnly = true;
  1020. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1021. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1022. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1023. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1024. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1025. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1026. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1027. // Populate profiles
  1028. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1029. const sel = document.getElementById('pppoe-modal-iface');
  1030. sel.innerHTML = '';
  1031. (state.interfaces || []).forEach(i => {
  1032. if (i.name === 'lo') return;
  1033. const opt = document.createElement('option');
  1034. opt.value = i.name;
  1035. opt.innerText = `${i.name} (${i.role || i.type})`;
  1036. if (i.name === inst.interface) opt.selected = true;
  1037. sel.appendChild(opt);
  1038. });
  1039. document.getElementById('pppoe-modal').classList.remove('hidden');
  1040. }
  1041. function closePPPoEModal() {
  1042. document.getElementById('pppoe-modal').classList.add('hidden');
  1043. }
  1044. async function submitSavePPPoE(e) {
  1045. e.preventDefault();
  1046. const name = document.getElementById('pppoe-modal-name').value.trim();
  1047. const iface = document.getElementById('pppoe-modal-iface').value;
  1048. const user = document.getElementById('pppoe-modal-user').value.trim();
  1049. const pass = document.getElementById('pppoe-modal-pass').value;
  1050. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1051. const service = document.getElementById('pppoe-modal-service').value.trim();
  1052. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1053. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1054. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1055. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1056. try {
  1057. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1058. method: 'POST',
  1059. headers: { 'Content-Type': 'application/json' },
  1060. body: JSON.stringify({
  1061. name,
  1062. interface: iface,
  1063. username: user,
  1064. password: pass,
  1065. profile: profile,
  1066. service_name: service,
  1067. mtu,
  1068. default_route: defRoute,
  1069. auto_reconnect: reconnect,
  1070. disabled
  1071. })
  1072. });
  1073. if (res.ok) {
  1074. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1075. closePPPoEModal();
  1076. loadPPPoE(false);
  1077. fetchData(false);
  1078. } else {
  1079. const err = await res.json();
  1080. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1081. }
  1082. } catch (err) {
  1083. showToast('Error', err.message, 'error');
  1084. }
  1085. }
  1086. async function connectPPPoEInstance(name) {
  1087. try {
  1088. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1089. if (res.ok) {
  1090. showToast('Connecting', `Dialing ${name}...`, 'info');
  1091. setTimeout(() => loadPPPoE(false), 2000);
  1092. }
  1093. } catch (err) {
  1094. showToast('Error', err.message, 'error');
  1095. }
  1096. }
  1097. async function disconnectPPPoEInstance(name) {
  1098. try {
  1099. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1100. if (res.ok) {
  1101. showToast('Disconnected', `${name} session terminated`, 'info');
  1102. setTimeout(() => loadPPPoE(false), 1000);
  1103. }
  1104. } catch (err) {
  1105. showToast('Error', err.message, 'error');
  1106. }
  1107. }
  1108. async function togglePPPoEState(name, enable) {
  1109. try {
  1110. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1111. method: 'POST',
  1112. headers: { 'Content-Type': 'application/json' },
  1113. body: JSON.stringify({ enabled: enable })
  1114. });
  1115. if (res.ok) {
  1116. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1117. loadPPPoE(false);
  1118. }
  1119. } catch (err) {
  1120. showToast('Error', err.message, 'error');
  1121. }
  1122. }
  1123. async function deletePPPoEInstance(name) {
  1124. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1125. try {
  1126. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1127. if (res.ok) {
  1128. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1129. loadPPPoE(false);
  1130. fetchData(false);
  1131. }
  1132. } catch (err) {
  1133. showToast('Error', err.message, 'error');
  1134. }
  1135. }
  1136. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1137. state.wgSubTab = 'ifaces';
  1138. function switchWGSubTab(tab) {
  1139. state.wgSubTab = tab;
  1140. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1141. const peersPanel = document.getElementById('wg-subtab-peers');
  1142. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1143. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1144. if (tab === 'ifaces') {
  1145. ifacesPanel?.classList.remove('hidden');
  1146. peersPanel?.classList.add('hidden');
  1147. 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';
  1148. 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';
  1149. } else {
  1150. ifacesPanel?.classList.add('hidden');
  1151. peersPanel?.classList.remove('hidden');
  1152. 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';
  1153. 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';
  1154. renderWGPeers();
  1155. }
  1156. }
  1157. async function loadWireGuard(populateInputs = true) {
  1158. try {
  1159. const [ifacesRes, peersRes] = await Promise.all([
  1160. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1161. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1162. ]);
  1163. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1164. const peers = peersRes.ok ? await peersRes.json() : [];
  1165. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1166. state.wgPeers = Array.isArray(peers) ? peers : [];
  1167. // Badges
  1168. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1169. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1170. const peersCountBadge = document.getElementById('wg-peers-count');
  1171. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1172. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1173. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1174. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1175. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1176. // Render Interfaces
  1177. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1178. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1179. if (ifacesTbody) {
  1180. ifacesTbody.innerHTML = '';
  1181. if (state.wgInterfaces.length === 0) {
  1182. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1183. } else {
  1184. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1185. state.wgInterfaces.forEach(iface => {
  1186. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1187. const tr = document.createElement('tr');
  1188. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1189. tr.innerHTML = `
  1190. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1191. <td class="py-2.5 px-3">
  1192. <div class="flex items-center gap-1.5">
  1193. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1194. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1195. </div>
  1196. </td>
  1197. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1198. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1199. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1200. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1201. ${(iface.public_key || '').substring(0, 10)}... 📋
  1202. </span>
  1203. </td>
  1204. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1205. <td class="py-2.5 px-3 text-center">
  1206. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1207. </td>
  1208. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1209. ${iface.running ? `
  1210. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1211. ` : `
  1212. <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>
  1213. `}
  1214. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1215. ${iface.disabled ? 'Enable' : 'Disable'}
  1216. </button>
  1217. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1218. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1219. </td>
  1220. `;
  1221. ifacesTbody.appendChild(tr);
  1222. });
  1223. }
  1224. }
  1225. // Populate filter dropdown in peers tab
  1226. const filterSel = document.getElementById('wg-peers-filter-iface');
  1227. if (filterSel) {
  1228. const currentVal = filterSel.value;
  1229. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1230. state.wgInterfaces.forEach(i => {
  1231. const opt = document.createElement('option');
  1232. opt.value = i.name;
  1233. opt.innerText = i.name;
  1234. if (i.name === currentVal) opt.selected = true;
  1235. filterSel.appendChild(opt);
  1236. });
  1237. }
  1238. renderWGPeers();
  1239. } catch (err) {
  1240. console.error('Failed to load WireGuard:', err);
  1241. }
  1242. }
  1243. function renderWGPeers() {
  1244. const filterSel = document.getElementById('wg-peers-filter-iface');
  1245. const selectedIface = filterSel ? filterSel.value : '';
  1246. const tbody = document.getElementById('wg-peers-table-body');
  1247. const empty = document.getElementById('wg-peers-empty');
  1248. if (!tbody) return;
  1249. tbody.innerHTML = '';
  1250. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1251. if (filtered.length === 0) {
  1252. if (empty) empty.classList.remove('hidden');
  1253. } else {
  1254. if (empty) empty.classList.add('hidden');
  1255. filtered.forEach(p => {
  1256. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1257. const tr = document.createElement('tr');
  1258. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1259. tr.innerHTML = `
  1260. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1261. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1262. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1263. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1264. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1265. ${(p.public_key || '').substring(0, 10)}... 📋
  1266. </span>
  1267. </td>
  1268. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1269. <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>
  1270. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1271. <td class="py-2.5 px-3 font-mono text-[11px]">
  1272. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1273. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1274. </td>
  1275. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1276. <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">
  1277. ${p.disabled ? 'Enable' : 'Disable'}
  1278. </button>
  1279. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1280. <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>
  1281. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1282. </td>
  1283. `;
  1284. tbody.appendChild(tr);
  1285. });
  1286. }
  1287. }
  1288. function openAddWGInterfaceModal() {
  1289. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1290. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1291. const nameEl = document.getElementById('wg-iface-modal-name');
  1292. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1293. nameEl.readOnly = false;
  1294. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1295. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1296. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1297. document.getElementById('wg-iface-modal-comment').value = '';
  1298. document.getElementById('wg-iface-modal-pubkey').value = '';
  1299. document.getElementById('wg-iface-modal-privkey').value = '';
  1300. document.getElementById('wg-iface-modal-disabled').checked = false;
  1301. generateWGInterfaceKeys();
  1302. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1303. }
  1304. function openEditWGInterfaceModal(name) {
  1305. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1306. if (!iface) return;
  1307. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1308. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1309. const nameEl = document.getElementById('wg-iface-modal-name');
  1310. nameEl.value = iface.name;
  1311. nameEl.readOnly = false; // ALLOW RENAMING
  1312. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1313. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1314. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1315. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1316. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1317. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1318. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1319. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1320. }
  1321. function closeAddWGInterfaceModal() {
  1322. document.getElementById('wg-iface-modal').classList.add('hidden');
  1323. }
  1324. async function generateWGInterfaceKeys() {
  1325. try {
  1326. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1327. const keys = await res.json();
  1328. if (res.ok) {
  1329. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1330. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1331. }
  1332. } catch (err) {
  1333. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1334. }
  1335. }
  1336. async function onWGInterfacePrivKeyInput() {
  1337. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1338. if (!privKey) return;
  1339. try {
  1340. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1341. method: 'POST',
  1342. headers: { 'Content-Type': 'application/json' },
  1343. body: JSON.stringify({ private_key: privKey })
  1344. });
  1345. if (res.ok) {
  1346. const data = await res.json();
  1347. if (data.public_key) {
  1348. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1349. }
  1350. }
  1351. } catch (err) {
  1352. // Ignore while typing
  1353. }
  1354. }
  1355. function toggleWGPrivKeyVisibility() {
  1356. const el = document.getElementById('wg-iface-modal-privkey');
  1357. const btn = document.getElementById('btn-toggle-wg-privkey');
  1358. if (el.type === 'password') {
  1359. el.type = 'text';
  1360. btn.innerText = '🙈 Hide';
  1361. } else {
  1362. el.type = 'password';
  1363. btn.innerText = '👁️ Show';
  1364. }
  1365. }
  1366. function copyWGInterfacePubKey() {
  1367. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1368. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1369. }
  1370. async function submitSaveWGInterface(e) {
  1371. e.preventDefault();
  1372. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1373. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1374. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1375. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1376. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1377. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1378. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1379. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1380. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1381. try {
  1382. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1383. method: 'POST',
  1384. headers: { 'Content-Type': 'application/json' },
  1385. body: JSON.stringify({
  1386. orig_name: origName,
  1387. name,
  1388. listen_port: port,
  1389. address: addr,
  1390. mtu,
  1391. comment,
  1392. public_key: pub,
  1393. private_key: priv,
  1394. disabled
  1395. })
  1396. });
  1397. const data = await res.json();
  1398. if (res.ok) {
  1399. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1400. closeAddWGInterfaceModal();
  1401. loadWireGuard(false);
  1402. fetchData(false);
  1403. } else {
  1404. showToast('Error', data.error || 'Failed to save interface', 'error');
  1405. }
  1406. } catch (err) {
  1407. showToast('Error', err.message, 'error');
  1408. }
  1409. }
  1410. async function startWGInterface(name) {
  1411. try {
  1412. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1413. if (res.ok) {
  1414. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1415. loadWireGuard(false);
  1416. fetchData(false);
  1417. }
  1418. } catch (err) {
  1419. showToast('Error', err.message, 'error');
  1420. }
  1421. }
  1422. async function stopWGInterface(name) {
  1423. try {
  1424. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1425. if (res.ok) {
  1426. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1427. loadWireGuard(false);
  1428. fetchData(false);
  1429. }
  1430. } catch (err) {
  1431. showToast('Error', err.message, 'error');
  1432. }
  1433. }
  1434. async function toggleWGInterfaceState(name, enable) {
  1435. try {
  1436. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1437. method: 'POST',
  1438. headers: { 'Content-Type': 'application/json' },
  1439. body: JSON.stringify({ enabled: enable })
  1440. });
  1441. if (res.ok) {
  1442. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1443. loadWireGuard(false);
  1444. fetchData(false);
  1445. }
  1446. } catch (err) {
  1447. showToast('Error', err.message, 'error');
  1448. }
  1449. }
  1450. async function deleteWGInterface(name) {
  1451. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1452. try {
  1453. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1454. if (res.ok) {
  1455. showToast('Deleted', `Interface ${name} removed`, 'success');
  1456. loadWireGuard(false);
  1457. fetchData(false);
  1458. }
  1459. } catch (err) {
  1460. showToast('Error', err.message, 'error');
  1461. }
  1462. }
  1463. function populateWGPeerIfaceSelect(selectedIface = '') {
  1464. const sel = document.getElementById('wg-peer-modal-iface');
  1465. if (!sel) return;
  1466. sel.innerHTML = '';
  1467. (state.wgInterfaces || []).forEach(i => {
  1468. const opt = document.createElement('option');
  1469. opt.value = i.name;
  1470. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1471. if (i.name === selectedIface) opt.selected = true;
  1472. sel.appendChild(opt);
  1473. });
  1474. }
  1475. function openAddWGPeerModal() {
  1476. if ((state.wgInterfaces || []).length === 0) {
  1477. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1478. openAddWGInterfaceModal();
  1479. return;
  1480. }
  1481. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  1482. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  1483. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  1484. populateWGPeerIfaceSelect();
  1485. document.getElementById('wg-peer-modal-name').value = '';
  1486. document.getElementById('wg-peer-modal-pubkey').value = '';
  1487. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1488. document.getElementById('wg-peer-modal-endpoint').value = '';
  1489. document.getElementById('wg-peer-modal-port').value = '';
  1490. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1491. document.getElementById('wg-peer-modal-preshared').value = '';
  1492. document.getElementById('wg-peer-modal-disabled').checked = false;
  1493. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1494. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1495. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1496. }
  1497. function openEditWGPeerModal(ifaceName, pubKey) {
  1498. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  1499. if (!peer) {
  1500. showToast('Not Found', 'Peer not found', 'warning');
  1501. return;
  1502. }
  1503. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  1504. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  1505. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  1506. populateWGPeerIfaceSelect(peer.interface);
  1507. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  1508. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  1509. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  1510. document.getElementById('wg-peer-modal-endpoint').value = peer.endpoint_address || '';
  1511. document.getElementById('wg-peer-modal-port').value = peer.endpoint_port || '';
  1512. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  1513. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  1514. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  1515. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1516. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1517. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1518. }
  1519. function closeAddWGPeerModal() {
  1520. document.getElementById('wg-peer-modal').classList.add('hidden');
  1521. }
  1522. async function generatePeerKeypairHelper() {
  1523. try {
  1524. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1525. const keys = await res.json();
  1526. if (res.ok) {
  1527. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  1528. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  1529. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  1530. checkWGPeerKeyValidity();
  1531. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  1532. }
  1533. } catch (err) {
  1534. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1535. }
  1536. }
  1537. function copyGeneratedPeerPrivKey() {
  1538. const priv = document.getElementById('wg-peer-gen-privkey').value;
  1539. if (priv) copyToClipboard(priv, 'Client Private Key');
  1540. }
  1541. async function generatePeerPSK() {
  1542. try {
  1543. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1544. const keys = await res.json();
  1545. if (res.ok && keys.private_key) {
  1546. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  1547. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  1548. }
  1549. } catch (err) {
  1550. showToast('Error', err.message, 'error');
  1551. }
  1552. }
  1553. function checkWGPeerKeyValidity() {
  1554. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  1555. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1556. const warningEl = document.getElementById('wg-peer-key-warning');
  1557. if (!warningEl) return;
  1558. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  1559. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  1560. warningEl.classList.remove('hidden');
  1561. } else {
  1562. warningEl.classList.add('hidden');
  1563. }
  1564. }
  1565. async function submitSaveWGPeer(e) {
  1566. e.preventDefault();
  1567. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  1568. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  1569. const iface = document.getElementById('wg-peer-modal-iface').value;
  1570. const name = document.getElementById('wg-peer-modal-name').value.trim();
  1571. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1572. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  1573. .split(',')
  1574. .map(s => s.trim())
  1575. .filter(s => s.length > 0);
  1576. const epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  1577. const epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  1578. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  1579. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  1580. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  1581. // Validation
  1582. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  1583. if (targetIface && targetIface.public_key === pub) {
  1584. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  1585. return;
  1586. }
  1587. try {
  1588. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  1589. method: 'POST',
  1590. headers: { 'Content-Type': 'application/json' },
  1591. body: JSON.stringify({
  1592. orig_interface: origIface,
  1593. orig_public_key: origPubKey,
  1594. interface: iface,
  1595. name,
  1596. public_key: pub,
  1597. allowed_ips: allowed,
  1598. endpoint_address: epHost,
  1599. endpoint_port: epPort,
  1600. persistent_keepalive: keepalive,
  1601. preshared_key: psk,
  1602. disabled
  1603. })
  1604. });
  1605. const data = await res.json();
  1606. if (res.ok) {
  1607. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  1608. closeAddWGPeerModal();
  1609. loadWireGuard(false);
  1610. } else {
  1611. showToast('Error', data.error || 'Failed to save peer', 'error');
  1612. }
  1613. } catch (err) {
  1614. showToast('Error', err.message, 'error');
  1615. }
  1616. }
  1617. async function toggleWGPeerState(iface, pubkey, enable) {
  1618. try {
  1619. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  1620. method: 'POST',
  1621. headers: { 'Content-Type': 'application/json' },
  1622. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  1623. });
  1624. const data = await res.json();
  1625. if (res.ok) {
  1626. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  1627. loadWireGuard(false);
  1628. } else {
  1629. showToast('Error', data.error || 'Failed to update peer state', 'error');
  1630. }
  1631. } catch (err) {
  1632. showToast('Error', err.message, 'error');
  1633. }
  1634. }
  1635. async function deleteWGPeer(iface, pubkey) {
  1636. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  1637. try {
  1638. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  1639. method: 'POST',
  1640. headers: { 'Content-Type': 'application/json' },
  1641. body: JSON.stringify({ interface: iface, public_key: pubkey })
  1642. });
  1643. const data = await res.json();
  1644. if (res.ok) {
  1645. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  1646. loadWireGuard(false);
  1647. } else {
  1648. showToast('Error', data.error || 'Failed to remove peer', 'error');
  1649. }
  1650. } catch (err) {
  1651. showToast('Error', err.message, 'error');
  1652. }
  1653. }
  1654. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  1655. function switchIpsecModalTab(tab) {
  1656. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  1657. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  1658. const p1Content = document.getElementById('ipsec-tab-content-p1');
  1659. const p2Content = document.getElementById('ipsec-tab-content-p2');
  1660. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  1661. if (tab === 'p1') {
  1662. if (p1Tab) {
  1663. 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';
  1664. }
  1665. if (p2Tab) {
  1666. 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';
  1667. }
  1668. if (p1Content) p1Content.classList.remove('hidden');
  1669. if (p2Content) p2Content.classList.add('hidden');
  1670. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  1671. } else {
  1672. if (p1Tab) {
  1673. 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';
  1674. }
  1675. if (p2Tab) {
  1676. 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';
  1677. }
  1678. if (p1Content) p1Content.classList.add('hidden');
  1679. if (p2Content) p2Content.classList.remove('hidden');
  1680. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  1681. }
  1682. }
  1683. function toggleIpsecPhaseStep() {
  1684. const p1Content = document.getElementById('ipsec-tab-content-p1');
  1685. if (p1Content && !p1Content.classList.contains('hidden')) {
  1686. switchIpsecModalTab('p2');
  1687. } else {
  1688. switchIpsecModalTab('p1');
  1689. }
  1690. }
  1691. function toggleIpsecPskVisibility() {
  1692. const pskInput = document.getElementById('ipsec-modal-psk');
  1693. if (!pskInput) return;
  1694. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  1695. }
  1696. function addIpsecLocalSubnet(val = '') {
  1697. const container = document.getElementById('ipsec-modal-local-subnets-container');
  1698. if (!container) return;
  1699. const row = document.createElement('div');
  1700. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  1701. row.innerHTML = `
  1702. <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">
  1703. <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>
  1704. `;
  1705. container.appendChild(row);
  1706. }
  1707. function addIpsecRemoteSubnet(val = '') {
  1708. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  1709. if (!container) return;
  1710. const row = document.createElement('div');
  1711. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  1712. row.innerHTML = `
  1713. <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">
  1714. <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>
  1715. `;
  1716. container.appendChild(row);
  1717. }
  1718. function updateIpsecEspProposalFromPFS(val) {
  1719. const prop = document.getElementById('ipsec-modal-espprop');
  1720. if (!prop) return;
  1721. if (val === 'none') {
  1722. prop.value = 'aes256-sha256,aes128-sha256,default';
  1723. } else {
  1724. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  1725. }
  1726. }
  1727. function updateIpsecIkeProposalFromDH(dh) {
  1728. const el = document.getElementById('ipsec-modal-ikeprop');
  1729. if (el) {
  1730. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  1731. }
  1732. }
  1733. function safeSetVal(id, val) {
  1734. const el = document.getElementById(id);
  1735. if (el) el.value = val;
  1736. }
  1737. function safeSetChecked(id, val) {
  1738. const el = document.getElementById(id);
  1739. if (el) el.checked = !!val;
  1740. }
  1741. function safeGetVal(id, def = '') {
  1742. const el = document.getElementById(id);
  1743. return el ? el.value : def;
  1744. }
  1745. async function loadIPSec(populateInputs = true) {
  1746. try {
  1747. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1748. const list = await res.json();
  1749. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1750. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1751. const badge = document.getElementById('ipsec-sas-badge');
  1752. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1753. const tbody = document.getElementById('ipsec-table-body');
  1754. const empty = document.getElementById('ipsec-empty');
  1755. if (!tbody) return;
  1756. tbody.innerHTML = '';
  1757. if (state.ipsecTunnels.length === 0) {
  1758. if (empty) empty.classList.remove('hidden');
  1759. } else {
  1760. if (empty) empty.classList.add('hidden');
  1761. state.ipsecTunnels.forEach(c => {
  1762. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1763. const tr = document.createElement('tr');
  1764. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  1765. // Local subnets tags
  1766. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  1767. 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('');
  1768. // Remote subnets tags
  1769. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  1770. 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('');
  1771. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  1772. const p2Name = c.phase2_name || `${c.name}_p2`;
  1773. tr.innerHTML = `
  1774. <td class="py-2.5 px-3 text-center">
  1775. ${isEstablished ? `
  1776. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  1777. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  1778. <span>UP</span>
  1779. </span>
  1780. ` : (c.disabled ? `
  1781. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  1782. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  1783. <span>DOWN</span>
  1784. </span>
  1785. ` : `
  1786. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  1787. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  1788. <span>IDLE</span>
  1789. </span>
  1790. `)}
  1791. </td>
  1792. <td class="py-2.5 px-4 font-bold text-white">
  1793. <div class="flex items-center gap-2">
  1794. <span class="text-amber-400">🛡</span>
  1795. <div>
  1796. <div>${escapeHtml(c.name)}</div>
  1797. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  1798. </div>
  1799. </div>
  1800. </td>
  1801. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  1802. <td class="py-2.5 px-4 font-sans">
  1803. <div class="flex items-center gap-1.5">
  1804. <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>
  1805. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  1806. </div>
  1807. </td>
  1808. <td class="py-2.5 px-4">
  1809. <div class="space-y-1">
  1810. <div class="flex items-center flex-wrap gap-1">
  1811. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  1812. ${localBadges}
  1813. </div>
  1814. <div class="flex items-center flex-wrap gap-1">
  1815. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  1816. ${remoteBadges}
  1817. </div>
  1818. </div>
  1819. </td>
  1820. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  1821. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  1822. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  1823. </div>
  1824. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  1825. </td>
  1826. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  1827. ${isEstablished ? `
  1828. <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>
  1829. ` : `
  1830. <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>
  1831. `}
  1832. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1833. ${c.disabled ? 'Enable' : 'Disable'}
  1834. </button>
  1835. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  1836. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1837. </td>
  1838. `;
  1839. tbody.appendChild(tr);
  1840. });
  1841. }
  1842. } catch (err) {
  1843. console.error('Failed to load IPSec:', err);
  1844. }
  1845. }
  1846. function openAddIPSecModal() {
  1847. const modal = document.getElementById('ipsec-modal');
  1848. if (!modal) return;
  1849. const title = document.getElementById('ipsec-modal-title');
  1850. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  1851. // Phase 1 Fields
  1852. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  1853. const nameEl = document.getElementById('ipsec-modal-name');
  1854. if (nameEl) nameEl.readOnly = false;
  1855. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  1856. safeSetVal('ipsec-modal-ikever', 'ikev2');
  1857. safeSetVal('ipsec-modal-remotegw', '');
  1858. safeSetVal('ipsec-modal-localaddrs', '');
  1859. safeSetVal('ipsec-modal-comments', '');
  1860. safeSetVal('ipsec-modal-psk', '');
  1861. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  1862. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  1863. safeSetVal('ipsec-modal-ikekeylife', '86400');
  1864. safeSetVal('ipsec-modal-localid', '');
  1865. safeSetVal('ipsec-modal-remoteid', '');
  1866. safeSetVal('ipsec-modal-dpd', 'on-demand');
  1867. // Phase 2 Fields
  1868. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  1869. safeSetVal('ipsec-modal-espkeylife', '28800');
  1870. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  1871. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  1872. safeSetChecked('ipsec-modal-autostart', true);
  1873. safeSetChecked('ipsec-modal-disabled', false);
  1874. // Clear & Populate default dynamic subnets
  1875. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  1876. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  1877. if (localContainer) {
  1878. localContainer.innerHTML = '';
  1879. addIpsecLocalSubnet('192.168.10.0/24');
  1880. }
  1881. if (remoteContainer) {
  1882. remoteContainer.innerHTML = '';
  1883. addIpsecRemoteSubnet('192.168.20.0/24');
  1884. }
  1885. switchIpsecModalTab('p1');
  1886. modal.classList.remove('hidden');
  1887. }
  1888. function openEditIPSecModal(name) {
  1889. const modal = document.getElementById('ipsec-modal');
  1890. if (!modal) return;
  1891. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  1892. if (!conn) return;
  1893. const title = document.getElementById('ipsec-modal-title');
  1894. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  1895. // Phase 1 Fields
  1896. safeSetVal('ipsec-modal-name', conn.name);
  1897. const nameEl = document.getElementById('ipsec-modal-name');
  1898. if (nameEl) nameEl.readOnly = true;
  1899. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  1900. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  1901. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  1902. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  1903. safeSetVal('ipsec-modal-comments', conn.comment || '');
  1904. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  1905. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  1906. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  1907. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  1908. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  1909. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  1910. // Phase 2 Fields
  1911. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  1912. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  1913. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  1914. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  1915. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  1916. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  1917. // Populate dynamic subnets
  1918. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  1919. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  1920. if (localContainer) {
  1921. localContainer.innerHTML = '';
  1922. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  1923. locals.forEach(s => addIpsecLocalSubnet(s));
  1924. }
  1925. if (remoteContainer) {
  1926. remoteContainer.innerHTML = '';
  1927. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  1928. remotes.forEach(s => addIpsecRemoteSubnet(s));
  1929. }
  1930. switchIpsecModalTab('p1');
  1931. modal.classList.remove('hidden');
  1932. }
  1933. function closeAddIPSecModal() {
  1934. const modal = document.getElementById('ipsec-modal');
  1935. if (modal) modal.classList.add('hidden');
  1936. }
  1937. async function submitSaveIPSec(e) {
  1938. if (e) e.preventDefault();
  1939. const name = safeGetVal('ipsec-modal-name').trim();
  1940. if (!name) {
  1941. showToast('Error', 'Tunnel name is required', 'error');
  1942. return;
  1943. }
  1944. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  1945. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  1946. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  1947. const comments = safeGetVal('ipsec-modal-comments').trim();
  1948. const psk = safeGetVal('ipsec-modal-psk');
  1949. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  1950. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  1951. const localId = safeGetVal('ipsec-modal-localid').trim();
  1952. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  1953. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  1954. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  1955. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  1956. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  1957. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  1958. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  1959. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  1960. // Scrape dynamic local and remote subnets
  1961. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  1962. const localSubnets = [];
  1963. localInputs.forEach(inp => {
  1964. const v = inp.value.trim();
  1965. if (v) localSubnets.push(v);
  1966. });
  1967. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  1968. const remoteSubnets = [];
  1969. remoteInputs.forEach(inp => {
  1970. const v = inp.value.trim();
  1971. if (v) remoteSubnets.push(v);
  1972. });
  1973. try {
  1974. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  1975. method: 'POST',
  1976. headers: { 'Content-Type': 'application/json' },
  1977. body: JSON.stringify({
  1978. name,
  1979. comment: comments,
  1980. ike_version: ikeVersion,
  1981. local_addrs: localAddrs,
  1982. remote_addrs: remotegw,
  1983. preshared_key: psk,
  1984. ike_proposals: ikeProposals,
  1985. ike_keylife: ikeKeylife,
  1986. local_id: localId,
  1987. remote_id: remoteId,
  1988. dpd: dpd,
  1989. phase2_name: phase2Name,
  1990. esp_proposals: espProposals,
  1991. esp_keylife: espKeylife,
  1992. pfs_group: pfsGroup,
  1993. pfs: pfsGroup !== 'none',
  1994. local_subnets: localSubnets,
  1995. remote_subnets: remoteSubnets,
  1996. local_subnet: localSubnets[0] || '0.0.0.0/0',
  1997. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  1998. auto_start: autostart,
  1999. disabled
  2000. })
  2001. });
  2002. if (res.ok) {
  2003. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2004. closeAddIPSecModal();
  2005. loadIPSec(false);
  2006. } else {
  2007. const err = await res.json();
  2008. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2009. }
  2010. } catch (err) {
  2011. showToast('Error', err.message, 'error');
  2012. }
  2013. }
  2014. async function startIPSecTunnel(name) {
  2015. try {
  2016. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2017. if (res.ok) {
  2018. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2019. setTimeout(() => loadIPSec(false), 2000);
  2020. }
  2021. } catch (err) {
  2022. showToast('Error', err.message, 'error');
  2023. }
  2024. }
  2025. async function stopIPSecTunnel(name) {
  2026. try {
  2027. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2028. if (res.ok) {
  2029. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2030. loadIPSec(false);
  2031. }
  2032. } catch (err) {
  2033. showToast('Error', err.message, 'error');
  2034. }
  2035. }
  2036. async function toggleIPSecState(name, enable) {
  2037. try {
  2038. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2039. method: 'POST',
  2040. headers: { 'Content-Type': 'application/json' },
  2041. body: JSON.stringify({ enabled: enable })
  2042. });
  2043. if (res.ok) {
  2044. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2045. loadIPSec(false);
  2046. }
  2047. } catch (err) {
  2048. showToast('Error', err.message, 'error');
  2049. }
  2050. }
  2051. async function deleteIPSecConn(name) {
  2052. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2053. try {
  2054. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2055. if (res.ok) {
  2056. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2057. loadIPSec(false);
  2058. fetchData(false);
  2059. }
  2060. } catch (err) {
  2061. showToast('Error', err.message, 'error');
  2062. }
  2063. }
  2064. // ======================== L2TP Multi-Instance ========================
  2065. async function loadL2TP(populateInputs = true) {
  2066. try {
  2067. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2068. await fetchPPPProfilesList();
  2069. }
  2070. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2071. const list = await res.json();
  2072. state.l2tpList = Array.isArray(list) ? list : [];
  2073. const badge = document.getElementById('l2tp-count-badge');
  2074. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2075. const tbody = document.getElementById('l2tp-table-body');
  2076. const empty = document.getElementById('l2tp-empty');
  2077. if (!tbody) return;
  2078. tbody.innerHTML = '';
  2079. if (state.l2tpList.length === 0) {
  2080. if (empty) empty.classList.remove('hidden');
  2081. } else {
  2082. if (empty) empty.classList.add('hidden');
  2083. state.l2tpList.forEach(inst => {
  2084. const tr = document.createElement('tr');
  2085. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2086. tr.innerHTML = `
  2087. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2088. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2089. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2090. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2091. <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default-encryption')}</span></td>
  2092. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  2093. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2094. <td class="py-2.5 px-3 text-center">
  2095. <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'}">
  2096. ${inst.default_route ? 'Yes' : 'No'}
  2097. </span>
  2098. </td>
  2099. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2100. ${inst.running ? `
  2101. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2102. ` : `
  2103. <button onclick="connectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs bg-cyan-600/30 hover:bg-cyan-600/50 text-cyan-300 px-2 py-0.5 rounded border border-cyan-500/30">Connect</button>
  2104. `}
  2105. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2106. ${inst.disabled ? 'Enable' : 'Disable'}
  2107. </button>
  2108. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2109. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2110. </td>
  2111. `;
  2112. tbody.appendChild(tr);
  2113. });
  2114. }
  2115. } catch (err) {
  2116. console.error('Failed to load L2TP:', err);
  2117. }
  2118. }
  2119. async function openAddL2TPModal() {
  2120. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2121. await fetchPPPProfilesList();
  2122. }
  2123. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2124. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2125. document.getElementById('l2tp-modal-name').readOnly = false;
  2126. document.getElementById('l2tp-modal-server').value = '';
  2127. document.getElementById('l2tp-modal-user').value = '';
  2128. document.getElementById('l2tp-modal-pass').value = '';
  2129. document.getElementById('l2tp-modal-ipsec').value = '';
  2130. document.getElementById('l2tp-modal-defroute').checked = true;
  2131. document.getElementById('l2tp-modal-disabled').checked = false;
  2132. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2133. document.getElementById('l2tp-modal').classList.remove('hidden');
  2134. }
  2135. async function openEditL2TPModal(name) {
  2136. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2137. await fetchPPPProfilesList();
  2138. }
  2139. const inst = (state.l2tpList || []).find(i => i.name === name);
  2140. if (!inst) return;
  2141. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2142. document.getElementById('l2tp-modal-name').value = inst.name;
  2143. document.getElementById('l2tp-modal-name').readOnly = true;
  2144. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2145. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2146. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2147. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2148. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2149. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2150. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2151. document.getElementById('l2tp-modal').classList.remove('hidden');
  2152. }
  2153. function closeL2TPModal() {
  2154. document.getElementById('l2tp-modal').classList.add('hidden');
  2155. }
  2156. async function submitSaveL2TP(e) {
  2157. e.preventDefault();
  2158. const name = document.getElementById('l2tp-modal-name').value.trim();
  2159. const server = document.getElementById('l2tp-modal-server').value.trim();
  2160. const user = document.getElementById('l2tp-modal-user').value.trim();
  2161. const pass = document.getElementById('l2tp-modal-pass').value;
  2162. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2163. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2164. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2165. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2166. try {
  2167. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2168. method: 'POST',
  2169. headers: { 'Content-Type': 'application/json' },
  2170. body: JSON.stringify({
  2171. name,
  2172. connect_to: server,
  2173. username: user,
  2174. password: pass,
  2175. profile: profile,
  2176. ipsec_secret: ipsec,
  2177. default_route: defRoute,
  2178. disabled
  2179. })
  2180. });
  2181. if (res.ok) {
  2182. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2183. closeL2TPModal();
  2184. loadL2TP(false);
  2185. fetchData(false);
  2186. }
  2187. } catch (err) {
  2188. showToast('Error', err.message, 'error');
  2189. }
  2190. }
  2191. async function connectL2TPInstance(name) {
  2192. try {
  2193. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2194. if (res.ok) {
  2195. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2196. setTimeout(() => loadL2TP(false), 2000);
  2197. }
  2198. } catch (err) {
  2199. showToast('Error', err.message, 'error');
  2200. }
  2201. }
  2202. async function disconnectL2TPInstance(name) {
  2203. try {
  2204. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2205. if (res.ok) {
  2206. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2207. loadL2TP(false);
  2208. }
  2209. } catch (err) {
  2210. showToast('Error', err.message, 'error');
  2211. }
  2212. }
  2213. async function toggleL2TPState(name, enable) {
  2214. try {
  2215. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2216. method: 'POST',
  2217. headers: { 'Content-Type': 'application/json' },
  2218. body: JSON.stringify({ enabled: enable })
  2219. });
  2220. if (res.ok) {
  2221. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2222. loadL2TP(false);
  2223. }
  2224. } catch (err) {
  2225. showToast('Error', err.message, 'error');
  2226. }
  2227. }
  2228. async function deleteL2TPInstance(name) {
  2229. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2230. try {
  2231. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2232. if (res.ok) {
  2233. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2234. loadL2TP(false);
  2235. fetchData(false);
  2236. }
  2237. } catch (err) {
  2238. showToast('Error', err.message, 'error');
  2239. }
  2240. }
  2241. // ======================== PPTP Multi-Instance ========================
  2242. async function loadPPTP(populateInputs = true) {
  2243. try {
  2244. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2245. await fetchPPPProfilesList();
  2246. }
  2247. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2248. const list = await res.json();
  2249. state.pptpList = Array.isArray(list) ? list : [];
  2250. const badge = document.getElementById('pptp-count-badge');
  2251. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2252. const tbody = document.getElementById('pptp-table-body');
  2253. const empty = document.getElementById('pptp-empty');
  2254. if (!tbody) return;
  2255. tbody.innerHTML = '';
  2256. if (state.pptpList.length === 0) {
  2257. if (empty) empty.classList.remove('hidden');
  2258. } else {
  2259. if (empty) empty.classList.add('hidden');
  2260. state.pptpList.forEach(inst => {
  2261. const tr = document.createElement('tr');
  2262. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2263. tr.innerHTML = `
  2264. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2265. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2266. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2267. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2268. <td class="py-2.5 px-3 font-mono text-purple-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default-encryption')}</span></td>
  2269. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  2270. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2271. <td class="py-2.5 px-3 text-center">
  2272. <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'}">
  2273. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2274. </span>
  2275. </td>
  2276. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2277. ${inst.running ? `
  2278. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2279. ` : `
  2280. <button onclick="connectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs bg-purple-600/30 hover:bg-purple-600/50 text-purple-300 px-2 py-0.5 rounded border border-purple-500/30">Connect</button>
  2281. `}
  2282. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2283. ${inst.disabled ? 'Enable' : 'Disable'}
  2284. </button>
  2285. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2286. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2287. </td>
  2288. `;
  2289. tbody.appendChild(tr);
  2290. });
  2291. }
  2292. } catch (err) {
  2293. console.error('Failed to load PPTP:', err);
  2294. }
  2295. }
  2296. async function openAddPPTPModal() {
  2297. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2298. await fetchPPPProfilesList();
  2299. }
  2300. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2301. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2302. document.getElementById('pptp-modal-name').readOnly = false;
  2303. document.getElementById('pptp-modal-server').value = '';
  2304. document.getElementById('pptp-modal-user').value = '';
  2305. document.getElementById('pptp-modal-pass').value = '';
  2306. document.getElementById('pptp-modal-mppe').checked = true;
  2307. document.getElementById('pptp-modal-defroute').checked = true;
  2308. document.getElementById('pptp-modal-disabled').checked = false;
  2309. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2310. document.getElementById('pptp-modal').classList.remove('hidden');
  2311. }
  2312. async function openEditPPTPModal(name) {
  2313. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2314. await fetchPPPProfilesList();
  2315. }
  2316. const inst = (state.pptpList || []).find(i => i.name === name);
  2317. if (!inst) return;
  2318. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2319. document.getElementById('pptp-modal-name').value = inst.name;
  2320. document.getElementById('pptp-modal-name').readOnly = true;
  2321. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2322. document.getElementById('pptp-modal-user').value = inst.username || '';
  2323. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2324. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2325. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2326. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2327. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2328. document.getElementById('pptp-modal').classList.remove('hidden');
  2329. }
  2330. function closePPTPModal() {
  2331. document.getElementById('pptp-modal').classList.add('hidden');
  2332. }
  2333. async function submitSavePPTP(e) {
  2334. e.preventDefault();
  2335. const name = document.getElementById('pptp-modal-name').value.trim();
  2336. const server = document.getElementById('pptp-modal-server').value.trim();
  2337. const user = document.getElementById('pptp-modal-user').value.trim();
  2338. const pass = document.getElementById('pptp-modal-pass').value;
  2339. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  2340. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2341. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2342. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2343. try {
  2344. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2345. method: 'POST',
  2346. headers: { 'Content-Type': 'application/json' },
  2347. body: JSON.stringify({
  2348. name,
  2349. connect_to: server,
  2350. username: user,
  2351. password: pass,
  2352. profile: profile,
  2353. require_mppe: mppe,
  2354. default_route: defRoute,
  2355. auto_reconnect: true,
  2356. disabled
  2357. })
  2358. });
  2359. if (res.ok) {
  2360. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2361. closePPTPModal();
  2362. loadPPTP(false);
  2363. fetchData(false);
  2364. }
  2365. } catch (err) {
  2366. showToast('Error', err.message, 'error');
  2367. }
  2368. }
  2369. async function connectPPTPInstance(name) {
  2370. try {
  2371. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2372. if (res.ok) {
  2373. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2374. setTimeout(() => loadPPTP(false), 2000);
  2375. }
  2376. } catch (err) {
  2377. showToast('Error', err.message, 'error');
  2378. }
  2379. }
  2380. async function disconnectPPTPInstance(name) {
  2381. try {
  2382. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2383. if (res.ok) {
  2384. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2385. loadPPTP(false);
  2386. }
  2387. } catch (err) {
  2388. showToast('Error', err.message, 'error');
  2389. }
  2390. }
  2391. async function togglePPTPState(name, enable) {
  2392. try {
  2393. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2394. method: 'POST',
  2395. headers: { 'Content-Type': 'application/json' },
  2396. body: JSON.stringify({ enabled: enable })
  2397. });
  2398. if (res.ok) {
  2399. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2400. loadPPTP(false);
  2401. }
  2402. } catch (err) {
  2403. showToast('Error', err.message, 'error');
  2404. }
  2405. }
  2406. async function deletePPTPInstance(name) {
  2407. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2408. try {
  2409. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2410. if (res.ok) {
  2411. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2412. loadPPTP(false);
  2413. fetchData(false);
  2414. }
  2415. } catch (err) {
  2416. showToast('Error', err.message, 'error');
  2417. }
  2418. }
  2419. // ---------------- Modal & Helper Functions ----------------
  2420. function openVlanModal(defaultParent = '') {
  2421. const select = document.getElementById('vlan-parent');
  2422. select.innerHTML = '';
  2423. const allIfaces = state.interfaces || [];
  2424. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2425. if (eligible.length === 0) {
  2426. const opt = document.createElement('option');
  2427. opt.value = '';
  2428. opt.innerText = 'No VLAN-capable interfaces available';
  2429. select.appendChild(opt);
  2430. } else {
  2431. eligible.forEach(i => {
  2432. const opt = document.createElement('option');
  2433. opt.value = i.name;
  2434. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2435. if (i.name === defaultParent) opt.selected = true;
  2436. select.appendChild(opt);
  2437. });
  2438. }
  2439. document.getElementById('vlan-id').value = '';
  2440. document.getElementById('vlan-name').value = '';
  2441. document.getElementById('vlan-ip').value = '';
  2442. document.getElementById('vlan-desc').value = '';
  2443. autoSuggestVlanName();
  2444. document.getElementById('vlan-modal').classList.remove('hidden');
  2445. }
  2446. function closeVlanModal() {
  2447. document.getElementById('vlan-modal').classList.add('hidden');
  2448. }
  2449. function autoSuggestVlanName() {
  2450. const parent = document.getElementById('vlan-parent').value;
  2451. if (!parent) return;
  2452. const id = document.getElementById('vlan-id').value;
  2453. const nameInput = document.getElementById('vlan-name');
  2454. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  2455. }
  2456. function setSubnetPreset(cidr) {
  2457. const ipInput = document.getElementById('vlan-ip');
  2458. const id = document.getElementById('vlan-id').value || '10';
  2459. ipInput.value = `192.168.${id}.1${cidr}`;
  2460. }
  2461. async function submitCreateVlan(e) {
  2462. e.preventDefault();
  2463. const btn = document.getElementById('vlan-submit-btn');
  2464. btn.disabled = true;
  2465. btn.innerText = 'Creating...';
  2466. const parent = document.getElementById('vlan-parent').value;
  2467. if (!parent) {
  2468. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  2469. btn.disabled = false;
  2470. btn.innerText = 'Create VLAN';
  2471. return;
  2472. }
  2473. const id = parseInt(document.getElementById('vlan-id').value, 10);
  2474. const name = document.getElementById('vlan-name').value.trim();
  2475. const ip = document.getElementById('vlan-ip').value.trim();
  2476. const role = document.getElementById('vlan-role').value;
  2477. const desc = document.getElementById('vlan-desc').value.trim();
  2478. try {
  2479. const res = await fetch(`${API_BASE}/vlans`, {
  2480. method: 'POST',
  2481. headers: { 'Content-Type': 'application/json' },
  2482. body: JSON.stringify({
  2483. parent_name: parent,
  2484. vlan_id: id,
  2485. name: name,
  2486. ip_address: ip,
  2487. role: role,
  2488. description: desc,
  2489. mtu: 1500,
  2490. auto_up: true
  2491. })
  2492. });
  2493. const data = await res.json();
  2494. if (res.ok) {
  2495. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  2496. state.expandedParents.add(parent);
  2497. closeVlanModal();
  2498. await fetchData(true);
  2499. if (state.activeTab !== 'interfaces') navigate('interfaces');
  2500. } else {
  2501. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  2502. }
  2503. } catch (err) {
  2504. showToast('Error', err.message, 'error');
  2505. } finally {
  2506. btn.disabled = false;
  2507. btn.innerText = 'Create VLAN';
  2508. }
  2509. }
  2510. async function confirmDeleteVlan(name) {
  2511. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  2512. try {
  2513. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2514. if (res.ok) {
  2515. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  2516. closeIfaceModal();
  2517. fetchData(true);
  2518. }
  2519. } catch (err) {
  2520. showToast('Error', err.message, 'error');
  2521. }
  2522. }
  2523. function openIfaceModal(name) {
  2524. const iface = (state.interfaces || []).find(i => i.name === name);
  2525. if (!iface) return;
  2526. state.currentModalIface = iface.name;
  2527. document.getElementById('modal-iface-name').innerText = iface.name;
  2528. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  2529. document.getElementById('modal-iface-mtu').value = iface.mtu;
  2530. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  2531. document.getElementById('modal-iface-desc').value = iface.description || '';
  2532. const delBtn = document.getElementById('modal-delete-vlan-btn');
  2533. if (iface.is_vlan) {
  2534. delBtn.classList.remove('hidden');
  2535. } else {
  2536. delBtn.classList.add('hidden');
  2537. }
  2538. renderModalIPs(iface);
  2539. document.getElementById('iface-modal').classList.remove('hidden');
  2540. }
  2541. function renderModalIPs(iface) {
  2542. const container = document.getElementById('modal-ip-list');
  2543. container.innerHTML = '';
  2544. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  2545. if (addrs.length === 0) {
  2546. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  2547. return;
  2548. }
  2549. addrs.forEach(addr => {
  2550. const row = document.createElement('div');
  2551. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  2552. row.innerHTML = `
  2553. <span class="text-white">${addr}</span>
  2554. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  2555. `;
  2556. container.appendChild(row);
  2557. });
  2558. }
  2559. function closeIfaceModal() {
  2560. document.getElementById('iface-modal').classList.add('hidden');
  2561. state.currentModalIface = null;
  2562. }
  2563. async function setIfaceState(name, newState) {
  2564. await toggleInterfaceState(name, newState);
  2565. const updated = (state.interfaces || []).find(i => i.name === name);
  2566. if (updated) openIfaceModal(name);
  2567. }
  2568. async function applyMTU() {
  2569. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  2570. try {
  2571. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  2572. method: 'POST',
  2573. headers: { 'Content-Type': 'application/json' },
  2574. body: JSON.stringify({ mtu })
  2575. });
  2576. if (res.ok) {
  2577. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  2578. fetchData(false);
  2579. }
  2580. } catch (err) {
  2581. showToast('Error', err.message, 'error');
  2582. }
  2583. }
  2584. async function addInterfaceIP() {
  2585. const ip = document.getElementById('modal-new-ip').value.trim();
  2586. if (!ip) return;
  2587. try {
  2588. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2589. method: 'POST',
  2590. headers: { 'Content-Type': 'application/json' },
  2591. body: JSON.stringify({ ip })
  2592. });
  2593. if (res.ok) {
  2594. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  2595. document.getElementById('modal-new-ip').value = '';
  2596. await fetchData(false);
  2597. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2598. if (iface) renderModalIPs(iface);
  2599. } else {
  2600. const err = await res.json();
  2601. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  2602. }
  2603. } catch (err) {
  2604. showToast('Error', err.message, 'error');
  2605. }
  2606. }
  2607. async function removeInterfaceIP(ip) {
  2608. if (!confirm(`Remove IP ${ip}?`)) return;
  2609. try {
  2610. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2611. method: 'DELETE',
  2612. headers: { 'Content-Type': 'application/json' },
  2613. body: JSON.stringify({ ip })
  2614. });
  2615. if (res.ok) {
  2616. showToast('IP Removed', `Removed ${ip}`, 'success');
  2617. await fetchData(false);
  2618. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2619. if (iface) renderModalIPs(iface);
  2620. }
  2621. } catch (err) {
  2622. showToast('Error', err.message, 'error');
  2623. }
  2624. }
  2625. async function saveInterfaceMetadata() {
  2626. const role = document.getElementById('modal-iface-role').value;
  2627. const desc = document.getElementById('modal-iface-desc').value.trim();
  2628. try {
  2629. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/metadata`, {
  2630. method: 'POST',
  2631. headers: { 'Content-Type': 'application/json' },
  2632. body: JSON.stringify({ role, description: desc })
  2633. });
  2634. if (res.ok) {
  2635. showToast('Saved', 'Metadata updated', 'success');
  2636. closeIfaceModal();
  2637. fetchData(false);
  2638. }
  2639. } catch (err) {
  2640. showToast('Error', err.message, 'error');
  2641. }
  2642. }
  2643. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  2644. state.fwSubTab = 'filter';
  2645. state.routesSubTab = 'routes';
  2646. function renderRuleFlag(disabled, hasComment) {
  2647. let flags = '';
  2648. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  2649. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  2650. return flags || '<span class="text-slate-600">-</span>';
  2651. }
  2652. function renderActionBadge(action) {
  2653. const act = (action || '').toLowerCase();
  2654. let color = 'bg-slate-800 text-slate-300';
  2655. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  2656. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  2657. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  2658. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  2659. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  2660. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  2661. }
  2662. function switchFWSubTab(tab) {
  2663. state.fwSubTab = tab;
  2664. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  2665. tabs.forEach(t => {
  2666. const panel = document.getElementById(`fw-subtab-${t}`);
  2667. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  2668. if (panel) {
  2669. if (t === tab) panel.classList.remove('hidden');
  2670. else panel.classList.add('hidden');
  2671. }
  2672. if (btn) {
  2673. if (t === tab) {
  2674. 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';
  2675. } else {
  2676. 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';
  2677. }
  2678. }
  2679. });
  2680. const addBtn = document.getElementById('fw-primary-add-btn');
  2681. if (addBtn) {
  2682. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  2683. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  2684. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  2685. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  2686. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  2687. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  2688. }
  2689. if (tab === 'geo') loadGeoIP();
  2690. if (tab === 'connections') loadConnections();
  2691. setTimeout(initTableSorting, 50);
  2692. }
  2693. function openCurrentFWModal() {
  2694. if (state.fwSubTab === 'filter') openAddFilterModal();
  2695. else if (state.fwSubTab === 'nat') openAddNATModal();
  2696. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  2697. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  2698. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  2699. else if (state.fwSubTab === 'connections') loadConnections();
  2700. }
  2701. async function loadFirewall(populateDropdowns = true) {
  2702. try {
  2703. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  2704. fetch(`${API_BASE}/firewall/summary`),
  2705. fetch(`${API_BASE}/firewall/filter`),
  2706. fetch(`${API_BASE}/firewall/nat`),
  2707. fetch(`${API_BASE}/firewall/mangle`),
  2708. fetch(`${API_BASE}/firewall/address-lists`),
  2709. fetch(`${API_BASE}/firewall/geoip/status`),
  2710. fetch(`${API_BASE}/firewall/geoip/countries`)
  2711. ]);
  2712. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  2713. if (filterRes.ok) state.filterRules = await filterRes.json();
  2714. if (natRes.ok) state.natRules = await natRes.json();
  2715. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  2716. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  2717. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  2718. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  2719. // Badges
  2720. const bFilter = document.getElementById('fw-badge-filter');
  2721. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  2722. const bNat = document.getElementById('fw-badge-nat');
  2723. if (bNat) bNat.innerText = (state.natRules || []).length;
  2724. const bMangle = document.getElementById('fw-badge-mangle');
  2725. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  2726. const bAddr = document.getElementById('fw-badge-addrlist');
  2727. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  2728. const bGeo = document.getElementById('fw-badge-geo');
  2729. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  2730. renderFilterRules();
  2731. renderNATRules();
  2732. renderMangleRules();
  2733. renderAddressLists();
  2734. renderGeoCountries();
  2735. if (state.fwSubTab === 'connections') {
  2736. loadConnections();
  2737. }
  2738. } catch (err) {
  2739. console.error('Failed to load firewall:', err);
  2740. }
  2741. }
  2742. // ----------------- Filter Rules -----------------
  2743. function renderFilterRules() {
  2744. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  2745. const tbody = document.getElementById('filter-table-body');
  2746. const empty = document.getElementById('filter-empty');
  2747. if (!tbody) return;
  2748. tbody.innerHTML = '';
  2749. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2750. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2751. if (rules.length === 0) {
  2752. empty?.classList.remove('hidden');
  2753. return;
  2754. }
  2755. empty?.classList.add('hidden');
  2756. rules.forEach((r, idx) => {
  2757. const tr = document.createElement('tr');
  2758. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2759. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2760. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2761. let actionExtra = '';
  2762. if (r.action === 'reject') {
  2763. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  2764. } else if (r.action === 'jump') {
  2765. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  2766. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  2767. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  2768. } else if (r.action === 'log' && r.log_prefix) {
  2769. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  2770. }
  2771. tr.innerHTML = `
  2772. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2773. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2774. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2775. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2776. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2777. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2778. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2779. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2780. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  2781. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2782. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2783. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2784. </td>
  2785. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2786. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2787. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2788. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2789. <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>
  2790. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2791. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2792. </td>
  2793. `;
  2794. tbody.appendChild(tr);
  2795. });
  2796. }
  2797. function formatTarget(addr, list, geo) {
  2798. const parts = [];
  2799. if (addr) parts.push(`<span>${addr}</span>`);
  2800. if (list) {
  2801. const inv = list.startsWith('!') ? '!' : '';
  2802. const clean = list.replace(/^!/, '');
  2803. 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>`);
  2804. }
  2805. if (geo) {
  2806. const inv = geo.startsWith('!') ? '!' : '';
  2807. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  2808. 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>`);
  2809. }
  2810. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  2811. return parts.join(' ');
  2812. }
  2813. function populateInterfaceSelect(selectId, currentVal = '') {
  2814. const sel = document.getElementById(selectId);
  2815. if (!sel) return;
  2816. sel.innerHTML = '<option value="">(Any Interface)</option>';
  2817. (state.interfaces || []).forEach(i => {
  2818. const opt = document.createElement('option');
  2819. opt.value = i.name;
  2820. opt.innerText = `${i.name} (${i.role || i.type})`;
  2821. if (i.name === currentVal) opt.selected = true;
  2822. sel.appendChild(opt);
  2823. });
  2824. }
  2825. function populateAddressListSelect(selectId, currentVal = '') {
  2826. const sel = document.getElementById(selectId);
  2827. if (!sel) return;
  2828. sel.innerHTML = '<option value="">(None)</option>';
  2829. const cleanVal = (currentVal || '').replace(/^!/, '');
  2830. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  2831. customNames.forEach(name => {
  2832. const count = (state.addressLists || []).filter(a => a.name === name).length;
  2833. const opt = document.createElement('option');
  2834. opt.value = name;
  2835. opt.innerText = `${name} (${count} entries)`;
  2836. if (name === cleanVal) opt.selected = true;
  2837. sel.appendChild(opt);
  2838. });
  2839. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  2840. const opt = document.createElement('option');
  2841. opt.value = cleanVal;
  2842. opt.innerText = cleanVal;
  2843. opt.selected = true;
  2844. sel.appendChild(opt);
  2845. }
  2846. populateCommonAddrListDatalist();
  2847. }
  2848. function populateCommonAddrListDatalist() {
  2849. const dl = document.getElementById('fw-addrlist-datalist');
  2850. if (!dl) return;
  2851. dl.innerHTML = '';
  2852. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  2853. names.forEach(name => {
  2854. const opt = document.createElement('option');
  2855. opt.value = name;
  2856. dl.appendChild(opt);
  2857. });
  2858. }
  2859. function populateGeoIPSelect(selectId, currentVal = '') {
  2860. const sel = document.getElementById(selectId);
  2861. if (!sel) return;
  2862. sel.innerHTML = '<option value="">(None)</option>';
  2863. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  2864. // Presets optgroup
  2865. const grpPresets = document.createElement('optgroup');
  2866. grpPresets.label = '⚡ Regional Presets';
  2867. const presets = [
  2868. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  2869. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  2870. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  2871. ];
  2872. presets.forEach(p => {
  2873. const opt = document.createElement('option');
  2874. opt.value = p.code;
  2875. opt.innerText = p.label;
  2876. if (p.code === cleanVal) opt.selected = true;
  2877. grpPresets.appendChild(opt);
  2878. });
  2879. sel.appendChild(grpPresets);
  2880. // All Countries optgroup
  2881. const grpCountries = document.createElement('optgroup');
  2882. grpCountries.label = '🌍 All Countries';
  2883. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  2884. countries.forEach(c => {
  2885. const opt = document.createElement('option');
  2886. opt.value = c.code;
  2887. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  2888. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  2889. if (c.code === cleanVal) opt.selected = true;
  2890. grpCountries.appendChild(opt);
  2891. });
  2892. sel.appendChild(grpCountries);
  2893. }
  2894. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  2895. function switchFwRuleTab(tab) {
  2896. state.activeFwRuleTab = tab;
  2897. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  2898. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  2899. btn.classList.add('text-slate-400', 'border-transparent');
  2900. });
  2901. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  2902. if (activeBtn) {
  2903. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  2904. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  2905. }
  2906. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  2907. const activePane = document.getElementById(`fw-pane-${tab}`);
  2908. if (activePane) activePane.classList.remove('hidden');
  2909. if (tab === 'statistics') {
  2910. startFwStatPolling();
  2911. } else {
  2912. stopFwStatPolling();
  2913. }
  2914. }
  2915. function toggleFwField(fieldKey, expand) {
  2916. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  2917. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  2918. if (!plusBtn || !fieldBox) return;
  2919. if (expand) {
  2920. plusBtn.classList.add('hidden');
  2921. fieldBox.classList.remove('hidden');
  2922. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2923. if (valInput) valInput.focus();
  2924. } else {
  2925. fieldBox.classList.add('hidden');
  2926. plusBtn.classList.remove('hidden');
  2927. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2928. if (valInput) {
  2929. if (valInput.tagName === 'SELECT') {
  2930. valInput.selectedIndex = 0;
  2931. } else {
  2932. valInput.value = '';
  2933. }
  2934. }
  2935. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  2936. if (invInput) invInput.checked = false;
  2937. if (fieldKey === 'cs') {
  2938. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  2939. const el = document.getElementById(id);
  2940. if (el) el.checked = false;
  2941. });
  2942. }
  2943. if (fieldKey === 'natstate') {
  2944. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  2945. const el = document.getElementById(id);
  2946. if (el) el.checked = false;
  2947. });
  2948. }
  2949. if (fieldKey === 'days') {
  2950. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  2951. const el = document.getElementById(`fw-day-${d}`);
  2952. if (el) el.checked = true;
  2953. });
  2954. }
  2955. }
  2956. }
  2957. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  2958. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  2959. toggleFwField(fieldKey, true);
  2960. let strVal = String(value);
  2961. if (hasInvert) {
  2962. const inv = strVal.startsWith('!');
  2963. if (inv) strVal = strVal.slice(1);
  2964. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  2965. if (invEl) invEl.checked = inv;
  2966. }
  2967. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  2968. if (valEl) valEl.value = strVal;
  2969. } else {
  2970. toggleFwField(fieldKey, false);
  2971. }
  2972. }
  2973. function getFwFieldVal(fieldKey, hasInvert = false) {
  2974. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  2975. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  2976. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  2977. let v = valEl ? valEl.value.trim() : '';
  2978. if (!v) return '';
  2979. if (hasInvert) {
  2980. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  2981. if (invEl && invEl.checked) {
  2982. v = '!' + v.replace(/^!/, '');
  2983. }
  2984. }
  2985. return v;
  2986. }
  2987. function toggleMaximizeFilterModal() {
  2988. const win = document.getElementById('filter-modal-window');
  2989. if (!win) return;
  2990. if (win.classList.contains('max-w-[720px]')) {
  2991. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  2992. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  2993. } else {
  2994. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  2995. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  2996. }
  2997. }
  2998. function openAddFilterModal() {
  2999. switchFwRuleTab('general');
  3000. const badge = document.getElementById('fw-modal-badge');
  3001. if (badge) badge.innerText = 'New...';
  3002. document.getElementById('filter-modal-id').value = '';
  3003. document.getElementById('filter-modal-enabled').checked = true;
  3004. document.getElementById('filter-modal-comment').value = '';
  3005. document.getElementById('filter-modal-chain').value = 'forward';
  3006. document.getElementById('filter-modal-action').value = 'accept';
  3007. document.getElementById('filter-modal-log').checked = false;
  3008. populateInterfaceSelect('fw-val-iniface');
  3009. populateInterfaceSelect('fw-val-outiface');
  3010. populateAddressListSelect('fw-val-srclist');
  3011. populateAddressListSelect('fw-val-dstlist');
  3012. populateGeoIPSelect('fw-val-srcgeo');
  3013. populateGeoIPSelect('fw-val-dstgeo');
  3014. const allFieldKeys = [
  3015. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3016. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3017. 'routingmark', 'conntype', 'cs', 'natstate',
  3018. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3019. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3020. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3021. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3022. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3023. ];
  3024. allFieldKeys.forEach(k => toggleFwField(k, false));
  3025. resetCurrentRuleCounters();
  3026. toggleFilterActionFields();
  3027. document.getElementById('filter-modal').classList.remove('hidden');
  3028. }
  3029. function openEditFilterModal(id) {
  3030. const r = (state.filterRules || []).find(rule => rule.id === id);
  3031. if (!r) return;
  3032. switchFwRuleTab('general');
  3033. const badge = document.getElementById('fw-modal-badge');
  3034. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3035. document.getElementById('filter-modal-id').value = r.id;
  3036. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  3037. document.getElementById('filter-modal-comment').value = r.comment || '';
  3038. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  3039. document.getElementById('filter-modal-action').value = r.action || 'accept';
  3040. document.getElementById('filter-modal-log').checked = !!r.log;
  3041. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3042. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3043. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3044. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3045. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  3046. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  3047. setFwFieldVal('src', r.src_address, true);
  3048. setFwFieldVal('dst', r.dst_address, true);
  3049. setFwFieldVal('srclist', r.src_address_list, true);
  3050. setFwFieldVal('dstlist', r.dst_address_list, true);
  3051. setFwFieldVal('srcgeo', r.src_geoip, true);
  3052. setFwFieldVal('dstgeo', r.dst_geoip, true);
  3053. if (r.protocol && r.protocol !== 'all') {
  3054. setFwFieldVal('proto', r.protocol, true);
  3055. } else {
  3056. toggleFwField('proto', false);
  3057. }
  3058. setFwFieldVal('sport', r.src_port, true);
  3059. setFwFieldVal('dport', r.dst_port, true);
  3060. setFwFieldVal('anyport', r.any_port, true);
  3061. setFwFieldVal('iniface', r.in_interface, true);
  3062. setFwFieldVal('outiface', r.out_interface, true);
  3063. setFwFieldVal('inifacelist', r.in_interface_list, true);
  3064. setFwFieldVal('outifacelist', r.out_interface_list, true);
  3065. setFwFieldVal('pktmark', r.packet_mark, true);
  3066. setFwFieldVal('connmark', r.connection_mark, true);
  3067. setFwFieldVal('routingmark', r.routing_mark, true);
  3068. setFwFieldVal('conntype', r.connection_type, false);
  3069. const states = r.connection_state || [];
  3070. if (states.length > 0) {
  3071. toggleFwField('cs', true);
  3072. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  3073. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  3074. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  3075. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  3076. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  3077. } else {
  3078. toggleFwField('cs', false);
  3079. }
  3080. const natStates = r.connection_nat_state || [];
  3081. if (natStates.length > 0) {
  3082. toggleFwField('natstate', true);
  3083. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  3084. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  3085. } else {
  3086. toggleFwField('natstate', false);
  3087. }
  3088. // Advanced tab fields
  3089. setFwFieldVal('layer7', r.layer7_protocol, false);
  3090. setFwFieldVal('content', r.content, false);
  3091. setFwFieldVal('connbytes', r.connection_bytes, false);
  3092. setFwFieldVal('connrate', r.connection_rate, false);
  3093. setFwFieldVal('pcc', r.pcc, false);
  3094. setFwFieldVal('srcmac', r.src_mac_address, true);
  3095. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  3096. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  3097. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3098. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3099. setFwFieldVal('ipsec', r.ipsec_policy, false);
  3100. setFwFieldVal('tlshost', r.tls_host, false);
  3101. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  3102. setFwFieldVal('priority', r.priority, false);
  3103. setFwFieldVal('dscp', r.dscp, false);
  3104. setFwFieldVal('tcpmss', r.tcp_mss, false);
  3105. if (r.tos) {
  3106. const tosEl = document.getElementById('fw-val-tos');
  3107. if (tosEl) tosEl.value = r.tos;
  3108. }
  3109. setFwFieldVal('pktsize', r.packet_size, false);
  3110. setFwFieldVal('random', r.random, false);
  3111. setFwFieldVal('tcpflags', r.tcp_flags, false);
  3112. setFwFieldVal('icmpoptions', r.icmp_options, false);
  3113. setFwFieldVal('ipv4options', r.ipv4_options, false);
  3114. setFwFieldVal('ttl', r.ttl, false);
  3115. // Extra tab fields
  3116. setFwFieldVal('time', r.time, false);
  3117. if (r.days) {
  3118. toggleFwField('days', true);
  3119. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3120. const chk = document.getElementById(`fw-day-${d}`);
  3121. if (chk) chk.checked = r.days.includes(d);
  3122. });
  3123. } else {
  3124. toggleFwField('days', false);
  3125. }
  3126. setFwFieldVal('limit', r.limit, false);
  3127. setFwFieldVal('dstlimit', r.dst_limit, false);
  3128. setFwFieldVal('psd', r.psd, false);
  3129. // Action fields
  3130. if (r.reject_with) {
  3131. const rwEl = document.getElementById('filter-modal-rejectwith');
  3132. if (rwEl) rwEl.value = r.reject_with;
  3133. }
  3134. if (r.jump_target) {
  3135. const jtEl = document.getElementById('filter-modal-jumptarget');
  3136. if (jtEl) jtEl.value = r.jump_target;
  3137. }
  3138. if (r.address_list) {
  3139. const alEl = document.getElementById('filter-modal-action-addrlist');
  3140. if (alEl) alEl.value = r.address_list;
  3141. }
  3142. if (r.address_list_timeout) {
  3143. const toEl = document.getElementById('filter-modal-action-timeout');
  3144. if (toEl) toEl.value = r.address_list_timeout;
  3145. }
  3146. setFwFieldVal('logprefix', r.log_prefix, false);
  3147. // Statistics
  3148. const bEl = document.getElementById('fw-stat-bytes');
  3149. const pEl = document.getElementById('fw-stat-packets');
  3150. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3151. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3152. state.fwLastBytes = r.bytes || 0;
  3153. state.fwLastPackets = r.packets || 0;
  3154. state.fwLastTimestamp = Date.now();
  3155. state.fwStatRateHistory = new Array(30).fill(0);
  3156. state.fwStatPktHistory = new Array(30).fill(0);
  3157. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3158. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3159. toggleFilterActionFields();
  3160. document.getElementById('filter-modal').classList.remove('hidden');
  3161. }
  3162. function closeFilterModal() {
  3163. stopFwStatPolling();
  3164. document.getElementById('filter-modal').classList.add('hidden');
  3165. }
  3166. function toggleFilterActionFields() {
  3167. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  3168. const rejectBox = document.getElementById('filter-action-reject-box');
  3169. const jumpBox = document.getElementById('filter-action-jump-box');
  3170. const addrBox = document.getElementById('filter-action-addrlist-box');
  3171. if (rejectBox) {
  3172. if (act === 'reject') rejectBox.classList.remove('hidden');
  3173. else rejectBox.classList.add('hidden');
  3174. }
  3175. if (jumpBox) {
  3176. if (act === 'jump') jumpBox.classList.remove('hidden');
  3177. else jumpBox.classList.add('hidden');
  3178. }
  3179. if (addrBox) {
  3180. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  3181. addrBox.classList.remove('hidden');
  3182. } else {
  3183. addrBox.classList.add('hidden');
  3184. }
  3185. }
  3186. if (act === 'log') {
  3187. const logEl = document.getElementById('filter-modal-log');
  3188. if (logEl) logEl.checked = true;
  3189. toggleFwField('logprefix', true);
  3190. }
  3191. }
  3192. function toggleFwLogPrefix() {
  3193. const isLog = document.getElementById('filter-modal-log')?.checked;
  3194. toggleFwField('logprefix', !!isLog);
  3195. }
  3196. function copyFilterRule() {
  3197. document.getElementById('filter-modal-id').value = '';
  3198. const badge = document.getElementById('fw-modal-badge');
  3199. if (badge) badge.innerText = 'New...';
  3200. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  3201. }
  3202. function resetCurrentRuleCounters() {
  3203. state.fwStatRateHistory = new Array(30).fill(0);
  3204. state.fwStatPktHistory = new Array(30).fill(0);
  3205. state.fwLastBytes = 0;
  3206. state.fwLastPackets = 0;
  3207. state.fwLastTimestamp = Date.now();
  3208. const bEl = document.getElementById('fw-stat-bytes');
  3209. const pEl = document.getElementById('fw-stat-packets');
  3210. const rEl = document.getElementById('fw-stat-rate');
  3211. const prEl = document.getElementById('fw-stat-pktrate');
  3212. if (bEl) bEl.value = '0 B';
  3213. if (pEl) pEl.value = '0';
  3214. if (rEl) rEl.value = '0 bps';
  3215. if (prEl) prEl.value = '0 p/s';
  3216. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3217. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3218. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  3219. }
  3220. async function resetAllFwCounters() {
  3221. try {
  3222. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3223. if (res.ok) {
  3224. resetCurrentRuleCounters();
  3225. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  3226. loadFirewall(false);
  3227. }
  3228. } catch (err) {
  3229. showToast('Error', err.message, 'error');
  3230. }
  3231. }
  3232. async function applyFilterRule(closeAfter = false) {
  3233. const id = document.getElementById('filter-modal-id').value;
  3234. const chain = document.getElementById('filter-modal-chain').value;
  3235. const action = document.getElementById('filter-modal-action').value;
  3236. const comment = document.getElementById('filter-modal-comment').value.trim();
  3237. const enabled = document.getElementById('filter-modal-enabled').checked;
  3238. const src = getFwFieldVal('src', true);
  3239. const dst = getFwFieldVal('dst', true);
  3240. const srclist = getFwFieldVal('srclist', true);
  3241. const dstlist = getFwFieldVal('dstlist', true);
  3242. const srcgeo = getFwFieldVal('srcgeo', true);
  3243. const dstgeo = getFwFieldVal('dstgeo', true);
  3244. const proto = getFwFieldVal('proto', true);
  3245. const sport = getFwFieldVal('sport', true);
  3246. const dport = getFwFieldVal('dport', true);
  3247. const anyport = getFwFieldVal('anyport', true);
  3248. const iniface = getFwFieldVal('iniface', true);
  3249. const outiface = getFwFieldVal('outiface', true);
  3250. const inifacelist = getFwFieldVal('inifacelist', true);
  3251. const outifacelist = getFwFieldVal('outifacelist', true);
  3252. const pktmark = getFwFieldVal('pktmark', true);
  3253. const connmark = getFwFieldVal('connmark', true);
  3254. const routingmark = getFwFieldVal('routingmark', true);
  3255. const conntype = getFwFieldVal('conntype', false);
  3256. const states = [];
  3257. const csBox = document.getElementById('fw-field-cs');
  3258. if (csBox && !csBox.classList.contains('hidden')) {
  3259. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  3260. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  3261. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  3262. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  3263. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  3264. }
  3265. const natStates = [];
  3266. const natBox = document.getElementById('fw-field-natstate');
  3267. if (natBox && !natBox.classList.contains('hidden')) {
  3268. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  3269. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  3270. }
  3271. const payload = {
  3272. id,
  3273. chain,
  3274. action,
  3275. protocol: proto || 'all',
  3276. src_address: src,
  3277. dst_address: dst,
  3278. src_port: sport,
  3279. dst_port: dport,
  3280. any_port: anyport,
  3281. in_interface: iniface,
  3282. out_interface: outiface,
  3283. in_interface_list: inifacelist,
  3284. out_interface_list: outifacelist,
  3285. packet_mark: pktmark,
  3286. connection_mark: connmark,
  3287. routing_mark: routingmark,
  3288. connection_type: conntype,
  3289. connection_state: states,
  3290. connection_nat_state: natStates,
  3291. src_address_list: srclist,
  3292. dst_address_list: dstlist,
  3293. src_geoip: srcgeo,
  3294. dst_geoip: dstgeo,
  3295. comment,
  3296. disabled: !enabled,
  3297. // Advanced tab
  3298. layer7_protocol: getFwFieldVal('layer7', false),
  3299. content: getFwFieldVal('content', false),
  3300. connection_bytes: getFwFieldVal('connbytes', false),
  3301. connection_rate: getFwFieldVal('connrate', false),
  3302. pcc: getFwFieldVal('pcc', false),
  3303. src_mac_address: getFwFieldVal('srcmac', true),
  3304. out_bridge_port: getFwFieldVal('outbridgeport', false),
  3305. in_bridge_port: getFwFieldVal('inbridgeport', false),
  3306. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  3307. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  3308. ipsec_policy: getFwFieldVal('ipsec', false),
  3309. tls_host: getFwFieldVal('tlshost', false),
  3310. ingress_priority: getFwFieldVal('ingresspriority', false),
  3311. priority: getFwFieldVal('priority', false),
  3312. dscp: getFwFieldVal('dscp', false),
  3313. tcp_mss: getFwFieldVal('tcpmss', false),
  3314. tos: document.getElementById('fw-val-tos')?.value || '',
  3315. packet_size: getFwFieldVal('pktsize', false),
  3316. random: getFwFieldVal('random', false),
  3317. tcp_flags: getFwFieldVal('tcpflags', false),
  3318. icmp_options: getFwFieldVal('icmpoptions', false),
  3319. ipv4_options: getFwFieldVal('ipv4options', false),
  3320. ttl: getFwFieldVal('ttl', false),
  3321. // Extra tab
  3322. time: getFwFieldVal('time', false),
  3323. limit: getFwFieldVal('limit', false),
  3324. dst_limit: getFwFieldVal('dstlimit', false),
  3325. psd: getFwFieldVal('psd', false),
  3326. // Action tab
  3327. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  3328. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  3329. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  3330. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  3331. log: document.getElementById('filter-modal-log')?.checked || false,
  3332. log_prefix: getFwFieldVal('logprefix', false)
  3333. };
  3334. try {
  3335. const res = await fetch(`${API_BASE}/firewall/filter`, {
  3336. method: 'POST',
  3337. headers: { 'Content-Type': 'application/json' },
  3338. body: JSON.stringify(payload)
  3339. });
  3340. if (res.ok) {
  3341. const data = await res.json();
  3342. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  3343. loadFirewall(false);
  3344. if (closeAfter) {
  3345. closeFilterModal();
  3346. } else {
  3347. if (data.id) {
  3348. document.getElementById('filter-modal-id').value = data.id;
  3349. const badge = document.getElementById('fw-modal-badge');
  3350. if (badge) badge.innerText = `#${data.id}`;
  3351. }
  3352. }
  3353. } else {
  3354. const err = await res.json();
  3355. showToast('Error', err.message || 'Failed to save rule', 'error');
  3356. }
  3357. } catch (err) {
  3358. showToast('Error', err.message, 'error');
  3359. }
  3360. }
  3361. function submitSaveFilterRule(e) {
  3362. if (e && e.preventDefault) e.preventDefault();
  3363. return applyFilterRule(true);
  3364. }
  3365. function startFwStatPolling() {
  3366. stopFwStatPolling();
  3367. pollRuleStats();
  3368. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  3369. }
  3370. function stopFwStatPolling() {
  3371. if (state.fwStatInterval) {
  3372. clearInterval(state.fwStatInterval);
  3373. state.fwStatInterval = null;
  3374. }
  3375. }
  3376. async function pollRuleStats() {
  3377. const id = document.getElementById('filter-modal-id')?.value;
  3378. if (!id) {
  3379. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  3380. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  3381. return;
  3382. }
  3383. try {
  3384. const res = await fetch(`${API_BASE}/firewall/filter`);
  3385. if (!res.ok) return;
  3386. const rules = await res.json();
  3387. const r = rules.find(x => x.id === id);
  3388. if (!r) return;
  3389. const now = Date.now();
  3390. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  3391. state.fwLastTimestamp = now;
  3392. const curBytes = r.bytes || 0;
  3393. const curPackets = r.packets || 0;
  3394. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  3395. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  3396. state.fwLastBytes = curBytes;
  3397. state.fwLastPackets = curPackets;
  3398. const rateBps = Math.round((deltaBytes * 8) / dt);
  3399. const ratePkt = Math.round(deltaPkts / dt);
  3400. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  3401. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  3402. state.fwStatRateHistory.push(rateBps);
  3403. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  3404. state.fwStatPktHistory.push(ratePkt);
  3405. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  3406. const bEl = document.getElementById('fw-stat-bytes');
  3407. const pEl = document.getElementById('fw-stat-packets');
  3408. const rEl = document.getElementById('fw-stat-rate');
  3409. const prEl = document.getElementById('fw-stat-pktrate');
  3410. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  3411. if (pEl) pEl.value = curPackets.toLocaleString();
  3412. if (rEl) rEl.value = formatBps(rateBps);
  3413. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  3414. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3415. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3416. } catch (e) {
  3417. console.error('Error polling rule stats', e);
  3418. }
  3419. }
  3420. function formatBps(bps) {
  3421. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  3422. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  3423. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  3424. return bps + ' bps';
  3425. }
  3426. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  3427. const svg = document.getElementById(svgId);
  3428. if (!svg) return;
  3429. const w = 500;
  3430. const h = 100;
  3431. const paddingRight = 45;
  3432. const graphWidth = w - paddingRight;
  3433. const maxVal = Math.max(5, ...dataArray);
  3434. const currentVal = dataArray[dataArray.length - 1] || 0;
  3435. const leg = document.getElementById(legendId);
  3436. if (leg) {
  3437. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  3438. }
  3439. let gridLines = '';
  3440. for (let i = 0; i <= 5; i++) {
  3441. const y = 8 + (i * (h - 18) / 5);
  3442. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  3443. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  3444. gridLines += `
  3445. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  3446. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  3447. `;
  3448. }
  3449. const step = graphWidth / (dataArray.length - 1);
  3450. const points = dataArray.map((val, idx) => {
  3451. const x = idx * step;
  3452. const y = (h - 10) - (val / maxVal) * (h - 20);
  3453. return `${x.toFixed(1)},${y.toFixed(1)}`;
  3454. });
  3455. const polylineStr = points.join(' ');
  3456. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  3457. svg.innerHTML = `
  3458. ${gridLines}
  3459. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  3460. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  3461. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  3462. `;
  3463. }
  3464. async function moveFilterRule(id, dir) {
  3465. try {
  3466. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  3467. method: 'POST',
  3468. headers: { 'Content-Type': 'application/json' },
  3469. body: JSON.stringify({ direction: dir })
  3470. });
  3471. if (res.ok) loadFirewall(false);
  3472. } catch (err) {
  3473. showToast('Error', err.message, 'error');
  3474. }
  3475. }
  3476. async function toggleFilterRuleState(id, disabled) {
  3477. try {
  3478. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  3479. method: 'POST',
  3480. headers: { 'Content-Type': 'application/json' },
  3481. body: JSON.stringify({ disabled })
  3482. });
  3483. if (res.ok) loadFirewall(false);
  3484. } catch (err) {
  3485. showToast('Error', err.message, 'error');
  3486. }
  3487. }
  3488. async function deleteFilterRule(id) {
  3489. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  3490. try {
  3491. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3492. if (res.ok) {
  3493. showToast('Deleted', 'Filter rule removed', 'success');
  3494. loadFirewall(false);
  3495. }
  3496. } catch (err) {
  3497. showToast('Error', err.message, 'error');
  3498. }
  3499. }
  3500. // ----------------- NAT Rules -----------------
  3501. function renderNATRules() {
  3502. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  3503. const tbody = document.getElementById('nat-table-body');
  3504. const empty = document.getElementById('nat-empty');
  3505. if (!tbody) return;
  3506. tbody.innerHTML = '';
  3507. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3508. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  3509. if (rules.length === 0) {
  3510. empty?.classList.remove('hidden');
  3511. return;
  3512. }
  3513. empty?.classList.add('hidden');
  3514. rules.forEach((r, idx) => {
  3515. const tr = document.createElement('tr');
  3516. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3517. let toTarget = '-';
  3518. if (r.action === 'jump') {
  3519. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  3520. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3521. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  3522. } else if (r.action === 'redirect') {
  3523. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  3524. } else if (r.action === 'masquerade') {
  3525. 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>`;
  3526. } else if (r.action === 'log') {
  3527. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  3528. } else {
  3529. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  3530. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  3531. }
  3532. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  3533. tr.innerHTML = `
  3534. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3535. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3536. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  3537. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3538. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3539. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  3540. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3541. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  3542. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  3543. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3544. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3545. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3546. </td>
  3547. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3548. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3549. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3550. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3551. <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>
  3552. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3553. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3554. </td>
  3555. `;
  3556. tbody.appendChild(tr);
  3557. });
  3558. }
  3559. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3560. function switchNATRuleTab(tab) {
  3561. state.activeNATRuleTab = tab;
  3562. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  3563. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3564. btn.classList.add('text-slate-400', 'border-transparent');
  3565. });
  3566. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  3567. if (activeBtn) {
  3568. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3569. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3570. }
  3571. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  3572. const activePane = document.getElementById(`nat-pane-${tab}`);
  3573. if (activePane) activePane.classList.remove('hidden');
  3574. if (tab === 'statistics') {
  3575. startNATStatPolling();
  3576. } else {
  3577. stopNATStatPolling();
  3578. }
  3579. }
  3580. function toggleNATField(fieldKey, expand) {
  3581. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  3582. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3583. if (!plusBtn || !fieldBox) return;
  3584. if (expand) {
  3585. plusBtn.classList.add('hidden');
  3586. fieldBox.classList.remove('hidden');
  3587. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3588. if (valInput) valInput.focus();
  3589. } else {
  3590. fieldBox.classList.add('hidden');
  3591. plusBtn.classList.remove('hidden');
  3592. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3593. if (valInput) {
  3594. if (valInput.tagName === 'SELECT') {
  3595. valInput.selectedIndex = 0;
  3596. } else {
  3597. valInput.value = '';
  3598. }
  3599. }
  3600. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  3601. if (invInput) invInput.checked = false;
  3602. if (fieldKey === 'days') {
  3603. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3604. const el = document.getElementById(`nat-day-${d}`);
  3605. if (el) el.checked = true;
  3606. });
  3607. }
  3608. }
  3609. }
  3610. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  3611. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3612. toggleNATField(fieldKey, true);
  3613. let strVal = String(value);
  3614. if (hasInvert) {
  3615. const inv = strVal.startsWith('!');
  3616. if (inv) strVal = strVal.slice(1);
  3617. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3618. if (invEl) invEl.checked = inv;
  3619. }
  3620. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3621. if (valEl) valEl.value = strVal;
  3622. } else {
  3623. toggleNATField(fieldKey, false);
  3624. }
  3625. }
  3626. function getNATFieldVal(fieldKey, hasInvert = false) {
  3627. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3628. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3629. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3630. let v = valEl ? valEl.value.trim() : '';
  3631. if (!v) return '';
  3632. if (hasInvert) {
  3633. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3634. if (invEl && invEl.checked) {
  3635. v = '!' + v.replace(/^!/, '');
  3636. }
  3637. }
  3638. return v;
  3639. }
  3640. function toggleMaximizeNATModal() {
  3641. const win = document.getElementById('nat-modal-window');
  3642. if (!win) return;
  3643. if (win.classList.contains('max-w-[720px]')) {
  3644. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3645. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3646. } else {
  3647. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3648. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3649. }
  3650. }
  3651. function handleNATChainChange() {
  3652. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  3653. const actSel = document.getElementById('nat-modal-action');
  3654. if (actSel) {
  3655. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  3656. actSel.value = 'masquerade';
  3657. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  3658. actSel.value = 'dst-nat';
  3659. }
  3660. }
  3661. toggleNATActionFields();
  3662. }
  3663. function toggleNATActionFields() {
  3664. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  3665. const rowAddr = document.getElementById('nat-row-toaddr');
  3666. const rowPort = document.getElementById('nat-row-toport');
  3667. const jumpBox = document.getElementById('nat-action-jump-box');
  3668. const addrBox = document.getElementById('nat-action-addrlist-box');
  3669. // Hide all dynamic rows first
  3670. if (rowAddr) rowAddr.classList.add('hidden');
  3671. if (rowPort) rowPort.classList.add('hidden');
  3672. if (jumpBox) jumpBox.classList.add('hidden');
  3673. if (addrBox) addrBox.classList.add('hidden');
  3674. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  3675. if (rowAddr) rowAddr.classList.remove('hidden');
  3676. if (rowPort) rowPort.classList.remove('hidden');
  3677. } else if (act === 'redirect' || act === 'masquerade') {
  3678. if (rowPort) rowPort.classList.remove('hidden');
  3679. } else if (act === 'jump') {
  3680. if (jumpBox) jumpBox.classList.remove('hidden');
  3681. } else if (act.includes('address-list') || act.includes('address list')) {
  3682. if (addrBox) addrBox.classList.remove('hidden');
  3683. }
  3684. if (act === 'log') {
  3685. const logEl = document.getElementById('nat-modal-log');
  3686. if (logEl) logEl.checked = true;
  3687. toggleNATField('logprefix', true);
  3688. }
  3689. }
  3690. function toggleNATLogPrefix() {
  3691. const isLog = document.getElementById('nat-modal-log')?.checked;
  3692. toggleNATField('logprefix', !!isLog);
  3693. }
  3694. function openAddNATModal() {
  3695. switchNATRuleTab('general');
  3696. const badge = document.getElementById('nat-modal-badge');
  3697. if (badge) badge.innerText = 'New...';
  3698. document.getElementById('nat-modal-id').value = '';
  3699. document.getElementById('nat-modal-enabled').checked = true;
  3700. document.getElementById('nat-modal-comment').value = '';
  3701. document.getElementById('nat-modal-chain').value = 'srcnat';
  3702. document.getElementById('nat-modal-action').value = 'masquerade';
  3703. document.getElementById('nat-modal-toaddr').value = '';
  3704. document.getElementById('nat-modal-toport').value = '';
  3705. document.getElementById('nat-modal-log').checked = false;
  3706. populateInterfaceSelect('nat-val-iniface');
  3707. populateInterfaceSelect('nat-val-outiface');
  3708. populateAddressListSelect('nat-val-srclist');
  3709. populateAddressListSelect('nat-val-dstlist');
  3710. populateGeoIPSelect('nat-val-srcgeo');
  3711. populateGeoIPSelect('nat-val-dstgeo');
  3712. const allFieldKeys = [
  3713. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3714. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3715. 'routingmark', 'conntype',
  3716. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3717. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3718. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3719. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  3720. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3721. ];
  3722. allFieldKeys.forEach(k => toggleNATField(k, false));
  3723. resetCurrentNATRuleCounters();
  3724. toggleNATActionFields();
  3725. document.getElementById('nat-modal').classList.remove('hidden');
  3726. }
  3727. function openEditNATModal(id) {
  3728. const r = (state.natRules || []).find(rule => rule.id === id);
  3729. if (!r) return;
  3730. switchNATRuleTab('general');
  3731. const badge = document.getElementById('nat-modal-badge');
  3732. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3733. document.getElementById('nat-modal-id').value = r.id;
  3734. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  3735. document.getElementById('nat-modal-comment').value = r.comment || '';
  3736. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  3737. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  3738. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  3739. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  3740. document.getElementById('nat-modal-log').checked = !!r.log;
  3741. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3742. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3743. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3744. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3745. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  3746. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  3747. setNATFieldVal('src', r.src_address, true);
  3748. setNATFieldVal('dst', r.dst_address, true);
  3749. setNATFieldVal('srclist', r.src_address_list, true);
  3750. setNATFieldVal('dstlist', r.dst_address_list, true);
  3751. setNATFieldVal('srcgeo', r.src_geoip, true);
  3752. setNATFieldVal('dstgeo', r.dst_geoip, true);
  3753. if (r.protocol && r.protocol !== 'all') {
  3754. setNATFieldVal('proto', r.protocol, true);
  3755. } else {
  3756. toggleNATField('proto', false);
  3757. }
  3758. setNATFieldVal('sport', r.src_port, true);
  3759. setNATFieldVal('dport', r.dst_port, true);
  3760. setNATFieldVal('anyport', r.any_port, true);
  3761. setNATFieldVal('iniface', r.in_interface, true);
  3762. setNATFieldVal('outiface', r.out_interface, true);
  3763. setNATFieldVal('inifacelist', r.in_interface_list, true);
  3764. setNATFieldVal('outifacelist', r.out_interface_list, true);
  3765. setNATFieldVal('pktmark', r.packet_mark, true);
  3766. setNATFieldVal('connmark', r.connection_mark, true);
  3767. setNATFieldVal('routingmark', r.routing_mark, true);
  3768. setNATFieldVal('conntype', r.connection_type, false);
  3769. // Advanced tab fields
  3770. setNATFieldVal('layer7', r.layer7_protocol, false);
  3771. setNATFieldVal('content', r.content, false);
  3772. setNATFieldVal('connbytes', r.connection_bytes, false);
  3773. setNATFieldVal('connrate', r.connection_rate, false);
  3774. setNATFieldVal('pcc', r.pcc, false);
  3775. setNATFieldVal('srcmac', r.src_mac_address, true);
  3776. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  3777. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  3778. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3779. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3780. setNATFieldVal('ipsec', r.ipsec_policy, false);
  3781. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  3782. setNATFieldVal('priority', r.priority, false);
  3783. setNATFieldVal('dscp', r.dscp, false);
  3784. setNATFieldVal('tcpmss', r.tcp_mss, false);
  3785. if (r.tos) {
  3786. const tosEl = document.getElementById('nat-val-tos');
  3787. if (tosEl) tosEl.value = r.tos;
  3788. }
  3789. setNATFieldVal('pktsize', r.packet_size, false);
  3790. setNATFieldVal('random', r.random, false);
  3791. setNATFieldVal('icmpoptions', r.icmp_options, false);
  3792. setNATFieldVal('ipv4options', r.ipv4_options, false);
  3793. setNATFieldVal('ttl', r.ttl, false);
  3794. // Extra tab fields
  3795. setNATFieldVal('time', r.time, false);
  3796. if (r.days) {
  3797. toggleNATField('days', true);
  3798. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3799. const chk = document.getElementById(`nat-day-${d}`);
  3800. if (chk) chk.checked = r.days.includes(d);
  3801. });
  3802. } else {
  3803. toggleNATField('days', false);
  3804. }
  3805. setNATFieldVal('limit', r.limit, false);
  3806. setNATFieldVal('dstlimit', r.dst_limit, false);
  3807. setNATFieldVal('psd', r.psd, false);
  3808. // Action fields
  3809. if (r.jump_target) {
  3810. const jtEl = document.getElementById('nat-modal-jumptarget');
  3811. if (jtEl) jtEl.value = r.jump_target;
  3812. }
  3813. if (r.address_list) {
  3814. const alEl = document.getElementById('nat-modal-action-addrlist');
  3815. if (alEl) alEl.value = r.address_list;
  3816. }
  3817. if (r.address_list_timeout) {
  3818. const toEl = document.getElementById('nat-modal-action-timeout');
  3819. if (toEl) toEl.value = r.address_list_timeout;
  3820. }
  3821. setNATFieldVal('logprefix', r.log_prefix, false);
  3822. // Statistics
  3823. const bEl = document.getElementById('nat-stat-bytes');
  3824. const pEl = document.getElementById('nat-stat-packets');
  3825. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3826. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3827. state.natLastBytes = r.bytes || 0;
  3828. state.natLastPackets = r.packets || 0;
  3829. state.natLastTimestamp = Date.now();
  3830. state.natStatRateHistory = new Array(30).fill(0);
  3831. state.natStatPktHistory = new Array(30).fill(0);
  3832. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3833. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3834. toggleNATActionFields();
  3835. document.getElementById('nat-modal').classList.remove('hidden');
  3836. }
  3837. function closeNATModal() {
  3838. stopNATStatPolling();
  3839. document.getElementById('nat-modal').classList.add('hidden');
  3840. }
  3841. function copyNATRule() {
  3842. document.getElementById('nat-modal-id').value = '';
  3843. const badge = document.getElementById('nat-modal-badge');
  3844. if (badge) badge.innerText = 'New...';
  3845. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  3846. }
  3847. function resetCurrentNATRuleCounters() {
  3848. state.natStatRateHistory = new Array(30).fill(0);
  3849. state.natStatPktHistory = new Array(30).fill(0);
  3850. state.natLastBytes = 0;
  3851. state.natLastPackets = 0;
  3852. state.natLastTimestamp = Date.now();
  3853. const bEl = document.getElementById('nat-stat-bytes');
  3854. const pEl = document.getElementById('nat-stat-packets');
  3855. const rEl = document.getElementById('nat-stat-rate');
  3856. const prEl = document.getElementById('nat-stat-pktrate');
  3857. if (bEl) bEl.value = '0 B';
  3858. if (pEl) pEl.value = '0';
  3859. if (rEl) rEl.value = '0 bps';
  3860. if (prEl) prEl.value = '0 p/s';
  3861. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3862. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3863. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  3864. }
  3865. async function applyNATRule(closeAfter = false) {
  3866. const id = document.getElementById('nat-modal-id').value;
  3867. const chain = document.getElementById('nat-modal-chain').value;
  3868. const action = document.getElementById('nat-modal-action').value;
  3869. const comment = document.getElementById('nat-modal-comment').value.trim();
  3870. const enabled = document.getElementById('nat-modal-enabled').checked;
  3871. const src = getNATFieldVal('src', true);
  3872. const dst = getNATFieldVal('dst', true);
  3873. const srclist = getNATFieldVal('srclist', true);
  3874. const dstlist = getNATFieldVal('dstlist', true);
  3875. const srcgeo = getNATFieldVal('srcgeo', true);
  3876. const dstgeo = getNATFieldVal('dstgeo', true);
  3877. const proto = getNATFieldVal('proto', true);
  3878. const sport = getNATFieldVal('sport', true);
  3879. const dport = getNATFieldVal('dport', true);
  3880. const anyport = getNATFieldVal('anyport', true);
  3881. const iniface = getNATFieldVal('iniface', true);
  3882. const outiface = getNATFieldVal('outiface', true);
  3883. const inifacelist = getNATFieldVal('inifacelist', true);
  3884. const outifacelist = getNATFieldVal('outifacelist', true);
  3885. const pktmark = getNATFieldVal('pktmark', true);
  3886. const connmark = getNATFieldVal('connmark', true);
  3887. const routingmark = getNATFieldVal('routingmark', true);
  3888. const conntype = getNATFieldVal('conntype', false);
  3889. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  3890. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  3891. const payload = {
  3892. id,
  3893. chain,
  3894. action,
  3895. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  3896. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  3897. protocol: proto || 'all',
  3898. src_address: src,
  3899. dst_address: dst,
  3900. src_port: sport,
  3901. dst_port: dport,
  3902. any_port: anyport,
  3903. in_interface: iniface,
  3904. out_interface: outiface,
  3905. in_interface_list: inifacelist,
  3906. out_interface_list: outifacelist,
  3907. packet_mark: pktmark,
  3908. connection_mark: connmark,
  3909. routing_mark: routingmark,
  3910. connection_type: conntype,
  3911. src_address_list: srclist,
  3912. dst_address_list: dstlist,
  3913. src_geoip: srcgeo,
  3914. dst_geoip: dstgeo,
  3915. comment,
  3916. disabled: !enabled,
  3917. // Advanced tab
  3918. layer7_protocol: getNATFieldVal('layer7', false),
  3919. content: getNATFieldVal('content', false),
  3920. connection_bytes: getNATFieldVal('connbytes', false),
  3921. connection_rate: getNATFieldVal('connrate', false),
  3922. pcc: getNATFieldVal('pcc', false),
  3923. src_mac_address: getNATFieldVal('srcmac', true),
  3924. out_bridge_port: getNATFieldVal('outbridgeport', false),
  3925. in_bridge_port: getNATFieldVal('inbridgeport', false),
  3926. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  3927. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  3928. ipsec_policy: getNATFieldVal('ipsec', false),
  3929. ingress_priority: getNATFieldVal('ingresspriority', false),
  3930. priority: getNATFieldVal('priority', false),
  3931. dscp: getNATFieldVal('dscp', false),
  3932. tcp_mss: getNATFieldVal('tcpmss', false),
  3933. tos: document.getElementById('nat-val-tos')?.value || '',
  3934. packet_size: getNATFieldVal('pktsize', false),
  3935. random: getNATFieldVal('random', false),
  3936. icmp_options: getNATFieldVal('icmpoptions', false),
  3937. ipv4_options: getNATFieldVal('ipv4options', false),
  3938. ttl: getNATFieldVal('ttl', false),
  3939. // Extra tab
  3940. time: getNATFieldVal('time', false),
  3941. limit: getNATFieldVal('limit', false),
  3942. dst_limit: getNATFieldVal('dstlimit', false),
  3943. psd: getNATFieldVal('psd', false),
  3944. // Action tab
  3945. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  3946. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  3947. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  3948. log: document.getElementById('nat-modal-log')?.checked || false,
  3949. log_prefix: getNATFieldVal('logprefix', false)
  3950. };
  3951. try {
  3952. const res = await fetch(`${API_BASE}/firewall/nat`, {
  3953. method: 'POST',
  3954. headers: { 'Content-Type': 'application/json' },
  3955. body: JSON.stringify(payload)
  3956. });
  3957. if (res.ok) {
  3958. const data = await res.json();
  3959. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  3960. loadFirewall(false);
  3961. if (closeAfter) {
  3962. closeNATModal();
  3963. } else {
  3964. if (data.id) {
  3965. document.getElementById('nat-modal-id').value = data.id;
  3966. const badge = document.getElementById('nat-modal-badge');
  3967. if (badge) badge.innerText = `#${data.id}`;
  3968. }
  3969. }
  3970. } else {
  3971. const err = await res.json();
  3972. showToast('Error', err.message || 'Failed to save rule', 'error');
  3973. }
  3974. } catch (err) {
  3975. showToast('Error', err.message, 'error');
  3976. }
  3977. }
  3978. function submitSaveNATRule(e) {
  3979. if (e && e.preventDefault) e.preventDefault();
  3980. return applyNATRule(true);
  3981. }
  3982. function startNATStatPolling() {
  3983. stopNATStatPolling();
  3984. pollNATRuleStats();
  3985. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  3986. }
  3987. function stopNATStatPolling() {
  3988. if (state.natStatInterval) {
  3989. clearInterval(state.natStatInterval);
  3990. state.natStatInterval = null;
  3991. }
  3992. }
  3993. async function pollNATRuleStats() {
  3994. const id = document.getElementById('nat-modal-id')?.value;
  3995. if (!id) {
  3996. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  3997. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  3998. return;
  3999. }
  4000. try {
  4001. const res = await fetch(`${API_BASE}/firewall/nat`);
  4002. if (!res.ok) return;
  4003. const rules = await res.json();
  4004. const r = rules.find(x => x.id === id);
  4005. if (!r) return;
  4006. const now = Date.now();
  4007. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  4008. state.natLastTimestamp = now;
  4009. const curBytes = r.bytes || 0;
  4010. const curPackets = r.packets || 0;
  4011. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  4012. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  4013. state.natLastBytes = curBytes;
  4014. state.natLastPackets = curPackets;
  4015. const rateBps = Math.round((deltaBytes * 8) / dt);
  4016. const ratePkt = Math.round(deltaPkts / dt);
  4017. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  4018. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  4019. state.natStatRateHistory.push(rateBps);
  4020. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  4021. state.natStatPktHistory.push(ratePkt);
  4022. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  4023. const bEl = document.getElementById('nat-stat-bytes');
  4024. const pEl = document.getElementById('nat-stat-packets');
  4025. const rEl = document.getElementById('nat-stat-rate');
  4026. const prEl = document.getElementById('nat-stat-pktrate');
  4027. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4028. if (pEl) pEl.value = curPackets.toLocaleString();
  4029. if (rEl) rEl.value = formatBps(rateBps);
  4030. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4031. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4032. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4033. } catch (e) {
  4034. console.error('Error polling NAT rule stats', e);
  4035. }
  4036. }
  4037. async function moveNATRule(id, dir) {
  4038. try {
  4039. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  4040. method: 'POST',
  4041. headers: { 'Content-Type': 'application/json' },
  4042. body: JSON.stringify({ direction: dir })
  4043. });
  4044. if (res.ok) loadFirewall(false);
  4045. } catch (err) {
  4046. showToast('Error', err.message, 'error');
  4047. }
  4048. }
  4049. async function toggleNATRuleState(id, disabled) {
  4050. try {
  4051. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  4052. method: 'POST',
  4053. headers: { 'Content-Type': 'application/json' },
  4054. body: JSON.stringify({ disabled })
  4055. });
  4056. if (res.ok) loadFirewall(false);
  4057. } catch (err) {
  4058. showToast('Error', err.message, 'error');
  4059. }
  4060. }
  4061. async function deleteNATRule(id) {
  4062. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  4063. try {
  4064. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4065. if (res.ok) {
  4066. showToast('Deleted', 'NAT rule removed', 'success');
  4067. loadFirewall(false);
  4068. }
  4069. } catch (err) {
  4070. showToast('Error', err.message, 'error');
  4071. }
  4072. }
  4073. // ----------------- Mangle Rules -----------------
  4074. function renderMangleRules() {
  4075. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  4076. const tbody = document.getElementById('mangle-table-body');
  4077. const empty = document.getElementById('mangle-empty');
  4078. if (!tbody) return;
  4079. tbody.innerHTML = '';
  4080. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4081. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  4082. if (rules.length === 0) {
  4083. empty?.classList.remove('hidden');
  4084. return;
  4085. }
  4086. empty?.classList.add('hidden');
  4087. rules.forEach((r, idx) => {
  4088. const tr = document.createElement('tr');
  4089. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4090. let markVal = '<span class="text-slate-500">-</span>';
  4091. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  4092. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  4093. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  4094. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  4095. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  4096. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  4097. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  4098. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  4099. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  4100. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4101. 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>`;
  4102. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4103. tr.innerHTML = `
  4104. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4105. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4106. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  4107. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4108. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4109. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4110. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  4111. <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>
  4112. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4113. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  4114. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4115. </td>
  4116. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4117. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4118. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4119. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4120. <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>
  4121. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4122. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4123. </td>
  4124. `;
  4125. tbody.appendChild(tr);
  4126. });
  4127. }
  4128. // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4129. function switchMangleRuleTab(tab) {
  4130. state.activeMangleRuleTab = tab;
  4131. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4132. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4133. btn.classList.add('text-slate-400', 'border-transparent');
  4134. });
  4135. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4136. if (activeBtn) {
  4137. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4138. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4139. }
  4140. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4141. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4142. if (activePane) activePane.classList.remove('hidden');
  4143. if (tab === 'statistics') {
  4144. startMangleStatPolling();
  4145. } else {
  4146. stopMangleStatPolling();
  4147. }
  4148. }
  4149. function toggleMangleField(fieldKey, expand) {
  4150. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4151. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4152. if (!plusBtn || !fieldBox) return;
  4153. if (expand) {
  4154. plusBtn.classList.add('hidden');
  4155. fieldBox.classList.remove('hidden');
  4156. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4157. if (valInput) valInput.focus();
  4158. } else {
  4159. fieldBox.classList.add('hidden');
  4160. plusBtn.classList.remove('hidden');
  4161. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4162. if (valInput) {
  4163. if (valInput.tagName === 'SELECT') {
  4164. valInput.selectedIndex = 0;
  4165. } else {
  4166. valInput.value = '';
  4167. }
  4168. }
  4169. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4170. if (invInput) invInput.checked = false;
  4171. if (fieldKey === 'cs') {
  4172. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4173. const el = document.getElementById(id);
  4174. if (el) el.checked = false;
  4175. });
  4176. }
  4177. if (fieldKey === 'natstate') {
  4178. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4179. const el = document.getElementById(id);
  4180. if (el) el.checked = false;
  4181. });
  4182. }
  4183. }
  4184. }
  4185. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4186. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4187. toggleMangleField(fieldKey, true);
  4188. let strVal = String(value);
  4189. if (hasInvert) {
  4190. const inv = strVal.startsWith('!');
  4191. if (inv) strVal = strVal.slice(1);
  4192. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4193. if (invEl) invEl.checked = inv;
  4194. }
  4195. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4196. if (valEl) valEl.value = strVal;
  4197. } else {
  4198. toggleMangleField(fieldKey, false);
  4199. }
  4200. }
  4201. function getMangleFieldVal(fieldKey, hasInvert = false) {
  4202. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4203. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4204. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4205. let v = valEl ? valEl.value.trim() : '';
  4206. if (!v) return '';
  4207. if (hasInvert) {
  4208. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4209. if (invEl && invEl.checked) {
  4210. v = '!' + v.replace(/^!/, '');
  4211. }
  4212. }
  4213. return v;
  4214. }
  4215. function toggleMaximizeMangleModal() {
  4216. const win = document.getElementById('mangle-modal-window');
  4217. if (!win) return;
  4218. if (win.classList.contains('max-w-[720px]')) {
  4219. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4220. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4221. } else {
  4222. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4223. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4224. }
  4225. }
  4226. function toggleMangleActionFields() {
  4227. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  4228. // Hide all dynamic rows first
  4229. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  4230. const el = document.getElementById(`mangle-row-${id}`);
  4231. if (el) el.classList.add('hidden');
  4232. });
  4233. const jumpBox = document.getElementById('mangle-action-jump-box');
  4234. const addrBox = document.getElementById('mangle-action-addrlist-box');
  4235. if (jumpBox) jumpBox.classList.add('hidden');
  4236. if (addrBox) addrBox.classList.add('hidden');
  4237. // Activate matching rows
  4238. if (act === 'mark-connection') {
  4239. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  4240. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4241. } else if (act === 'mark-routing') {
  4242. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  4243. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4244. } else if (act === 'mark-packet') {
  4245. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  4246. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4247. } else if (act === 'change-mss') {
  4248. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  4249. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4250. } else if (act === 'change-dscp') {
  4251. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  4252. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4253. } else if (act === 'change-ttl') {
  4254. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  4255. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4256. } else if (act === 'set-priority') {
  4257. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  4258. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4259. } else if (act === 'route') {
  4260. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  4261. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4262. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  4263. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  4264. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4265. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  4266. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4267. } else if (act === 'jump') {
  4268. if (jumpBox) jumpBox.classList.remove('hidden');
  4269. } else if (act.includes('address-list') || act.includes('address list')) {
  4270. if (addrBox) addrBox.classList.remove('hidden');
  4271. }
  4272. if (act === 'log') {
  4273. const logEl = document.getElementById('mangle-modal-log');
  4274. if (logEl) logEl.checked = true;
  4275. toggleMangleField('logprefix', true);
  4276. }
  4277. }
  4278. function toggleMangleLogPrefix() {
  4279. const isLog = document.getElementById('mangle-modal-log')?.checked;
  4280. toggleMangleField('logprefix', !!isLog);
  4281. }
  4282. const allMangleFieldKeys = [
  4283. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4284. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4285. 'routingmark', 'conntype', 'cs', 'natstate',
  4286. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4287. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4288. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4289. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  4290. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  4291. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  4292. ];
  4293. function openAddMangleModal() {
  4294. switchMangleRuleTab('general');
  4295. const badge = document.getElementById('mangle-modal-badge');
  4296. if (badge) badge.innerText = 'New...';
  4297. document.getElementById('mangle-modal-id').value = '';
  4298. document.getElementById('mangle-modal-enabled').checked = true;
  4299. document.getElementById('mangle-modal-comment').value = '';
  4300. document.getElementById('mangle-modal-chain').value = 'prerouting';
  4301. document.getElementById('mangle-modal-action').value = 'mark-connection';
  4302. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  4303. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  4304. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  4305. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  4306. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  4307. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  4308. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  4309. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  4310. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  4311. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  4312. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  4313. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  4314. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  4315. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  4316. populateInterfaceSelect('mangle-val-iniface');
  4317. populateInterfaceSelect('mangle-val-outiface');
  4318. populateAddressListSelect('mangle-val-srclist');
  4319. populateAddressListSelect('mangle-val-dstlist');
  4320. populateGeoIPSelect('mangle-val-srcgeo');
  4321. populateGeoIPSelect('mangle-val-dstgeo');
  4322. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  4323. resetCurrentMangleRuleCounters();
  4324. toggleMangleActionFields();
  4325. document.getElementById('mangle-modal').classList.remove('hidden');
  4326. }
  4327. function openEditMangleModal(id) {
  4328. const r = (state.mangleRules || []).find(rule => rule.id === id);
  4329. if (!r) return;
  4330. switchMangleRuleTab('general');
  4331. const badge = document.getElementById('mangle-modal-badge');
  4332. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4333. document.getElementById('mangle-modal-id').value = r.id;
  4334. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  4335. document.getElementById('mangle-modal-comment').value = r.comment || '';
  4336. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  4337. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  4338. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  4339. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  4340. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  4341. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  4342. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  4343. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  4344. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  4345. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  4346. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  4347. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  4348. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  4349. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  4350. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  4351. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  4352. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4353. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4354. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4355. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4356. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  4357. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  4358. setMangleFieldVal('src', r.src_address, true);
  4359. setMangleFieldVal('dst', r.dst_address, true);
  4360. setMangleFieldVal('srclist', r.src_address_list, true);
  4361. setMangleFieldVal('dstlist', r.dst_address_list, true);
  4362. setMangleFieldVal('srcgeo', r.src_geoip, true);
  4363. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  4364. if (r.protocol && r.protocol !== 'all') {
  4365. setMangleFieldVal('proto', r.protocol, true);
  4366. } else {
  4367. toggleMangleField('proto', false);
  4368. }
  4369. setMangleFieldVal('sport', r.src_port, true);
  4370. setMangleFieldVal('dport', r.dst_port, true);
  4371. setMangleFieldVal('anyport', r.any_port, true);
  4372. setMangleFieldVal('iniface', r.in_interface, true);
  4373. setMangleFieldVal('outiface', r.out_interface, true);
  4374. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  4375. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  4376. setMangleFieldVal('pktmark', r.packet_mark, true);
  4377. setMangleFieldVal('connmark', r.connection_mark, true);
  4378. setMangleFieldVal('routingmark', r.routing_mark, true);
  4379. setMangleFieldVal('conntype', r.connection_type, false);
  4380. // Connection State
  4381. const states = r.connection_state || [];
  4382. if (states.length > 0) {
  4383. toggleMangleField('cs', true);
  4384. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4385. const el = document.getElementById(`mangle-modal-cs-${s}`);
  4386. if (el) el.checked = states.includes(s);
  4387. });
  4388. } else {
  4389. toggleMangleField('cs', false);
  4390. }
  4391. // Connection NAT State
  4392. const natStates = r.connection_nat_state || [];
  4393. if (natStates.length > 0) {
  4394. toggleMangleField('natstate', true);
  4395. ['srcnat', 'dstnat'].forEach(s => {
  4396. const el = document.getElementById(`mangle-modal-nat-${s}`);
  4397. if (el) el.checked = natStates.includes(s);
  4398. });
  4399. } else {
  4400. toggleMangleField('natstate', false);
  4401. }
  4402. // Advanced tab fields
  4403. setMangleFieldVal('layer7', r.layer7_protocol, false);
  4404. setMangleFieldVal('content', r.content, false);
  4405. setMangleFieldVal('connbytes', r.connection_bytes, false);
  4406. setMangleFieldVal('connrate', r.connection_rate, false);
  4407. setMangleFieldVal('pcc', r.pcc, false);
  4408. setMangleFieldVal('srcmac', r.src_mac_address, true);
  4409. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  4410. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  4411. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4412. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4413. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  4414. setMangleFieldVal('tlshost', r.tls_host, false);
  4415. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  4416. setMangleFieldVal('priority', r.priority, false);
  4417. setMangleFieldVal('dscp', r.dscp, false);
  4418. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  4419. if (r.tos) {
  4420. const tosEl = document.getElementById('mangle-val-tos');
  4421. if (tosEl) tosEl.value = r.tos;
  4422. }
  4423. setMangleFieldVal('pktsize', r.packet_size, false);
  4424. setMangleFieldVal('random', r.random, false);
  4425. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  4426. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  4427. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  4428. setMangleFieldVal('ttl', r.ttl, false);
  4429. // Extra tab fields
  4430. setMangleFieldVal('nth', r.nth, false);
  4431. setMangleFieldVal('connlimit', r.connection_limit, false);
  4432. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  4433. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  4434. setMangleFieldVal('hotspot', r.hotspot, false);
  4435. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  4436. setMangleFieldVal('limit', r.limit, false);
  4437. setMangleFieldVal('dstlimit', r.dst_limit, false);
  4438. setMangleFieldVal('time', r.time, false);
  4439. setMangleFieldVal('psd', r.psd, false);
  4440. // Action fields
  4441. if (r.jump_target) {
  4442. const jtEl = document.getElementById('mangle-modal-jumptarget');
  4443. if (jtEl) jtEl.value = r.jump_target;
  4444. }
  4445. if (r.address_list) {
  4446. const alEl = document.getElementById('mangle-modal-action-addrlist');
  4447. if (alEl) alEl.value = r.address_list;
  4448. }
  4449. if (r.address_list_timeout) {
  4450. const toEl = document.getElementById('mangle-modal-action-timeout');
  4451. if (toEl) toEl.value = r.address_list_timeout;
  4452. }
  4453. setMangleFieldVal('logprefix', r.log_prefix, false);
  4454. // Statistics
  4455. const bEl = document.getElementById('mangle-stat-bytes');
  4456. const pEl = document.getElementById('mangle-stat-packets');
  4457. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4458. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4459. state.mangleLastBytes = r.bytes || 0;
  4460. state.mangleLastPackets = r.packets || 0;
  4461. state.mangleLastTimestamp = Date.now();
  4462. state.mangleStatRateHistory = new Array(30).fill(0);
  4463. state.mangleStatPktHistory = new Array(30).fill(0);
  4464. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4465. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4466. toggleMangleActionFields();
  4467. document.getElementById('mangle-modal').classList.remove('hidden');
  4468. }
  4469. function closeMangleModal() {
  4470. stopMangleStatPolling();
  4471. document.getElementById('mangle-modal').classList.add('hidden');
  4472. }
  4473. function copyMangleRule() {
  4474. document.getElementById('mangle-modal-id').value = '';
  4475. const badge = document.getElementById('mangle-modal-badge');
  4476. if (badge) badge.innerText = 'New...';
  4477. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  4478. }
  4479. function resetCurrentMangleRuleCounters() {
  4480. state.mangleStatRateHistory = new Array(30).fill(0);
  4481. state.mangleStatPktHistory = new Array(30).fill(0);
  4482. state.mangleLastBytes = 0;
  4483. state.mangleLastPackets = 0;
  4484. state.mangleLastTimestamp = Date.now();
  4485. const bEl = document.getElementById('mangle-stat-bytes');
  4486. const pEl = document.getElementById('mangle-stat-packets');
  4487. const rEl = document.getElementById('mangle-stat-rate');
  4488. const prEl = document.getElementById('mangle-stat-pktrate');
  4489. if (bEl) bEl.value = '0 B';
  4490. if (pEl) pEl.value = '0';
  4491. if (rEl) rEl.value = '0 bps';
  4492. if (prEl) prEl.value = '0 p/s';
  4493. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4494. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4495. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  4496. }
  4497. async function applyMangleRule(closeAfter = false) {
  4498. const id = document.getElementById('mangle-modal-id').value;
  4499. const chain = document.getElementById('mangle-modal-chain').value;
  4500. const action = document.getElementById('mangle-modal-action').value;
  4501. const comment = document.getElementById('mangle-modal-comment').value.trim();
  4502. const enabled = document.getElementById('mangle-modal-enabled').checked;
  4503. const src = getMangleFieldVal('src', true);
  4504. const dst = getMangleFieldVal('dst', true);
  4505. const srclist = getMangleFieldVal('srclist', true);
  4506. const dstlist = getMangleFieldVal('dstlist', true);
  4507. const srcgeo = getMangleFieldVal('srcgeo', true);
  4508. const dstgeo = getMangleFieldVal('dstgeo', true);
  4509. const proto = getMangleFieldVal('proto', true);
  4510. const sport = getMangleFieldVal('sport', true);
  4511. const dport = getMangleFieldVal('dport', true);
  4512. const anyport = getMangleFieldVal('anyport', true);
  4513. const iniface = getMangleFieldVal('iniface', true);
  4514. const outiface = getMangleFieldVal('outiface', true);
  4515. const inifacelist = getMangleFieldVal('inifacelist', true);
  4516. const outifacelist = getMangleFieldVal('outifacelist', true);
  4517. const pktmark = getMangleFieldVal('pktmark', true);
  4518. const connmark = getMangleFieldVal('connmark', true);
  4519. const routingmark = getMangleFieldVal('routingmark', true);
  4520. const conntype = getMangleFieldVal('conntype', false);
  4521. const states = [];
  4522. const csBox = document.getElementById('mangle-field-cs');
  4523. if (csBox && !csBox.classList.contains('hidden')) {
  4524. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4525. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  4526. });
  4527. }
  4528. const natStates = [];
  4529. const natBox = document.getElementById('mangle-field-natstate');
  4530. if (natBox && !natBox.classList.contains('hidden')) {
  4531. ['srcnat', 'dstnat'].forEach(s => {
  4532. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  4533. });
  4534. }
  4535. const payload = {
  4536. id,
  4537. chain,
  4538. action,
  4539. protocol: proto || 'all',
  4540. src_address: src,
  4541. dst_address: dst,
  4542. src_port: sport,
  4543. dst_port: dport,
  4544. any_port: anyport,
  4545. in_interface: iniface,
  4546. out_interface: outiface,
  4547. in_interface_list: inifacelist,
  4548. out_interface_list: outifacelist,
  4549. packet_mark: pktmark,
  4550. connection_mark: connmark,
  4551. routing_mark: routingmark,
  4552. connection_type: conntype,
  4553. connection_state: states,
  4554. connection_nat_state: natStates,
  4555. src_address_list: srclist,
  4556. dst_address_list: dstlist,
  4557. src_geoip: srcgeo,
  4558. dst_geoip: dstgeo,
  4559. comment,
  4560. disabled: !enabled,
  4561. // Advanced tab
  4562. layer7_protocol: getMangleFieldVal('layer7', false),
  4563. content: getMangleFieldVal('content', false),
  4564. connection_bytes: getMangleFieldVal('connbytes', false),
  4565. connection_rate: getMangleFieldVal('connrate', false),
  4566. pcc: getMangleFieldVal('pcc', false),
  4567. src_mac_address: getMangleFieldVal('srcmac', true),
  4568. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  4569. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  4570. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  4571. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  4572. ipsec_policy: getMangleFieldVal('ipsec', false),
  4573. tls_host: getMangleFieldVal('tlshost', false),
  4574. ingress_priority: getMangleFieldVal('ingresspriority', false),
  4575. priority: getMangleFieldVal('priority', false),
  4576. dscp: getMangleFieldVal('dscp', false),
  4577. tcp_mss: getMangleFieldVal('tcpmss', false),
  4578. tos: document.getElementById('mangle-val-tos')?.value || '',
  4579. packet_size: getMangleFieldVal('pktsize', false),
  4580. random: getMangleFieldVal('random', false),
  4581. tcp_flags: getMangleFieldVal('tcpflags', false),
  4582. icmp_options: getMangleFieldVal('icmpoptions', false),
  4583. ipv4_options: getMangleFieldVal('ipv4options', false),
  4584. ttl: getMangleFieldVal('ttl', false),
  4585. // Extra tab
  4586. nth: getMangleFieldVal('nth', false),
  4587. connection_limit: getMangleFieldVal('connlimit', false),
  4588. src_address_type: getMangleFieldVal('srcaddrtype', false),
  4589. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  4590. hotspot: getMangleFieldVal('hotspot', false),
  4591. ip_fragment: getMangleFieldVal('ipfragment', false),
  4592. limit: getMangleFieldVal('limit', false),
  4593. dst_limit: getMangleFieldVal('dstlimit', false),
  4594. time: getMangleFieldVal('time', false),
  4595. psd: getMangleFieldVal('psd', false),
  4596. // Action tab
  4597. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  4598. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  4599. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  4600. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  4601. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  4602. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  4603. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  4604. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  4605. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  4606. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  4607. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  4608. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  4609. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  4610. log: document.getElementById('mangle-modal-log')?.checked || false,
  4611. log_prefix: getMangleFieldVal('logprefix', false)
  4612. };
  4613. try {
  4614. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  4615. method: 'POST',
  4616. headers: { 'Content-Type': 'application/json' },
  4617. body: JSON.stringify(payload)
  4618. });
  4619. if (res.ok) {
  4620. const data = await res.json();
  4621. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  4622. loadFirewall(false);
  4623. if (closeAfter) {
  4624. closeMangleModal();
  4625. } else {
  4626. if (data.id) {
  4627. document.getElementById('mangle-modal-id').value = data.id;
  4628. const badge = document.getElementById('mangle-modal-badge');
  4629. if (badge) badge.innerText = `#${data.id}`;
  4630. }
  4631. }
  4632. } else {
  4633. const err = await res.json();
  4634. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  4635. }
  4636. } catch (err) {
  4637. showToast('Error', err.message, 'error');
  4638. }
  4639. }
  4640. function submitSaveMangleRule(e) {
  4641. if (e && e.preventDefault) e.preventDefault();
  4642. return applyMangleRule(true);
  4643. }
  4644. function startMangleStatPolling() {
  4645. stopMangleStatPolling();
  4646. pollMangleRuleStats();
  4647. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  4648. }
  4649. function stopMangleStatPolling() {
  4650. if (state.mangleStatInterval) {
  4651. clearInterval(state.mangleStatInterval);
  4652. state.mangleStatInterval = null;
  4653. }
  4654. }
  4655. async function pollMangleRuleStats() {
  4656. const id = document.getElementById('mangle-modal-id')?.value;
  4657. if (!id) {
  4658. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  4659. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  4660. return;
  4661. }
  4662. try {
  4663. const res = await fetch(`${API_BASE}/firewall/mangle`);
  4664. if (!res.ok) return;
  4665. const rules = await res.json();
  4666. const r = rules.find(x => x.id === id);
  4667. if (!r) return;
  4668. const now = Date.now();
  4669. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  4670. state.mangleLastTimestamp = now;
  4671. const curBytes = r.bytes || 0;
  4672. const curPackets = r.packets || 0;
  4673. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  4674. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  4675. state.mangleLastBytes = curBytes;
  4676. state.mangleLastPackets = curPackets;
  4677. const rateBps = Math.round((deltaBytes * 8) / dt);
  4678. const ratePkt = Math.round(deltaPkts / dt);
  4679. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  4680. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  4681. state.mangleStatRateHistory.push(rateBps);
  4682. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  4683. state.mangleStatPktHistory.push(ratePkt);
  4684. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  4685. const bEl = document.getElementById('mangle-stat-bytes');
  4686. const pEl = document.getElementById('mangle-stat-packets');
  4687. const rEl = document.getElementById('mangle-stat-rate');
  4688. const prEl = document.getElementById('mangle-stat-pktrate');
  4689. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4690. if (pEl) pEl.value = curPackets.toLocaleString();
  4691. if (rEl) rEl.value = formatBps(rateBps);
  4692. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4693. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4694. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4695. } catch (e) {
  4696. console.error('Error polling Mangle rule stats', e);
  4697. }
  4698. }
  4699. async function moveMangleRule(id, dir) {
  4700. try {
  4701. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  4702. method: 'POST',
  4703. headers: { 'Content-Type': 'application/json' },
  4704. body: JSON.stringify({ direction: dir })
  4705. });
  4706. if (res.ok) loadFirewall(false);
  4707. } catch (err) {
  4708. showToast('Error', err.message, 'error');
  4709. }
  4710. }
  4711. async function toggleMangleRuleState(id, disabled) {
  4712. try {
  4713. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  4714. method: 'POST',
  4715. headers: { 'Content-Type': 'application/json' },
  4716. body: JSON.stringify({ disabled })
  4717. });
  4718. if (res.ok) loadFirewall(false);
  4719. } catch (err) {
  4720. showToast('Error', err.message, 'error');
  4721. }
  4722. }
  4723. async function deleteMangleRule(id) {
  4724. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  4725. try {
  4726. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4727. if (res.ok) {
  4728. showToast('Deleted', 'Mangle rule removed', 'success');
  4729. loadFirewall(false);
  4730. }
  4731. } catch (err) {
  4732. showToast('Error', err.message, 'error');
  4733. }
  4734. }
  4735. // ----------------- Address Lists -----------------
  4736. function renderAddressLists() {
  4737. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  4738. const tbody = document.getElementById('addrlist-table-body');
  4739. const empty = document.getElementById('addrlist-empty');
  4740. if (!tbody) return;
  4741. tbody.innerHTML = '';
  4742. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  4743. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  4744. // Update filter select
  4745. const sel = document.getElementById('addrlist-filter-name');
  4746. if (sel) {
  4747. const cur = sel.value;
  4748. sel.innerHTML = '<option value="">All Lists</option>';
  4749. const set = new Set((state.addressLists || []).map(a => a.name));
  4750. set.forEach(n => {
  4751. const opt = document.createElement('option');
  4752. opt.value = n;
  4753. opt.innerText = n;
  4754. if (n === cur) opt.selected = true;
  4755. sel.appendChild(opt);
  4756. });
  4757. }
  4758. if (entries.length === 0) {
  4759. empty?.classList.remove('hidden');
  4760. return;
  4761. }
  4762. empty?.classList.add('hidden');
  4763. entries.forEach((e, idx) => {
  4764. const tr = document.createElement('tr');
  4765. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  4766. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  4767. tr.innerHTML = `
  4768. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  4769. <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>
  4770. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  4771. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  4772. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  4773. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4774. <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>
  4775. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  4776. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4777. </td>
  4778. `;
  4779. tbody.appendChild(tr);
  4780. });
  4781. populateCommonAddrListDatalist();
  4782. }
  4783. function openAddAddrListModal() {
  4784. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  4785. document.getElementById('addrlist-modal-id').value = '';
  4786. document.getElementById('addrlist-modal-name').value = '';
  4787. document.getElementById('addrlist-modal-addr').value = '';
  4788. document.getElementById('addrlist-modal-comment').value = '';
  4789. document.getElementById('addrlist-modal-disabled').checked = false;
  4790. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4791. if (submitBtn) submitBtn.innerText = 'Add to List';
  4792. document.getElementById('addrlist-modal').classList.remove('hidden');
  4793. }
  4794. function openEditAddrListModal(id) {
  4795. const e = (state.addressLists || []).find(item => item.id === id);
  4796. if (!e) return;
  4797. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  4798. document.getElementById('addrlist-modal-id').value = e.id;
  4799. document.getElementById('addrlist-modal-name').value = e.name;
  4800. document.getElementById('addrlist-modal-addr').value = e.address;
  4801. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  4802. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  4803. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4804. if (submitBtn) submitBtn.innerText = 'Save Changes';
  4805. document.getElementById('addrlist-modal').classList.remove('hidden');
  4806. }
  4807. function closeAddrListModal() {
  4808. document.getElementById('addrlist-modal').classList.add('hidden');
  4809. }
  4810. async function submitSaveAddrList(e) {
  4811. e.preventDefault();
  4812. const id = document.getElementById('addrlist-modal-id').value;
  4813. const name = document.getElementById('addrlist-modal-name').value.trim();
  4814. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  4815. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  4816. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  4817. try {
  4818. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  4819. method: 'POST',
  4820. headers: { 'Content-Type': 'application/json' },
  4821. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  4822. });
  4823. if (res.ok) {
  4824. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  4825. closeAddrListModal();
  4826. loadFirewall(false);
  4827. } else {
  4828. const err = await res.json();
  4829. showToast('Error', err.message || 'Failed to save address list', 'error');
  4830. }
  4831. } catch (err) {
  4832. showToast('Error', err.message, 'error');
  4833. }
  4834. }
  4835. async function toggleAddrListState(id, disabled) {
  4836. try {
  4837. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  4838. method: 'POST',
  4839. headers: { 'Content-Type': 'application/json' },
  4840. body: JSON.stringify({ disabled })
  4841. });
  4842. if (res.ok) {
  4843. loadFirewall(false);
  4844. }
  4845. } catch (err) {
  4846. showToast('Error', err.message, 'error');
  4847. }
  4848. }
  4849. async function deleteAddrList(id) {
  4850. if (!confirm('Are you sure you want to delete this address list item?')) return;
  4851. try {
  4852. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4853. if (res.ok) {
  4854. showToast('Deleted', 'Address list item removed', 'info');
  4855. loadFirewall(false);
  4856. }
  4857. } catch (err) {
  4858. showToast('Error', err.message, 'error');
  4859. }
  4860. }
  4861. // ----------------- Geo-Location IP Management -----------------
  4862. async function loadGeoIP() {
  4863. try {
  4864. const [statusRes, countriesRes] = await Promise.all([
  4865. fetch(`${API_BASE}/firewall/geoip/status`),
  4866. fetch(`${API_BASE}/firewall/geoip/countries`)
  4867. ]);
  4868. if (statusRes.ok) state.geoStatus = await statusRes.json();
  4869. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  4870. updateGeoHeader();
  4871. renderGeoCountries();
  4872. } catch (err) {
  4873. console.error('Failed to load GeoIP:', err);
  4874. }
  4875. }
  4876. function getGeoUsageMap() {
  4877. const usage = {};
  4878. const checkRule = (r, type) => {
  4879. ['src_geoip', 'dst_geoip'].forEach(field => {
  4880. let val = (r && r[field]) || '';
  4881. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  4882. if (code) {
  4883. if (!usage[code]) usage[code] = [];
  4884. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  4885. if (!usage[code].includes(label)) usage[code].push(label);
  4886. }
  4887. });
  4888. };
  4889. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  4890. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  4891. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  4892. return usage;
  4893. }
  4894. function updateGeoHeader() {
  4895. const s = state.geoStatus || {};
  4896. const statusBadge = document.getElementById('geo-status-badge');
  4897. if (statusBadge) {
  4898. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  4899. statusBadge.className = s.auto_update
  4900. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  4901. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  4902. }
  4903. const intervalLabel = document.getElementById('geo-interval-label');
  4904. if (intervalLabel) {
  4905. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  4906. }
  4907. const usageMap = getGeoUsageMap();
  4908. const inUseCount = Object.keys(usageMap).length;
  4909. const activeCountEl = document.getElementById('geo-stat-active-countries');
  4910. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  4911. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  4912. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  4913. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  4914. if (lastSyncEl) {
  4915. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  4916. const d = new Date(s.last_updated);
  4917. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4918. } else {
  4919. lastSyncEl.innerText = 'Never (Sync Pending)';
  4920. }
  4921. }
  4922. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  4923. if (nextSyncEl) {
  4924. if (s.next_update && !s.next_update.startsWith('0001')) {
  4925. const d = new Date(s.next_update);
  4926. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4927. } else {
  4928. nextSyncEl.innerText = '-';
  4929. }
  4930. }
  4931. const badge = document.getElementById('fw-badge-geo');
  4932. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  4933. }
  4934. function renderGeoCountries() {
  4935. const tbody = document.getElementById('geo-table-body');
  4936. const empty = document.getElementById('geo-empty');
  4937. if (!tbody) return;
  4938. tbody.innerHTML = '';
  4939. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  4940. const continent = document.getElementById('geo-continent-filter')?.value || '';
  4941. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  4942. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  4943. const usageMap = getGeoUsageMap();
  4944. const countries = (state.geoCountries || []).filter(c => {
  4945. const isUsed = !!usageMap[c.code];
  4946. if (inUseOnly && !isUsed) return false;
  4947. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  4948. if (continent && c.continent !== continent) return false;
  4949. if (q) {
  4950. const matchCode = c.code.toLowerCase().includes(q);
  4951. const matchName = c.name.toLowerCase().includes(q);
  4952. if (!matchCode && !matchName) return false;
  4953. }
  4954. return true;
  4955. });
  4956. if (countries.length === 0) {
  4957. empty?.classList.remove('hidden');
  4958. return;
  4959. }
  4960. empty?.classList.add('hidden');
  4961. countries.forEach(c => {
  4962. const tr = document.createElement('tr');
  4963. const isUsed = !!usageMap[c.code];
  4964. const rulesUsing = usageMap[c.code] || [];
  4965. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  4966. let statusHtml = '';
  4967. if (isUsed) {
  4968. 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>`;
  4969. } else if (c.subnet_count > 0) {
  4970. 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>';
  4971. } else {
  4972. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  4973. }
  4974. tr.innerHTML = `
  4975. <td class="py-2.5 px-3 text-center">
  4976. <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'}">
  4977. ${c.code}
  4978. </span>
  4979. </td>
  4980. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  4981. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  4982. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  4983. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  4984. </td>
  4985. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  4986. <td class="py-2.5 px-3">
  4987. ${statusHtml}
  4988. </td>
  4989. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4990. <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>
  4991. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  4992. </td>
  4993. `;
  4994. tbody.appendChild(tr);
  4995. });
  4996. }
  4997. function quickFilterGeo(preset) {
  4998. const searchInput = document.getElementById('geo-search-input');
  4999. const continentSel = document.getElementById('geo-continent-filter');
  5000. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  5001. const cachedCheck = document.getElementById('geo-filter-cached-only');
  5002. if (searchInput) searchInput.value = '';
  5003. if (continentSel) continentSel.value = '';
  5004. if (inUseCheck) inUseCheck.checked = false;
  5005. if (cachedCheck) cachedCheck.checked = false;
  5006. if (preset === 'GR') {
  5007. if (searchInput) searchInput.value = 'Greece';
  5008. } else if (preset === 'Europe') {
  5009. if (continentSel) continentSel.value = 'Europe';
  5010. } else if (preset === 'HIGHRISK') {
  5011. if (searchInput) searchInput.value = 'China';
  5012. }
  5013. renderGeoCountries();
  5014. }
  5015. async function toggleGeoCountry(code, enabled) {
  5016. try {
  5017. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  5018. method: 'POST',
  5019. headers: { 'Content-Type': 'application/json' },
  5020. body: JSON.stringify({ enabled })
  5021. });
  5022. if (res.ok) {
  5023. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  5024. loadGeoIP();
  5025. } else {
  5026. const err = await res.json();
  5027. showToast('Error', err.message || 'Failed to toggle country', 'error');
  5028. }
  5029. } catch (err) {
  5030. showToast('Error', err.message, 'error');
  5031. }
  5032. }
  5033. async function updateGeoCountry(code) {
  5034. try {
  5035. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  5036. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  5037. if (res.ok) {
  5038. const data = await res.json();
  5039. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  5040. loadGeoIP();
  5041. } else {
  5042. const err = await res.json();
  5043. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  5044. }
  5045. } catch (err) {
  5046. showToast('Error', err.message, 'error');
  5047. }
  5048. }
  5049. async function triggerGeoUpdateNow() {
  5050. const spinner = document.getElementById('geo-update-spinner');
  5051. if (spinner) spinner.classList.remove('hidden');
  5052. try {
  5053. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  5054. if (res.ok) {
  5055. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  5056. setTimeout(() => {
  5057. loadGeoIP();
  5058. if (spinner) spinner.classList.add('hidden');
  5059. }, 2500);
  5060. } else {
  5061. const err = await res.json();
  5062. showToast('Notice', err.message || 'Update in progress', 'info');
  5063. if (spinner) spinner.classList.add('hidden');
  5064. }
  5065. } catch (err) {
  5066. showToast('Error', err.message, 'error');
  5067. if (spinner) spinner.classList.add('hidden');
  5068. }
  5069. }
  5070. async function applyGeoPreset(preset) {
  5071. try {
  5072. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  5073. method: 'POST',
  5074. headers: { 'Content-Type': 'application/json' },
  5075. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  5076. });
  5077. if (res.ok) {
  5078. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  5079. loadGeoIP();
  5080. }
  5081. } catch (err) {
  5082. showToast('Error', err.message, 'error');
  5083. }
  5084. }
  5085. function openGeoIntervalModal() {
  5086. const s = state.geoStatus || {};
  5087. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  5088. const sel = document.getElementById('geo-cfg-interval');
  5089. const customBox = document.getElementById('geo-cfg-custom-box');
  5090. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  5091. const curHours = s.interval_hours || 24;
  5092. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  5093. if (matchOption) {
  5094. sel.value = String(curHours);
  5095. customBox.classList.add('hidden');
  5096. } else {
  5097. sel.value = 'custom';
  5098. customHoursInput.value = curHours;
  5099. customBox.classList.remove('hidden');
  5100. }
  5101. document.getElementById('geo-interval-modal').classList.remove('hidden');
  5102. }
  5103. function closeGeoIntervalModal() {
  5104. document.getElementById('geo-interval-modal').classList.add('hidden');
  5105. }
  5106. function toggleCustomGeoInterval() {
  5107. const val = document.getElementById('geo-cfg-interval').value;
  5108. const customBox = document.getElementById('geo-cfg-custom-box');
  5109. if (val === 'custom') {
  5110. customBox.classList.remove('hidden');
  5111. } else {
  5112. customBox.classList.add('hidden');
  5113. }
  5114. }
  5115. async function submitGeoIntervalSettings(e) {
  5116. e.preventDefault();
  5117. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5118. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5119. let hours = 24;
  5120. if (intervalVal === 'custom') {
  5121. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5122. } else {
  5123. hours = parseInt(intervalVal, 10) || 24;
  5124. }
  5125. try {
  5126. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5127. method: 'POST',
  5128. headers: { 'Content-Type': 'application/json' },
  5129. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5130. });
  5131. if (res.ok) {
  5132. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5133. closeGeoIntervalModal();
  5134. loadGeoIP();
  5135. } else {
  5136. const err = await res.json();
  5137. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5138. }
  5139. } catch (err) {
  5140. showToast('Error', err.message, 'error');
  5141. }
  5142. }
  5143. async function viewGeoSubnets(code, name) {
  5144. if (!name) {
  5145. const found = (state.geoCountries || []).find(x => x.code === code);
  5146. name = found ? found.name : code;
  5147. }
  5148. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5149. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5150. const listEl = document.getElementById('geo-subnets-list');
  5151. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5152. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5153. try {
  5154. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5155. if (res.ok) {
  5156. const data = await res.json();
  5157. const subnets = data.subnets || [];
  5158. if (subnets.length === 0) {
  5159. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5160. } else {
  5161. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5162. }
  5163. } else {
  5164. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5165. }
  5166. } catch (err) {
  5167. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5168. }
  5169. }
  5170. function closeGeoSubnetsModal() {
  5171. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5172. }
  5173. // ----------------- Active Connections Tracking -----------------
  5174. async function loadConnections() {
  5175. try {
  5176. const res = await fetch(`${API_BASE}/firewall/connections`);
  5177. const data = await res.json();
  5178. state.connections = Array.isArray(data) ? data : [];
  5179. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5180. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5181. renderConnections();
  5182. } catch (err) {
  5183. console.error('Failed to load connections:', err);
  5184. }
  5185. }
  5186. function renderConnections() {
  5187. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  5188. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  5189. const tbody = document.getElementById('conns-table-body');
  5190. const empty = document.getElementById('conns-empty');
  5191. if (!tbody) return;
  5192. tbody.innerHTML = '';
  5193. const conns = (state.connections || []).filter(c => {
  5194. if (protoFilter && c.protocol !== protoFilter) return false;
  5195. if (search) {
  5196. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  5197. if (!line.includes(search)) return false;
  5198. }
  5199. return true;
  5200. });
  5201. if (conns.length === 0) {
  5202. empty?.classList.remove('hidden');
  5203. return;
  5204. }
  5205. empty?.classList.add('hidden');
  5206. conns.slice(0, 150).forEach(c => {
  5207. const tr = document.createElement('tr');
  5208. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5209. let stateColor = 'text-slate-400';
  5210. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  5211. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  5212. tr.innerHTML = `
  5213. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  5214. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  5215. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  5216. <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>
  5217. <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>
  5218. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  5219. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  5220. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  5221. <td class="py-2.5 px-3 text-right font-sans">
  5222. <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>
  5223. </td>
  5224. `;
  5225. tbody.appendChild(tr);
  5226. });
  5227. }
  5228. async function killConnection(protocol, src, sport, dst, dport) {
  5229. try {
  5230. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  5231. method: 'POST',
  5232. headers: { 'Content-Type': 'application/json' },
  5233. body: JSON.stringify({ protocol, src, sport, dst, dport })
  5234. });
  5235. if (res.ok) {
  5236. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  5237. loadConnections();
  5238. }
  5239. } catch (err) {
  5240. showToast('Error', err.message, 'error');
  5241. }
  5242. }
  5243. async function resetFirewallCounters() {
  5244. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  5245. try {
  5246. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  5247. if (res.ok) {
  5248. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  5249. loadFirewall(false);
  5250. }
  5251. } catch (err) {
  5252. showToast('Error', err.message, 'error');
  5253. }
  5254. }
  5255. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  5256. function switchRoutesSubTab(tab) {
  5257. state.routesSubTab = tab;
  5258. const tabs = ['routes', 'rules', 'tables'];
  5259. tabs.forEach(t => {
  5260. const panel = document.getElementById(`routes-subtab-${t}`);
  5261. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  5262. if (panel) {
  5263. if (t === tab) panel.classList.remove('hidden');
  5264. else panel.classList.add('hidden');
  5265. }
  5266. if (btn) {
  5267. if (t === tab) {
  5268. 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';
  5269. } else {
  5270. 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';
  5271. }
  5272. }
  5273. });
  5274. setTimeout(initTableSorting, 50);
  5275. }
  5276. async function loadRoutes() {
  5277. try {
  5278. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  5279. fetch(`${API_BASE}/routes`),
  5280. fetch(`${API_BASE}/routing/rules`),
  5281. fetch(`${API_BASE}/routing/tables`)
  5282. ]);
  5283. if (routesRes.ok) state.routes = await routesRes.json();
  5284. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  5285. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  5286. const bRoutes = document.getElementById('routes-badge-routes');
  5287. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  5288. const showSystem = document.getElementById('prule-show-system')?.checked;
  5289. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5290. const bRules = document.getElementById('routes-badge-rules');
  5291. if (bRules) bRules.innerText = userRules.length;
  5292. const bTables = document.getElementById('routes-badge-tables');
  5293. if (bTables) bTables.innerText = (state.routingTables || []).length;
  5294. const bRoutesCount = document.getElementById('badge-routes-count');
  5295. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  5296. renderRoutesList();
  5297. renderPolicyRules();
  5298. renderRoutingTables();
  5299. } catch (err) {
  5300. console.error('Failed to load routing:', err);
  5301. }
  5302. }
  5303. function renderRoutesList() {
  5304. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  5305. const tbody = document.getElementById('routes-table-body');
  5306. const empty = document.getElementById('routes-empty');
  5307. if (!tbody) return;
  5308. tbody.innerHTML = '';
  5309. // Update table filter select
  5310. const sel = document.getElementById('routes-filter-table');
  5311. if (sel) {
  5312. const cur = sel.value;
  5313. sel.innerHTML = '<option value="">All Tables</option>';
  5314. (state.routingTables || []).forEach(t => {
  5315. const opt = document.createElement('option');
  5316. opt.value = t.name;
  5317. opt.innerText = t.name;
  5318. if (t.name === cur) opt.selected = true;
  5319. sel.appendChild(opt);
  5320. });
  5321. }
  5322. const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
  5323. document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
  5324. if (routes.length === 0) {
  5325. empty?.classList.remove('hidden');
  5326. return;
  5327. }
  5328. empty?.classList.add('hidden');
  5329. routes.forEach(r => {
  5330. const tr = document.createElement('tr');
  5331. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  5332. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  5333. // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
  5334. let flags = '';
  5335. if (r.dynamic) flags += 'D';
  5336. if (r.active) flags += 'A';
  5337. if (r.connect) flags += 'C';
  5338. if (r.static) flags += 'S';
  5339. if (r.disabled) flags += 'X';
  5340. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  5341. tr.innerHTML = `
  5342. <td class="py-2.5 px-3 text-center">
  5343. <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'}">
  5344. ${flags || '-'}
  5345. </span>
  5346. </td>
  5347. <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
  5348. <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>
  5349. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  5350. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  5351. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  5352. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  5353. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5354. ${r.static ? `
  5355. <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>
  5356. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  5357. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5358. ` : `
  5359. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  5360. `}
  5361. </td>
  5362. `;
  5363. tbody.appendChild(tr);
  5364. });
  5365. }
  5366. function openAddRouteModal() {
  5367. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  5368. document.getElementById('route-modal-id').value = '';
  5369. document.getElementById('route-modal-old-dst').value = '';
  5370. document.getElementById('route-modal-old-gw').value = '';
  5371. document.getElementById('route-modal-old-distance').value = '';
  5372. document.getElementById('route-modal-old-table').value = '';
  5373. document.getElementById('route-modal-old-iface').value = '';
  5374. const dstInput = document.getElementById('route-modal-dst');
  5375. const gwInput = document.getElementById('route-modal-gw');
  5376. const distInput = document.getElementById('route-modal-distance');
  5377. const ifaceSelect = document.getElementById('route-modal-iface');
  5378. const tableSelect = document.getElementById('route-modal-table');
  5379. const commentInput = document.getElementById('route-modal-comment');
  5380. const disCheck = document.getElementById('route-modal-disabled');
  5381. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5382. dstInput.disabled = false;
  5383. dstInput.value = '0.0.0.0/0';
  5384. gwInput.disabled = false;
  5385. gwInput.value = '';
  5386. distInput.disabled = false;
  5387. distInput.value = '1';
  5388. ifaceSelect.disabled = false;
  5389. tableSelect.disabled = false;
  5390. commentInput.disabled = false;
  5391. commentInput.value = '';
  5392. disCheck.disabled = false;
  5393. disCheck.checked = false;
  5394. if (saveBtn) saveBtn.classList.remove('hidden');
  5395. populateInterfaceSelect('route-modal-iface');
  5396. // Populate tables
  5397. tableSelect.innerHTML = '';
  5398. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5399. const opt = document.createElement('option');
  5400. opt.value = t.name;
  5401. opt.innerText = t.name;
  5402. if (t.name === 'main') opt.selected = true;
  5403. tableSelect.appendChild(opt);
  5404. });
  5405. document.getElementById('route-modal').classList.remove('hidden');
  5406. }
  5407. function openEditRouteModal(id) {
  5408. const r = (state.routes || []).find(route => route.id === id);
  5409. if (!r) return;
  5410. const isStatic = !!r.static;
  5411. document.getElementById('route-modal-title').innerText = isStatic
  5412. ? `Edit Route: ${r.dst_address}`
  5413. : `Route Properties (Read Only): ${r.dst_address}`;
  5414. document.getElementById('route-modal-id').value = r.id;
  5415. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  5416. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  5417. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  5418. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  5419. document.getElementById('route-modal-old-iface').value = r.interface || '';
  5420. const dstInput = document.getElementById('route-modal-dst');
  5421. const gwInput = document.getElementById('route-modal-gw');
  5422. const distInput = document.getElementById('route-modal-distance');
  5423. const ifaceSelect = document.getElementById('route-modal-iface');
  5424. const tableSelect = document.getElementById('route-modal-table');
  5425. const commentInput = document.getElementById('route-modal-comment');
  5426. const disCheck = document.getElementById('route-modal-disabled');
  5427. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5428. dstInput.value = r.dst_address;
  5429. gwInput.value = r.gateway || '';
  5430. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  5431. commentInput.value = r.comment || '';
  5432. disCheck.checked = !!r.disabled;
  5433. dstInput.disabled = !isStatic;
  5434. gwInput.disabled = !isStatic;
  5435. distInput.disabled = !isStatic;
  5436. ifaceSelect.disabled = !isStatic;
  5437. tableSelect.disabled = !isStatic;
  5438. commentInput.disabled = !isStatic;
  5439. disCheck.disabled = !isStatic;
  5440. if (saveBtn) {
  5441. if (isStatic) {
  5442. saveBtn.classList.remove('hidden');
  5443. } else {
  5444. saveBtn.classList.add('hidden');
  5445. }
  5446. }
  5447. populateInterfaceSelect('route-modal-iface', r.interface);
  5448. tableSelect.innerHTML = '';
  5449. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5450. const opt = document.createElement('option');
  5451. opt.value = t.name;
  5452. opt.innerText = t.name;
  5453. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  5454. tableSelect.appendChild(opt);
  5455. });
  5456. document.getElementById('route-modal').classList.remove('hidden');
  5457. }
  5458. function closeRouteModal() {
  5459. document.getElementById('route-modal').classList.add('hidden');
  5460. }
  5461. async function submitSaveRoute(e) {
  5462. e.preventDefault();
  5463. const id = document.getElementById('route-modal-id').value;
  5464. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  5465. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  5466. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  5467. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  5468. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  5469. const dst = document.getElementById('route-modal-dst').value.trim();
  5470. const gw = document.getElementById('route-modal-gw').value.trim();
  5471. const table = document.getElementById('route-modal-table').value;
  5472. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  5473. const iface = document.getElementById('route-modal-iface').value;
  5474. const comment = document.getElementById('route-modal-comment').value.trim();
  5475. const disabled = document.getElementById('route-modal-disabled').checked;
  5476. if (!dst) {
  5477. showToast('Error', 'Destination address is required', 'error');
  5478. return;
  5479. }
  5480. if (!gw && !iface) {
  5481. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  5482. return;
  5483. }
  5484. const payload = {
  5485. id,
  5486. old_dst_address: oldDst,
  5487. old_gateway: oldGw,
  5488. old_routing_table: oldTable,
  5489. old_interface: oldIface,
  5490. dst_address: dst,
  5491. gateway: gw || iface,
  5492. routing_table: table,
  5493. distance,
  5494. interface: iface,
  5495. comment,
  5496. disabled
  5497. };
  5498. if (oldDistStr !== undefined && oldDistStr !== '') {
  5499. payload.old_distance = parseInt(oldDistStr, 10);
  5500. }
  5501. try {
  5502. const res = await fetch(`${API_BASE}/routes`, {
  5503. method: 'POST',
  5504. headers: { 'Content-Type': 'application/json' },
  5505. body: JSON.stringify(payload)
  5506. });
  5507. if (res.ok) {
  5508. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  5509. closeRouteModal();
  5510. loadRoutes();
  5511. } else {
  5512. const err = await res.json();
  5513. showToast('Error', err.message || 'Failed to save route', 'error');
  5514. }
  5515. } catch (err) {
  5516. showToast('Error', err.message, 'error');
  5517. }
  5518. }
  5519. async function toggleRouteState(id, disabled) {
  5520. try {
  5521. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  5522. method: 'POST',
  5523. headers: { 'Content-Type': 'application/json' },
  5524. body: JSON.stringify({ disabled })
  5525. });
  5526. if (res.ok) loadRoutes();
  5527. } catch (err) {
  5528. showToast('Error', err.message, 'error');
  5529. }
  5530. }
  5531. async function deleteRoute(id) {
  5532. if (!confirm('Are you sure you want to delete this route?')) return;
  5533. try {
  5534. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5535. if (res.ok) {
  5536. showToast('Deleted', 'Route removed', 'success');
  5537. loadRoutes();
  5538. }
  5539. } catch (err) {
  5540. showToast('Error', err.message, 'error');
  5541. }
  5542. }
  5543. // ----------------- Policy Rules (/ip route rule) -----------------
  5544. function renderPolicyRules() {
  5545. const tbody = document.getElementById('rules-table-body');
  5546. const empty = document.getElementById('rules-empty');
  5547. if (!tbody) return;
  5548. tbody.innerHTML = '';
  5549. const showSystem = document.getElementById('prule-show-system')?.checked;
  5550. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5551. const countBadge = document.getElementById('rules-count-badge');
  5552. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  5553. const bRules = document.getElementById('routes-badge-rules');
  5554. if (bRules) bRules.innerText = filtered.length;
  5555. if (filtered.length === 0) {
  5556. empty?.classList.remove('hidden');
  5557. return;
  5558. }
  5559. empty?.classList.add('hidden');
  5560. filtered.forEach(pr => {
  5561. const isSys = pr.is_default || pr.is_system;
  5562. const tr = document.createElement('tr');
  5563. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  5564. tr.innerHTML = `
  5565. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  5566. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  5567. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  5568. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  5569. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  5570. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  5571. <td class="py-2.5 px-3 text-right font-sans">
  5572. ${!pr.is_default ? `
  5573. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5574. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  5575. </td>
  5576. `;
  5577. tbody.appendChild(tr);
  5578. });
  5579. }
  5580. function openAddPolicyRuleModal() {
  5581. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  5582. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  5583. document.getElementById('prule-modal-mark').value = '';
  5584. document.getElementById('prule-modal-src').value = '';
  5585. document.getElementById('prule-modal-dst').value = '';
  5586. const sel = document.getElementById('prule-modal-table');
  5587. sel.innerHTML = '';
  5588. (state.routingTables || []).forEach(t => {
  5589. const opt = document.createElement('option');
  5590. opt.value = t.name;
  5591. opt.innerText = t.name;
  5592. sel.appendChild(opt);
  5593. });
  5594. document.getElementById('prule-modal').classList.remove('hidden');
  5595. }
  5596. function closePolicyRuleModal() {
  5597. document.getElementById('prule-modal').classList.add('hidden');
  5598. }
  5599. async function submitSavePolicyRule(e) {
  5600. e.preventDefault();
  5601. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  5602. const mark = document.getElementById('prule-modal-mark').value.trim();
  5603. const src = document.getElementById('prule-modal-src').value.trim();
  5604. const dst = document.getElementById('prule-modal-dst').value.trim();
  5605. const table = document.getElementById('prule-modal-table').value;
  5606. const action = document.getElementById('prule-modal-action').value;
  5607. try {
  5608. const res = await fetch(`${API_BASE}/routing/rules`, {
  5609. method: 'POST',
  5610. headers: { 'Content-Type': 'application/json' },
  5611. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  5612. });
  5613. if (res.ok) {
  5614. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  5615. closePolicyRuleModal();
  5616. loadRoutes();
  5617. } else {
  5618. const err = await res.json();
  5619. showToast('Error', err.message, 'error');
  5620. }
  5621. } catch (err) {
  5622. showToast('Error', err.message, 'error');
  5623. }
  5624. }
  5625. async function deletePolicyRule(id) {
  5626. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  5627. try {
  5628. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5629. if (res.ok) {
  5630. showToast('Rule Removed', 'Policy rule deleted', 'success');
  5631. loadRoutes();
  5632. }
  5633. } catch (err) {
  5634. showToast('Error', err.message, 'error');
  5635. }
  5636. }
  5637. // ----------------- Routing Tables -----------------
  5638. function renderRoutingTables() {
  5639. const tbody = document.getElementById('tables-table-body');
  5640. if (!tbody) return;
  5641. tbody.innerHTML = '';
  5642. (state.routingTables || []).forEach(t => {
  5643. const tr = document.createElement('tr');
  5644. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5645. tr.innerHTML = `
  5646. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  5647. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  5648. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  5649. `;
  5650. tbody.appendChild(tr);
  5651. });
  5652. }
  5653. function openAddTableModal() {
  5654. document.getElementById('table-modal-name').value = '';
  5655. document.getElementById('table-modal-id').value = '';
  5656. document.getElementById('table-modal-comment').value = '';
  5657. document.getElementById('table-modal').classList.remove('hidden');
  5658. }
  5659. function closeTableModal() {
  5660. document.getElementById('table-modal').classList.add('hidden');
  5661. }
  5662. async function submitSaveTable(e) {
  5663. e.preventDefault();
  5664. const name = document.getElementById('table-modal-name').value.trim();
  5665. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  5666. const comment = document.getElementById('table-modal-comment').value.trim();
  5667. try {
  5668. const res = await fetch(`${API_BASE}/routing/tables`, {
  5669. method: 'POST',
  5670. headers: { 'Content-Type': 'application/json' },
  5671. body: JSON.stringify({ name, table_id: id, comment })
  5672. });
  5673. if (res.ok) {
  5674. showToast('Table Created', `Routing table ${name} registered`, 'success');
  5675. closeTableModal();
  5676. loadRoutes();
  5677. } else {
  5678. const err = await res.json();
  5679. showToast('Error', err.message, 'error');
  5680. }
  5681. } catch (err) {
  5682. showToast('Error', err.message, 'error');
  5683. }
  5684. }
  5685. async function loadDebianConfig() {
  5686. const view = document.getElementById('debian-config-view');
  5687. view.innerText = 'Generating live configuration...';
  5688. try {
  5689. const res = await fetch(`${API_BASE}/debian/config`);
  5690. const data = await res.json();
  5691. view.innerText = data.content || '# Empty config';
  5692. } catch (err) {
  5693. view.innerText = 'Failed to generate Debian network config.';
  5694. }
  5695. }
  5696. async function saveDebianConfig() {
  5697. try {
  5698. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  5699. const data = await res.json();
  5700. if (res.ok) {
  5701. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  5702. loadDebianConfig();
  5703. }
  5704. } catch (err) {
  5705. showToast('Error', err.message, 'error');
  5706. }
  5707. }
  5708. function showToast(title, message, type = 'info') {
  5709. const container = document.getElementById('toast-container');
  5710. const toast = document.createElement('div');
  5711. const borderColors = {
  5712. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  5713. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  5714. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  5715. };
  5716. 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}`;
  5717. toast.innerHTML = `
  5718. <div class="flex-1">
  5719. <div class="font-bold text-xs text-white">${title}</div>
  5720. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  5721. </div>
  5722. `;
  5723. container.appendChild(toast);
  5724. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  5725. setTimeout(() => {
  5726. toast.classList.add('opacity-0', 'translate-y-2');
  5727. setTimeout(() => toast.remove(), 300);
  5728. }, 4000);
  5729. }
  5730. function formatTraffic(bytesPerSec) {
  5731. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  5732. const kb = bytesPerSec / 1024;
  5733. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  5734. const mb = kb / 1024;
  5735. return `${mb.toFixed(2)} MB/s`;
  5736. }
  5737. function toggleSidebar() {
  5738. const sb = document.getElementById('sidebar');
  5739. sb.classList.toggle('-translate-x-full');
  5740. }
  5741. // ======================== EoIP (Ethernet over IP) ========================
  5742. async function loadEoIP(populate = true) {
  5743. try {
  5744. const res = await fetch(`${API_BASE}/vpn/eoip`);
  5745. const data = await res.json();
  5746. state.eoipTunnels = Array.isArray(data) ? data : [];
  5747. const badge = document.getElementById('eoip-count-badge');
  5748. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  5749. const sideBadge = document.getElementById('badge-eoip-count');
  5750. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  5751. renderEoIPTunnels();
  5752. } catch (err) {
  5753. console.error('Failed to load EoIP:', err);
  5754. }
  5755. }
  5756. function renderEoIPTunnels() {
  5757. const tbody = document.getElementById('eoip-table-body');
  5758. const empty = document.getElementById('eoip-empty');
  5759. if (!tbody) return;
  5760. tbody.innerHTML = '';
  5761. const tunnels = state.eoipTunnels || [];
  5762. if (tunnels.length === 0) {
  5763. empty?.classList.remove('hidden');
  5764. return;
  5765. }
  5766. empty?.classList.add('hidden');
  5767. tunnels.forEach(t => {
  5768. const tr = document.createElement('tr');
  5769. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  5770. tr.innerHTML = `
  5771. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  5772. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  5773. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  5774. <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>
  5775. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  5776. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  5777. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  5778. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  5779. <td class="py-2.5 px-3 font-mono text-[11px]">
  5780. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  5781. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  5782. </td>
  5783. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  5784. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5785. <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>
  5786. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5787. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  5788. </td>
  5789. `;
  5790. tbody.appendChild(tr);
  5791. });
  5792. }
  5793. function openAddEoIPModal() {
  5794. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  5795. document.getElementById('eoip-modal-id').value = '';
  5796. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  5797. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  5798. document.getElementById('eoip-modal-remote').value = '';
  5799. document.getElementById('eoip-modal-ip').value = '';
  5800. document.getElementById('eoip-modal-local').value = '';
  5801. document.getElementById('eoip-modal-mac').value = '';
  5802. document.getElementById('eoip-modal-mtu').value = '1500';
  5803. document.getElementById('eoip-modal-comment').value = '';
  5804. document.getElementById('eoip-modal-clampmss').checked = true;
  5805. document.getElementById('eoip-modal-disabled').checked = false;
  5806. document.getElementById('eoip-modal').classList.remove('hidden');
  5807. }
  5808. function openEditEoIPModal(id) {
  5809. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  5810. if (!t) return;
  5811. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  5812. document.getElementById('eoip-modal-id').value = t.id;
  5813. document.getElementById('eoip-modal-name').value = t.name;
  5814. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  5815. document.getElementById('eoip-modal-remote').value = t.remote_address;
  5816. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  5817. document.getElementById('eoip-modal-local').value = t.local_address || '';
  5818. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  5819. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  5820. document.getElementById('eoip-modal-comment').value = t.comment || '';
  5821. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  5822. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  5823. document.getElementById('eoip-modal').classList.remove('hidden');
  5824. }
  5825. function closeEoIPModal() {
  5826. document.getElementById('eoip-modal').classList.add('hidden');
  5827. }
  5828. async function submitSaveEoIP(e) {
  5829. e.preventDefault();
  5830. const id = document.getElementById('eoip-modal-id').value;
  5831. const name = document.getElementById('eoip-modal-name').value.trim();
  5832. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  5833. const remote = document.getElementById('eoip-modal-remote').value.trim();
  5834. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  5835. const local = document.getElementById('eoip-modal-local').value.trim();
  5836. const mac = document.getElementById('eoip-modal-mac').value.trim();
  5837. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  5838. const comment = document.getElementById('eoip-modal-comment').value.trim();
  5839. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  5840. const disabled = document.getElementById('eoip-modal-disabled').checked;
  5841. try {
  5842. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  5843. method: 'POST',
  5844. headers: { 'Content-Type': 'application/json' },
  5845. body: JSON.stringify({
  5846. id,
  5847. name,
  5848. tunnel_id: tunnelId,
  5849. remote_address: remote,
  5850. ip_address: ipAddress,
  5851. local_address: local,
  5852. mac_address: mac,
  5853. mtu,
  5854. clamp_mss: clampMss,
  5855. comment,
  5856. disabled
  5857. })
  5858. });
  5859. if (res.ok) {
  5860. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  5861. closeEoIPModal();
  5862. loadEoIP(false);
  5863. fetchData(false);
  5864. } else {
  5865. const err = await res.json();
  5866. showToast('Error', err.message, 'error');
  5867. }
  5868. } catch (err) {
  5869. showToast('Error', err.message, 'error');
  5870. }
  5871. }
  5872. async function toggleEoIPState(id, disabled) {
  5873. try {
  5874. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  5875. method: 'POST',
  5876. headers: { 'Content-Type': 'application/json' },
  5877. body: JSON.stringify({ disabled })
  5878. });
  5879. if (res.ok) {
  5880. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  5881. loadEoIP(false);
  5882. fetchData(false);
  5883. }
  5884. } catch (err) {
  5885. showToast('Error', err.message, 'error');
  5886. }
  5887. }
  5888. async function deleteEoIP(id) {
  5889. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  5890. try {
  5891. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5892. if (res.ok) {
  5893. showToast('Deleted', 'EoIP tunnel removed', 'success');
  5894. loadEoIP(false);
  5895. fetchData(false);
  5896. }
  5897. } catch (err) {
  5898. showToast('Error', err.message, 'error');
  5899. }
  5900. }
  5901. // ======================== PPP Central Hub & Servers ========================
  5902. function switchPPPSubTab(tab) {
  5903. state.pppSubTab = tab;
  5904. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  5905. tabs.forEach(t => {
  5906. const panel = document.getElementById(`ppp-subtab-${t}`);
  5907. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  5908. if (panel) {
  5909. if (t === tab) panel.classList.remove('hidden');
  5910. else panel.classList.add('hidden');
  5911. }
  5912. if (btn) {
  5913. if (t === tab) {
  5914. 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';
  5915. } else {
  5916. 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';
  5917. }
  5918. }
  5919. });
  5920. const addBtn = document.getElementById('ppp-primary-add-btn');
  5921. if (addBtn) {
  5922. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  5923. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  5924. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  5925. else addBtn.innerHTML = '<span>Save Config</span>';
  5926. }
  5927. if (tab === 'active') loadPPPSessions();
  5928. }
  5929. function openCurrentPPPModal() {
  5930. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  5931. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  5932. else if (state.pppSubTab === 'active') loadPPPSessions();
  5933. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  5934. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  5935. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  5936. }
  5937. async function loadPPP(populateDropdowns = true) {
  5938. await Promise.all([
  5939. loadPPPSecrets(),
  5940. loadPPPProfiles(),
  5941. loadPPPServers(),
  5942. loadPPPSessions()
  5943. ]);
  5944. }
  5945. async function loadPPPSecrets() {
  5946. try {
  5947. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  5948. const data = await res.json();
  5949. state.pppSecrets = Array.isArray(data) ? data : [];
  5950. const b = document.getElementById('ppp-badge-secrets');
  5951. if (b) b.innerText = state.pppSecrets.length;
  5952. const b2 = document.getElementById('secrets-count-badge');
  5953. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  5954. renderPPPSecrets();
  5955. } catch (err) {
  5956. console.error('Failed to load PPP secrets:', err);
  5957. }
  5958. }
  5959. function renderPPPSecrets() {
  5960. const tbody = document.getElementById('secrets-table-body');
  5961. const empty = document.getElementById('secrets-empty');
  5962. if (!tbody) return;
  5963. tbody.innerHTML = '';
  5964. const secrets = state.pppSecrets || [];
  5965. if (secrets.length === 0) {
  5966. empty?.classList.remove('hidden');
  5967. return;
  5968. }
  5969. empty?.classList.add('hidden');
  5970. secrets.forEach(s => {
  5971. const tr = document.createElement('tr');
  5972. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  5973. tr.innerHTML = `
  5974. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  5975. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  5976. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  5977. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  5978. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  5979. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  5980. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  5981. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5982. <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>
  5983. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5984. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  5985. </td>
  5986. `;
  5987. tbody.appendChild(tr);
  5988. });
  5989. }
  5990. async function loadPPPProfiles() {
  5991. try {
  5992. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  5993. const data = await res.json();
  5994. state.pppProfiles = Array.isArray(data) ? data : [];
  5995. const b = document.getElementById('ppp-badge-profiles');
  5996. if (b) b.innerText = state.pppProfiles.length;
  5997. const b2 = document.getElementById('profiles-count-badge');
  5998. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  5999. // Populate profile selects across modals
  6000. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  6001. selects.forEach(sid => {
  6002. const el = document.getElementById(sid);
  6003. if (!el) return;
  6004. const cur = el.value;
  6005. el.innerHTML = '';
  6006. state.pppProfiles.forEach(p => {
  6007. const opt = document.createElement('option');
  6008. opt.value = p.name;
  6009. opt.innerText = `${p.name} (${p.remote_address})`;
  6010. if (p.name === cur) opt.selected = true;
  6011. el.appendChild(opt);
  6012. });
  6013. });
  6014. renderPPPProfiles();
  6015. } catch (err) {
  6016. console.error('Failed to load PPP profiles:', err);
  6017. }
  6018. }
  6019. function renderPPPProfiles() {
  6020. const tbody = document.getElementById('profiles-table-body');
  6021. if (!tbody) return;
  6022. tbody.innerHTML = '';
  6023. (state.pppProfiles || []).forEach(p => {
  6024. const isDefault = p.name.startsWith('default');
  6025. const tr = document.createElement('tr');
  6026. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6027. tr.innerHTML = `
  6028. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  6029. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  6030. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  6031. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  6032. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  6033. <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>
  6034. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  6035. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  6036. ${!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>`}
  6037. </td>
  6038. `;
  6039. tbody.appendChild(tr);
  6040. });
  6041. }
  6042. async function loadPPPServers() {
  6043. try {
  6044. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  6045. fetch(`${API_BASE}/vpn/servers/pppoe`),
  6046. fetch(`${API_BASE}/vpn/servers/pptp`),
  6047. fetch(`${API_BASE}/vpn/servers/l2tp`),
  6048. fetch(`${API_BASE}/vpn/servers/ipsec`)
  6049. ]);
  6050. if (pppoeRes.ok) {
  6051. state.pppoeServer = await pppoeRes.json();
  6052. const s = state.pppoeServer;
  6053. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  6054. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  6055. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  6056. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  6057. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  6058. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  6059. const pill = document.getElementById('pppoe-server-status-pill');
  6060. if (pill) {
  6061. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6062. 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';
  6063. }
  6064. setDotBadge('ppp-badge-pppoe-state', s.running);
  6065. }
  6066. if (pptpRes.ok) {
  6067. state.pptpServer = await pptpRes.json();
  6068. const s = state.pptpServer;
  6069. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  6070. document.getElementById('pptp-server-port').value = s.port || 1723;
  6071. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  6072. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  6073. const pill = document.getElementById('pptp-server-status-pill');
  6074. if (pill) {
  6075. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6076. 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';
  6077. }
  6078. setDotBadge('ppp-badge-pptp-state', s.running);
  6079. }
  6080. if (l2tpRes.ok) {
  6081. state.l2tpServer = await l2tpRes.json();
  6082. const s = state.l2tpServer;
  6083. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  6084. document.getElementById('l2tp-server-port').value = s.port || 1701;
  6085. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  6086. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  6087. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  6088. const pill = document.getElementById('l2tp-server-status-pill');
  6089. if (pill) {
  6090. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6091. 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';
  6092. }
  6093. setDotBadge('ppp-badge-l2tp-state', s.running);
  6094. }
  6095. if (ipsecRes.ok) {
  6096. state.ipsecServer = await ipsecRes.json();
  6097. const s = state.ipsecServer;
  6098. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  6099. if (modalEn) modalEn.checked = !!s.enabled;
  6100. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  6101. if (modalPsk) modalPsk.value = s.preshared_key || '';
  6102. const modalPool = document.getElementById('modal-ipsec-server-pool');
  6103. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  6104. const modalDns = document.getElementById('modal-ipsec-server-dns');
  6105. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  6106. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  6107. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  6108. const pill = document.getElementById('modal-ipsec-server-status');
  6109. if (pill) {
  6110. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  6111. 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';
  6112. }
  6113. }
  6114. } catch (err) {
  6115. console.error('Failed to load VPN servers:', err);
  6116. }
  6117. }
  6118. async function loadPPPSessions() {
  6119. try {
  6120. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  6121. const data = await res.json();
  6122. state.pppActiveSessions = Array.isArray(data) ? data : [];
  6123. const b = document.getElementById('ppp-badge-active');
  6124. if (b) b.innerText = state.pppActiveSessions.length;
  6125. const sideB = document.getElementById('badge-ppp-sessions');
  6126. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  6127. renderPPPSessions();
  6128. } catch (err) {
  6129. console.error('Failed to load active PPP sessions:', err);
  6130. }
  6131. }
  6132. function renderPPPSessions() {
  6133. const tbody = document.getElementById('active-ppp-table-body');
  6134. const empty = document.getElementById('active-ppp-empty');
  6135. if (!tbody) return;
  6136. tbody.innerHTML = '';
  6137. const list = state.pppActiveSessions || [];
  6138. if (list.length === 0) {
  6139. empty?.classList.remove('hidden');
  6140. return;
  6141. }
  6142. empty?.classList.add('hidden');
  6143. list.forEach(s => {
  6144. const tr = document.createElement('tr');
  6145. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6146. tr.innerHTML = `
  6147. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  6148. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  6149. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  6150. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  6151. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  6152. <td class="py-2.5 px-3 text-[11px]">
  6153. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  6154. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  6155. </td>
  6156. <td class="py-2.5 px-3 text-right font-sans">
  6157. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  6158. </td>
  6159. `;
  6160. tbody.appendChild(tr);
  6161. });
  6162. }
  6163. async function disconnectPPPSession(iface) {
  6164. if (!confirm(`Disconnect session ${iface}?`)) return;
  6165. try {
  6166. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  6167. if (res.ok) {
  6168. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  6169. loadPPPSessions();
  6170. }
  6171. } catch (err) {
  6172. showToast('Error', err.message, 'error');
  6173. }
  6174. }
  6175. // PPP Secret Modal handlers
  6176. function openAddPPPSecretModal() {
  6177. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  6178. document.getElementById('secret-modal-id').value = '';
  6179. document.getElementById('secret-modal-name').value = '';
  6180. document.getElementById('secret-modal-password').value = '';
  6181. document.getElementById('secret-modal-service').value = 'any';
  6182. document.getElementById('secret-modal-profile').value = 'default';
  6183. document.getElementById('secret-modal-local').value = '';
  6184. document.getElementById('secret-modal-remote').value = '';
  6185. document.getElementById('secret-modal-comment').value = '';
  6186. document.getElementById('secret-modal-disabled').checked = false;
  6187. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  6188. }
  6189. function openEditPPPSecretModal(id) {
  6190. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  6191. if (!s) return;
  6192. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  6193. document.getElementById('secret-modal-id').value = s.id;
  6194. document.getElementById('secret-modal-name').value = s.name;
  6195. document.getElementById('secret-modal-password').value = s.password;
  6196. document.getElementById('secret-modal-service').value = s.service || 'any';
  6197. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  6198. document.getElementById('secret-modal-local').value = s.local_address || '';
  6199. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  6200. document.getElementById('secret-modal-comment').value = s.comment || '';
  6201. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  6202. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  6203. }
  6204. function closePPPSecretModal() {
  6205. document.getElementById('ppp-secret-modal').classList.add('hidden');
  6206. }
  6207. async function submitSavePPPSecret(e) {
  6208. e.preventDefault();
  6209. const id = document.getElementById('secret-modal-id').value;
  6210. const name = document.getElementById('secret-modal-name').value.trim();
  6211. const password = document.getElementById('secret-modal-password').value.trim();
  6212. const service = document.getElementById('secret-modal-service').value;
  6213. const profile = document.getElementById('secret-modal-profile').value;
  6214. const local = document.getElementById('secret-modal-local').value.trim();
  6215. const remote = document.getElementById('secret-modal-remote').value.trim();
  6216. const comment = document.getElementById('secret-modal-comment').value.trim();
  6217. const disabled = document.getElementById('secret-modal-disabled').checked;
  6218. try {
  6219. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  6220. method: 'POST',
  6221. headers: { 'Content-Type': 'application/json' },
  6222. body: JSON.stringify({
  6223. id,
  6224. name,
  6225. password,
  6226. service,
  6227. profile,
  6228. local_address: local,
  6229. remote_address: remote,
  6230. comment,
  6231. disabled
  6232. })
  6233. });
  6234. if (res.ok) {
  6235. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  6236. closePPPSecretModal();
  6237. loadPPPSecrets();
  6238. } else {
  6239. const err = await res.json();
  6240. showToast('Error', err.message, 'error');
  6241. }
  6242. } catch (err) {
  6243. showToast('Error', err.message, 'error');
  6244. }
  6245. }
  6246. async function togglePPPSecretState(id, disabled) {
  6247. try {
  6248. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  6249. method: 'POST',
  6250. headers: { 'Content-Type': 'application/json' },
  6251. body: JSON.stringify({ disabled })
  6252. });
  6253. if (res.ok) {
  6254. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  6255. loadPPPSecrets();
  6256. }
  6257. } catch (err) {
  6258. showToast('Error', err.message, 'error');
  6259. }
  6260. }
  6261. async function deletePPPSecret(id) {
  6262. if (!confirm('Are you sure you want to delete this secret account?')) return;
  6263. try {
  6264. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6265. if (res.ok) {
  6266. showToast('Deleted', 'Secret account removed', 'success');
  6267. loadPPPSecrets();
  6268. }
  6269. } catch (err) {
  6270. showToast('Error', err.message, 'error');
  6271. }
  6272. }
  6273. // PPP Profile Modal handlers
  6274. function openAddPPPProfileModal() {
  6275. document.getElementById('profile-modal-name').value = '';
  6276. document.getElementById('profile-modal-local').value = '10.10.10.1';
  6277. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  6278. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  6279. document.getElementById('profile-modal-encryption').value = 'required';
  6280. document.getElementById('profile-modal-onlyone').checked = true;
  6281. document.getElementById('profile-modal-comment').value = '';
  6282. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  6283. }
  6284. function closePPPProfileModal() {
  6285. document.getElementById('ppp-profile-modal').classList.add('hidden');
  6286. }
  6287. async function submitSavePPPProfile(e) {
  6288. e.preventDefault();
  6289. const name = document.getElementById('profile-modal-name').value.trim();
  6290. const local = document.getElementById('profile-modal-local').value.trim();
  6291. const remote = document.getElementById('profile-modal-remote').value.trim();
  6292. const dns = document.getElementById('profile-modal-dns').value.trim();
  6293. const enc = document.getElementById('profile-modal-encryption').value;
  6294. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  6295. const comment = document.getElementById('profile-modal-comment').value.trim();
  6296. try {
  6297. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  6298. method: 'POST',
  6299. headers: { 'Content-Type': 'application/json' },
  6300. body: JSON.stringify({
  6301. id: name,
  6302. name,
  6303. local_address: local,
  6304. remote_address: remote,
  6305. dns_servers: dns,
  6306. use_encryption: enc,
  6307. only_one: onlyone,
  6308. comment
  6309. })
  6310. });
  6311. if (res.ok) {
  6312. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  6313. closePPPProfileModal();
  6314. loadPPPProfiles();
  6315. } else {
  6316. const err = await res.json();
  6317. showToast('Error', err.message, 'error');
  6318. }
  6319. } catch (err) {
  6320. showToast('Error', err.message, 'error');
  6321. }
  6322. }
  6323. async function deletePPPProfile(name) {
  6324. if (!confirm(`Delete PPP profile ${name}?`)) return;
  6325. try {
  6326. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  6327. if (res.ok) {
  6328. showToast('Deleted', 'Profile removed', 'success');
  6329. loadPPPProfiles();
  6330. } else {
  6331. const err = await res.json();
  6332. showToast('Error', err.message, 'error');
  6333. }
  6334. } catch (err) {
  6335. showToast('Error', err.message, 'error');
  6336. }
  6337. }
  6338. // Server Config submissions
  6339. async function savePPPoEServerConfig(e) {
  6340. e.preventDefault();
  6341. const enabled = document.getElementById('pppoe-server-enabled').checked;
  6342. const name = document.getElementById('pppoe-server-name').value.trim();
  6343. const iface = document.getElementById('pppoe-server-iface').value;
  6344. const profile = document.getElementById('pppoe-server-profile').value;
  6345. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  6346. const onesession = document.getElementById('pppoe-server-onesession').checked;
  6347. try {
  6348. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  6349. method: 'POST',
  6350. headers: { 'Content-Type': 'application/json' },
  6351. body: JSON.stringify({
  6352. enabled,
  6353. service_name: name,
  6354. interface: iface,
  6355. default_profile: profile,
  6356. max_mtu: mtu,
  6357. max_mru: mtu,
  6358. one_session_per_host: onesession
  6359. })
  6360. });
  6361. if (res.ok) {
  6362. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  6363. loadPPPServers();
  6364. fetchData(false);
  6365. } else {
  6366. const err = await res.json();
  6367. showToast('Error', err.message, 'error');
  6368. }
  6369. } catch (err) {
  6370. showToast('Error', err.message, 'error');
  6371. }
  6372. }
  6373. async function savePPTPServerConfig(e) {
  6374. e.preventDefault();
  6375. const enabled = document.getElementById('pptp-server-enabled').checked;
  6376. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  6377. const profile = document.getElementById('pptp-server-profile').value;
  6378. const mppe = document.getElementById('pptp-server-mppe').checked;
  6379. try {
  6380. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  6381. method: 'POST',
  6382. headers: { 'Content-Type': 'application/json' },
  6383. body: JSON.stringify({
  6384. enabled,
  6385. port,
  6386. default_profile: profile,
  6387. require_mppe: mppe
  6388. })
  6389. });
  6390. if (res.ok) {
  6391. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  6392. loadPPPServers();
  6393. fetchData(false);
  6394. } else {
  6395. const err = await res.json();
  6396. showToast('Error', err.message, 'error');
  6397. }
  6398. } catch (err) {
  6399. showToast('Error', err.message, 'error');
  6400. }
  6401. }
  6402. async function saveL2TPServerConfig(e) {
  6403. e.preventDefault();
  6404. const enabled = document.getElementById('l2tp-server-enabled').checked;
  6405. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  6406. const profile = document.getElementById('l2tp-server-profile').value;
  6407. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  6408. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  6409. try {
  6410. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  6411. method: 'POST',
  6412. headers: { 'Content-Type': 'application/json' },
  6413. body: JSON.stringify({
  6414. enabled,
  6415. port,
  6416. default_profile: profile,
  6417. use_ipsec: useipsec,
  6418. ipsec_secret: psk
  6419. })
  6420. });
  6421. if (res.ok) {
  6422. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  6423. loadPPPServers();
  6424. fetchData(false);
  6425. } else {
  6426. const err = await res.json();
  6427. showToast('Error', err.message, 'error');
  6428. }
  6429. } catch (err) {
  6430. showToast('Error', err.message, 'error');
  6431. }
  6432. }
  6433. // IPSec Server Modal
  6434. function openIPSecServerModal() {
  6435. loadPPPServers();
  6436. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  6437. }
  6438. function closeIPSecServerModal() {
  6439. document.getElementById('ipsec-server-modal').classList.add('hidden');
  6440. }
  6441. async function submitSaveIPSecServer(e) {
  6442. e.preventDefault();
  6443. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  6444. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  6445. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  6446. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  6447. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  6448. try {
  6449. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  6450. method: 'POST',
  6451. headers: { 'Content-Type': 'application/json' },
  6452. body: JSON.stringify({
  6453. enabled,
  6454. preshared_key: psk,
  6455. pool_address: pool,
  6456. dns_servers: dns,
  6457. local_subnet: subnet
  6458. })
  6459. });
  6460. if (res.ok) {
  6461. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  6462. closeIPSecServerModal();
  6463. loadPPPServers();
  6464. fetchData(false);
  6465. } else {
  6466. const err = await res.json();
  6467. showToast('Error', err.message, 'error');
  6468. }
  6469. } catch (err) {
  6470. showToast('Error', err.message, 'error');
  6471. }
  6472. }
  6473. // WireGuard Client Config Viewer
  6474. let currentWGClientConf = '';
  6475. async function openWGClientConfModal(iface, clientIP) {
  6476. try {
  6477. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  6478. method: 'POST',
  6479. headers: { 'Content-Type': 'application/json' },
  6480. body: JSON.stringify({
  6481. interface: iface,
  6482. address: clientIP || '10.10.0.2/32',
  6483. dns: '1.1.1.1, 8.8.8.8'
  6484. })
  6485. });
  6486. if (res.ok) {
  6487. const data = await res.json();
  6488. currentWGClientConf = data.config;
  6489. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  6490. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  6491. } else {
  6492. const err = await res.json();
  6493. showToast('Error', err.message, 'error');
  6494. }
  6495. } catch (err) {
  6496. showToast('Error', err.message, 'error');
  6497. }
  6498. }
  6499. function closeWGClientConfModal() {
  6500. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  6501. }
  6502. function copyWGClientConf() {
  6503. if (!currentWGClientConf) return;
  6504. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  6505. }
  6506. function downloadWGClientConf() {
  6507. if (!currentWGClientConf) return;
  6508. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  6509. const a = document.createElement('a');
  6510. a.href = URL.createObjectURL(blob);
  6511. a.download = 'wireguard-client.conf';
  6512. document.body.appendChild(a);
  6513. a.click();
  6514. document.body.removeChild(a);
  6515. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  6516. }
  6517. // =========================================================================
  6518. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  6519. // =========================================================================
  6520. state.activeDynSubTab = 'bgp-peers';
  6521. state.activeBgpSubTab = 'bgp-peers';
  6522. state.activeOspfTab = 'instances';
  6523. state.bgpInstance = null;
  6524. state.bgpPeers = [];
  6525. state.bgpNets = [];
  6526. state.bgpRoutes = [];
  6527. state.ospfInstance = null;
  6528. state.ospfInstances = [];
  6529. state.ospfAreas = [];
  6530. state.ospfAreaRanges = [];
  6531. state.ospfTemplates = [];
  6532. state.ospfLiveInterfaces = [];
  6533. state.ospfStaticNbrs = [];
  6534. state.ospfNeighbors = [];
  6535. state.ospfLSA = [];
  6536. state.ospfRoutes = [];
  6537. state.selectedOspfRow = {
  6538. instances: null,
  6539. areas: null,
  6540. 'area-ranges': null,
  6541. templates: null,
  6542. interfaces: null,
  6543. 'static-nbrs': null,
  6544. neighbors: null,
  6545. lsa: null,
  6546. };
  6547. state.ospfSort = {
  6548. instances: { col: 'name', asc: true },
  6549. areas: { col: 'name', asc: true },
  6550. ranges: { col: 'area', asc: true },
  6551. templates: { col: 'interfaces', asc: true },
  6552. live_ifaces: { col: 'interface', asc: true },
  6553. snbrs: { col: 'address', asc: true },
  6554. neighbors: { col: 'address', asc: true },
  6555. lsa: { col: 'instance', asc: true },
  6556. };
  6557. function switchBgpSubTab(subTab) {
  6558. state.activeBgpSubTab = subTab;
  6559. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  6560. tabs.forEach(t => {
  6561. const el = document.getElementById(`dyn-subtab-${t}`);
  6562. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  6563. if (el) el.classList.toggle('hidden', t !== subTab);
  6564. if (btn) {
  6565. if (t === subTab) {
  6566. 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';
  6567. } else {
  6568. 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';
  6569. }
  6570. }
  6571. });
  6572. }
  6573. function switchOspfTab(tabName) {
  6574. state.activeOspfTab = tabName;
  6575. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  6576. tabs.forEach(t => {
  6577. const pane = document.getElementById(`ospf-pane-${t}`);
  6578. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  6579. if (pane) pane.classList.toggle('hidden', t !== tabName);
  6580. if (btn) {
  6581. if (t === tabName) {
  6582. 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';
  6583. } else {
  6584. 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';
  6585. }
  6586. }
  6587. });
  6588. }
  6589. function switchOspfSubTab(tab) {
  6590. // Legacy alias
  6591. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  6592. else if (tab === 'ospf-areas') switchOspfTab('areas');
  6593. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  6594. else switchOspfTab('instances');
  6595. }
  6596. function switchDynSubTab(subTab) {
  6597. if (subTab.startsWith('bgp')) {
  6598. if (state.activeTab !== 'bgp') navigate('bgp');
  6599. switchBgpSubTab(subTab);
  6600. } else if (subTab.startsWith('ospf')) {
  6601. if (state.activeTab !== 'ospf') navigate('ospf');
  6602. switchOspfTab('instances');
  6603. }
  6604. }
  6605. async function loadDynamicRouting(showToastMsg = false) {
  6606. try {
  6607. const fetchSafeJson = async (url) => {
  6608. try {
  6609. const r = await fetch(url);
  6610. return r.ok ? await r.json() : null;
  6611. } catch (e) {
  6612. return null;
  6613. }
  6614. };
  6615. const [
  6616. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  6617. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  6618. selectRules, commLists, asLists
  6619. ] = await Promise.all([
  6620. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  6621. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  6622. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  6623. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  6624. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  6625. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  6626. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  6627. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  6628. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  6629. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  6630. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  6631. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  6632. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  6633. fetchSafeJson(`${API_BASE}/routing/filters`),
  6634. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  6635. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  6636. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  6637. ]);
  6638. if (sum) state.dynSummary = sum;
  6639. if (bgpInst) state.bgpInstance = bgpInst;
  6640. if (bgpPeers) state.bgpPeers = bgpPeers;
  6641. if (bgpNets) state.bgpNets = bgpNets;
  6642. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  6643. if (ospfInsts) state.ospfInstances = ospfInsts;
  6644. if (ospfAreas) state.ospfAreas = ospfAreas;
  6645. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  6646. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  6647. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  6648. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  6649. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  6650. if (ospfLsa) state.ospfLSA = ospfLsa;
  6651. if (filters) state.routingFilters = filters;
  6652. if (selectRules) state.routingSelectRules = selectRules;
  6653. if (commLists) state.routingCommunityLists = commLists;
  6654. if (asLists) state.routingASLists = asLists;
  6655. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  6656. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  6657. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  6658. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  6659. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  6660. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  6661. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  6662. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  6663. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  6664. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  6665. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  6666. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  6667. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  6668. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  6669. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  6670. } catch (err) {
  6671. console.error('Failed to load dynamic routing:', err);
  6672. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  6673. }
  6674. }
  6675. async function loadOspfAll() {
  6676. await loadDynamicRouting(true);
  6677. }
  6678. function renderBgpStatusPill() {
  6679. const pill = document.getElementById('bgp-live-status-pill');
  6680. if (!pill) return;
  6681. const inst = state.bgpInstance;
  6682. if (!inst || !inst.enabled) {
  6683. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  6684. pill.innerText = 'BGP DISABLED';
  6685. } else if (inst.running) {
  6686. 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';
  6687. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  6688. } else {
  6689. 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';
  6690. pill.innerText = 'BGP STARTING...';
  6691. }
  6692. }
  6693. function renderBgpPeers() {
  6694. const tbody = document.getElementById('bgp-peers-table-body');
  6695. if (!tbody) return;
  6696. const empty = document.getElementById('bgp-peers-empty');
  6697. const countBadge = document.getElementById('bgp-peers-count-badge');
  6698. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  6699. const peers = state.bgpPeers || [];
  6700. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  6701. if (navBadge) navBadge.innerText = peers.length;
  6702. if (peers.length === 0) {
  6703. tbody.innerHTML = '';
  6704. if (empty) empty.classList.remove('hidden');
  6705. return;
  6706. }
  6707. if (empty) empty.classList.add('hidden');
  6708. tbody.innerHTML = peers.map(p => {
  6709. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  6710. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  6711. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  6712. let stateBadge = '';
  6713. if (p.disabled) {
  6714. 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>';
  6715. } else if (p.state === 'Established') {
  6716. 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>';
  6717. } else if (p.state === 'Connect' || p.state === 'Active') {
  6718. 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>`;
  6719. } else {
  6720. 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>`;
  6721. }
  6722. return `
  6723. <tr class="hover:bg-slate-800/40 transition">
  6724. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  6725. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  6726. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  6727. <td class="py-2.5 px-3">
  6728. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  6729. ${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>`}
  6730. </td>
  6731. <td class="py-2.5 px-3">${stateBadge}</td>
  6732. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  6733. <td class="py-2.5 px-3 text-slate-300">
  6734. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  6735. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  6736. </td>
  6737. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  6738. ${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> ` : ''}
  6739. ${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>` : ''}
  6740. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  6741. </td>
  6742. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  6743. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  6744. <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'}">
  6745. ${p.disabled ? 'Enable' : 'Disable'}
  6746. </button>
  6747. <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">
  6748. Edit
  6749. </button>
  6750. <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">
  6751. Delete
  6752. </button>
  6753. </td>
  6754. </tr>
  6755. `;
  6756. }).join('');
  6757. }
  6758. function renderBgpNetworks() {
  6759. const tbody = document.getElementById('bgp-nets-table-body');
  6760. if (!tbody) return;
  6761. const empty = document.getElementById('bgp-nets-empty');
  6762. const countBadge = document.getElementById('bgp-nets-count-badge');
  6763. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  6764. const nets = state.bgpNets || [];
  6765. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  6766. if (navBadge) navBadge.innerText = nets.length;
  6767. if (nets.length === 0) {
  6768. tbody.innerHTML = '';
  6769. if (empty) empty.classList.remove('hidden');
  6770. return;
  6771. }
  6772. if (empty) empty.classList.add('hidden');
  6773. tbody.innerHTML = nets.map(n => `
  6774. <tr class="hover:bg-slate-800/40 transition">
  6775. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  6776. <td class="py-2.5 px-3">
  6777. ${n.disabled
  6778. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  6779. : '<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>'}
  6780. </td>
  6781. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  6782. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  6783. <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">
  6784. Delete
  6785. </button>
  6786. </td>
  6787. </tr>
  6788. `).join('');
  6789. }
  6790. function renderBgpRoutes() {
  6791. const tbody = document.getElementById('bgp-routes-table-body');
  6792. if (!tbody) return;
  6793. const empty = document.getElementById('bgp-routes-empty');
  6794. const countBadge = document.getElementById('bgp-routes-count-badge');
  6795. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  6796. const routes = state.bgpRoutes || [];
  6797. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  6798. if (navBadge) navBadge.innerText = routes.length;
  6799. if (routes.length === 0) {
  6800. tbody.innerHTML = '';
  6801. if (empty) empty.classList.remove('hidden');
  6802. return;
  6803. }
  6804. if (empty) empty.classList.add('hidden');
  6805. tbody.innerHTML = routes.map(r => `
  6806. <tr class="hover:bg-slate-800/40 transition">
  6807. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  6808. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  6809. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  6810. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  6811. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  6812. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  6813. </tr>
  6814. `).join('');
  6815. }
  6816. // =========================================================================
  6817. // ROUTEROS v7 OSPF TABLE RENDERING & SORTING
  6818. // =========================================================================
  6819. function sortOspfTable(tab, col) {
  6820. if (!state.ospfSort) state.ospfSort = {};
  6821. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  6822. if (state.ospfSort[tab].col === col) {
  6823. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  6824. } else {
  6825. state.ospfSort[tab].col = col;
  6826. state.ospfSort[tab].asc = true;
  6827. }
  6828. const asc = state.ospfSort[tab].asc;
  6829. let list = [];
  6830. if (tab === 'instances') list = state.ospfInstances || [];
  6831. else if (tab === 'areas') list = state.ospfAreas || [];
  6832. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  6833. else if (tab === 'templates') list = state.ospfTemplates || [];
  6834. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  6835. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  6836. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  6837. else if (tab === 'lsa') list = state.ospfLSA || [];
  6838. list.sort((a, b) => {
  6839. let valA = a[col] ?? '';
  6840. let valB = b[col] ?? '';
  6841. if (typeof valA === 'number' && typeof valB === 'number') {
  6842. return asc ? valA - valB : valB - valA;
  6843. }
  6844. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  6845. });
  6846. if (tab === 'instances') renderOspfInstances();
  6847. else if (tab === 'areas') renderOspfAreas();
  6848. else if (tab === 'ranges') renderOspfAreaRanges();
  6849. else if (tab === 'templates') renderOspfTemplates();
  6850. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  6851. else if (tab === 'snbrs') renderOspfStaticNbrs();
  6852. else if (tab === 'neighbors') renderOspfNeighbors();
  6853. else if (tab === 'lsa') renderOspfLSA();
  6854. }
  6855. function selectOspfRow(tab, id) {
  6856. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  6857. state.selectedOspfRow[tab] = id;
  6858. if (tab === 'instances') {
  6859. renderOspfInstances();
  6860. const btnEn = document.getElementById('btn-ospf-inst-enable');
  6861. const btnDis = document.getElementById('btn-ospf-inst-disable');
  6862. const btnRem = document.getElementById('btn-ospf-inst-remove');
  6863. const btnCom = document.getElementById('btn-ospf-inst-comment');
  6864. if (btnEn) btnEn.disabled = false;
  6865. if (btnDis) btnDis.disabled = false;
  6866. if (btnRem) btnRem.disabled = false;
  6867. if (btnCom) btnCom.disabled = false;
  6868. } else if (tab === 'areas') {
  6869. renderOspfAreas();
  6870. const btnEn = document.getElementById('btn-ospf-area-enable');
  6871. const btnDis = document.getElementById('btn-ospf-area-disable');
  6872. const btnRem = document.getElementById('btn-ospf-area-remove');
  6873. const btnCom = document.getElementById('btn-ospf-area-comment');
  6874. if (btnEn) btnEn.disabled = false;
  6875. if (btnDis) btnDis.disabled = false;
  6876. if (btnRem) btnRem.disabled = false;
  6877. if (btnCom) btnCom.disabled = false;
  6878. } else if (tab === 'ranges') {
  6879. renderOspfAreaRanges();
  6880. const btnEn = document.getElementById('btn-ospf-range-enable');
  6881. const btnDis = document.getElementById('btn-ospf-range-disable');
  6882. const btnRem = document.getElementById('btn-ospf-range-remove');
  6883. const btnCom = document.getElementById('btn-ospf-range-comment');
  6884. if (btnEn) btnEn.disabled = false;
  6885. if (btnDis) btnDis.disabled = false;
  6886. if (btnRem) btnRem.disabled = false;
  6887. if (btnCom) btnCom.disabled = false;
  6888. } else if (tab === 'templates') {
  6889. renderOspfTemplates();
  6890. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  6891. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  6892. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  6893. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  6894. if (btnEn) btnEn.disabled = false;
  6895. if (btnDis) btnDis.disabled = false;
  6896. if (btnRem) btnRem.disabled = false;
  6897. if (btnCom) btnCom.disabled = false;
  6898. } else if (tab === 'snbrs') {
  6899. renderOspfStaticNbrs();
  6900. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  6901. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  6902. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  6903. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  6904. if (btnEn) btnEn.disabled = false;
  6905. if (btnDis) btnDis.disabled = false;
  6906. if (btnRem) btnRem.disabled = false;
  6907. if (btnCom) btnCom.disabled = false;
  6908. }
  6909. }
  6910. // TAB 1: INSTANCES
  6911. function renderOspfInstances() {
  6912. const tbody = document.getElementById('ospf-instances-table-body');
  6913. if (!tbody) return;
  6914. const countEl = document.getElementById('ospf-instances-footer-count');
  6915. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  6916. let list = state.ospfInstances || [];
  6917. if (filter) {
  6918. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  6919. }
  6920. if (countEl) countEl.innerText = list.length;
  6921. const selId = state.selectedOspfRow?.instances;
  6922. tbody.innerHTML = list.map((inst, idx) => {
  6923. const isSel = inst.id === selId;
  6924. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  6925. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  6926. return `
  6927. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  6928. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  6929. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  6930. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  6931. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  6932. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  6933. </td>
  6934. <td class="py-1.5 px-3">${inst.version || 2}</td>
  6935. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  6936. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  6937. </tr>
  6938. `;
  6939. }).join('');
  6940. }
  6941. // TAB 2: AREAS
  6942. function renderOspfAreas() {
  6943. const tbody = document.getElementById('ospf-areas-table-body');
  6944. if (!tbody) return;
  6945. const countEl = document.getElementById('ospf-areas-footer-count');
  6946. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  6947. let list = state.ospfAreas || [];
  6948. if (filter) {
  6949. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  6950. }
  6951. if (countEl) countEl.innerText = list.length;
  6952. const selId = state.selectedOspfRow?.areas;
  6953. tbody.innerHTML = list.map((a, idx) => {
  6954. const isSel = a.id === selId;
  6955. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  6956. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  6957. return `
  6958. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  6959. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  6960. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  6961. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  6962. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  6963. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  6964. </td>
  6965. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  6966. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  6967. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  6968. </tr>
  6969. `;
  6970. }).join('');
  6971. }
  6972. // TAB 3: AREA RANGES
  6973. function renderOspfAreaRanges() {
  6974. const tbody = document.getElementById('ospf-ranges-table-body');
  6975. if (!tbody) return;
  6976. const countEl = document.getElementById('ospf-ranges-footer-count');
  6977. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  6978. let list = state.ospfAreaRanges || [];
  6979. if (filter) {
  6980. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  6981. }
  6982. if (countEl) countEl.innerText = list.length;
  6983. const selId = state.selectedOspfRow?.['area-ranges'];
  6984. tbody.innerHTML = list.map((r, idx) => {
  6985. const isSel = r.id === selId;
  6986. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  6987. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  6988. return `
  6989. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  6990. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  6991. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  6992. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  6993. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  6994. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  6995. <td class="py-1.5 px-3">${r.cost || 1}</td>
  6996. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  6997. </tr>
  6998. `;
  6999. }).join('');
  7000. }
  7001. // TAB 4: INTERFACE TEMPLATES
  7002. function renderOspfTemplates() {
  7003. const tbody = document.getElementById('ospf-templates-table-body');
  7004. if (!tbody) return;
  7005. const countEl = document.getElementById('ospf-templates-footer-count');
  7006. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  7007. let list = state.ospfTemplates || [];
  7008. if (filter) {
  7009. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  7010. }
  7011. if (countEl) countEl.innerText = list.length;
  7012. const selId = state.selectedOspfRow?.templates;
  7013. tbody.innerHTML = list.map((t, idx) => {
  7014. const isSel = t.id === selId;
  7015. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7016. const ifaces = t.interfaces || t.interface || 'all';
  7017. const nets = t.networks || t.network || '';
  7018. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7019. return `
  7020. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  7021. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  7022. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  7023. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  7024. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7025. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  7026. </td>
  7027. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  7028. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  7029. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  7030. <td class="py-1.5 px-3">${t.cost || 1}</td>
  7031. <td class="py-1.5 px-3">${t.priority || 128}</td>
  7032. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  7033. </tr>
  7034. `;
  7035. }).join('');
  7036. }
  7037. // TAB 5: LIVE INTERFACES
  7038. function renderOspfLiveInterfaces() {
  7039. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  7040. if (!tbody) return;
  7041. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  7042. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  7043. let list = state.ospfLiveInterfaces || [];
  7044. if (filter) {
  7045. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  7046. }
  7047. if (countEl) countEl.innerText = list.length;
  7048. tbody.innerHTML = list.map(i => `
  7049. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7050. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  7051. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  7052. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  7053. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  7054. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  7055. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  7056. <td class="py-1.5 px-3">${i.cost || 1}</td>
  7057. <td class="py-1.5 px-3">${i.priority || 128}</td>
  7058. </tr>
  7059. `).join('');
  7060. }
  7061. // TAB 6: STATIC NEIGHBORS
  7062. function renderOspfStaticNbrs() {
  7063. const tbody = document.getElementById('ospf-snbrs-table-body');
  7064. if (!tbody) return;
  7065. const countEl = document.getElementById('ospf-snbrs-footer-count');
  7066. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  7067. let list = state.ospfStaticNbrs || [];
  7068. if (filter) {
  7069. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  7070. }
  7071. if (countEl) countEl.innerText = list.length;
  7072. const selId = state.selectedOspfRow?.['static-nbrs'];
  7073. tbody.innerHTML = list.map((n, idx) => {
  7074. const isSel = n.id === selId;
  7075. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7076. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7077. return `
  7078. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  7079. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7080. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  7081. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  7082. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  7083. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  7084. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  7085. <td class="py-1.5 px-3">${n.cost || 1}</td>
  7086. </tr>
  7087. `;
  7088. }).join('');
  7089. }
  7090. // TAB 7: LIVE NEIGHBORS
  7091. function renderOspfNeighbors() {
  7092. const tbody = document.getElementById('ospf-neighbors-table-body');
  7093. if (!tbody) return;
  7094. const countEl = document.getElementById('ospf-neighbors-footer-count');
  7095. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  7096. let list = state.ospfNeighbors || [];
  7097. if (filter) {
  7098. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  7099. }
  7100. if (countEl) countEl.innerText = list.length;
  7101. tbody.innerHTML = list.map(n => `
  7102. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7103. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  7104. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  7105. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7106. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  7107. </td>
  7108. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  7109. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  7110. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  7111. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  7112. </tr>
  7113. `).join('');
  7114. }
  7115. // TAB 8: LINK-STATE DATABASE (LSA)
  7116. function renderOspfLSA() {
  7117. const tbody = document.getElementById('ospf-lsa-table-body');
  7118. if (!tbody) return;
  7119. const countEl = document.getElementById('ospf-lsa-footer-count');
  7120. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  7121. let list = state.ospfLSA || [];
  7122. if (filter) {
  7123. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  7124. }
  7125. if (countEl) countEl.innerText = list.length;
  7126. tbody.innerHTML = list.map(l => `
  7127. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7128. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  7129. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7130. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  7131. </td>
  7132. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  7133. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  7134. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  7135. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  7136. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  7137. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  7138. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  7139. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  7140. </tr>
  7141. `).join('');
  7142. }
  7143. function renderOspfStatusPill() {
  7144. // Maintained for backward compatibility
  7145. const pill = document.getElementById('ospf-live-status-pill');
  7146. if (!pill) return;
  7147. 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';
  7148. pill.innerText = 'OSPF ACTIVE';
  7149. }
  7150. function renderOspfInterfaces() {
  7151. renderOspfTemplates();
  7152. }
  7153. function renderOspfRoutes() {
  7154. // Routes retained in background
  7155. }
  7156. // BGP Modals & Actions
  7157. function openBgpInstanceModal() {
  7158. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  7159. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  7160. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  7161. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  7162. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  7163. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  7164. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  7165. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  7166. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  7167. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  7168. }
  7169. function closeBgpInstanceModal() {
  7170. document.getElementById('bgp-instance-modal').classList.add('hidden');
  7171. }
  7172. async function submitBgpInstance(e) {
  7173. e.preventDefault();
  7174. const payload = {
  7175. enabled: document.getElementById('modal-bgp-enabled').checked,
  7176. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  7177. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  7178. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  7179. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  7180. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  7181. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  7182. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  7183. };
  7184. try {
  7185. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  7186. method: 'POST',
  7187. headers: { 'Content-Type': 'application/json' },
  7188. body: JSON.stringify(payload)
  7189. });
  7190. if (res.ok) {
  7191. closeBgpInstanceModal();
  7192. showToast('Success', 'BGP instance configuration updated', 'success');
  7193. loadDynamicRouting();
  7194. } else {
  7195. const err = await res.json();
  7196. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  7197. }
  7198. } catch (err) {
  7199. showToast('Error', err.message, 'error');
  7200. }
  7201. }
  7202. // ----------------- BGP Peer Connection Modal (RouterOS v7) -----------------
  7203. function switchBgpPeerModalTab(tab) {
  7204. const tabs = ['general', 'extra', 'attributes', 'filter'];
  7205. tabs.forEach(t => {
  7206. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  7207. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  7208. if (t === tab) {
  7209. if (pane) pane.classList.remove('hidden');
  7210. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  7211. } else {
  7212. if (pane) pane.classList.add('hidden');
  7213. 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';
  7214. }
  7215. });
  7216. }
  7217. function addOutputNetworkRow(val = '') {
  7218. const container = document.getElementById('modal-bgp-output-networks-container');
  7219. if (!container) return;
  7220. const row = document.createElement('div');
  7221. row.className = 'flex items-center gap-2 output-net-row';
  7222. row.innerHTML = `
  7223. <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">
  7224. <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>
  7225. `;
  7226. container.appendChild(row);
  7227. }
  7228. function parseBgpTime(val) {
  7229. if (!val) return 0;
  7230. val = String(val).trim();
  7231. if (val.includes(':')) {
  7232. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  7233. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  7234. if (parts.length === 2) return parts[0] * 60 + parts[1];
  7235. }
  7236. return parseInt(val, 10) || 0;
  7237. }
  7238. function formatBgpTime(secs) {
  7239. if (!secs || secs <= 0) return '00:00:00';
  7240. const h = Math.floor(secs / 3600);
  7241. const m = Math.floor((secs % 3600) / 60);
  7242. const s = secs % 60;
  7243. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  7244. }
  7245. function populateBgpRoutingTables() {
  7246. const sel = document.getElementById('modal-bgp-peer-routing-table');
  7247. if (!sel) return;
  7248. const cur = sel.value || 'main';
  7249. sel.innerHTML = '<option value="main">main</option>';
  7250. (state.routingTables || []).forEach(t => {
  7251. if (t.name !== 'main') {
  7252. const opt = document.createElement('option');
  7253. opt.value = t.name;
  7254. opt.innerText = t.name;
  7255. sel.appendChild(opt);
  7256. }
  7257. });
  7258. sel.value = cur;
  7259. }
  7260. function openAddBgpPeerModal() {
  7261. document.getElementById('bgp-peer-form').reset();
  7262. document.getElementById('modal-bgp-peer-id').value = '';
  7263. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  7264. // General Tab
  7265. document.getElementById('modal-bgp-peer-enabled').checked = true;
  7266. document.getElementById('modal-bgp-peer-comment').value = '';
  7267. document.getElementById('modal-bgp-peer-name').value = '';
  7268. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  7269. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  7270. document.getElementById('modal-bgp-peer-local-as').value = '';
  7271. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  7272. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  7273. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  7274. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  7275. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  7276. document.getElementById('modal-bgp-peer-router-id').value = '';
  7277. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  7278. document.getElementById('modal-bgp-peer-remote-port').value = '';
  7279. document.getElementById('modal-bgp-peer-remote-as').value = '';
  7280. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  7281. document.getElementById('modal-bgp-peer-local-addr').value = '';
  7282. document.getElementById('modal-bgp-peer-local-port').value = '';
  7283. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  7284. document.getElementById('modal-bgp-peer-password').value = '';
  7285. document.getElementById('modal-bgp-peer-multihop').checked = false;
  7286. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  7287. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  7288. document.getElementById('modal-bgp-peer-connect').checked = true;
  7289. document.getElementById('modal-bgp-peer-listen').checked = true;
  7290. // Extra Tab
  7291. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  7292. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  7293. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  7294. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  7295. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  7296. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  7297. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  7298. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  7299. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  7300. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  7301. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  7302. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  7303. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = false;
  7304. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = false;
  7305. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  7306. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = false;
  7307. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = false;
  7308. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = false;
  7309. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = '';
  7310. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = '';
  7311. // Attributes Tab
  7312. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  7313. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  7314. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  7315. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  7316. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  7317. document.getElementById('modal-bgp-peer-as-override').checked = false;
  7318. // Filter Tab
  7319. populateFilterChainsDatalist();
  7320. document.getElementById('modal-bgp-peer-in-filter').value = '';
  7321. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = '';
  7322. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = '';
  7323. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = '';
  7324. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = '';
  7325. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = '';
  7326. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = '';
  7327. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = '';
  7328. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = false;
  7329. document.getElementById('modal-bgp-peer-out-filter').value = '';
  7330. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = 'disabled';
  7331. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  7332. populateBgpRoutingTables();
  7333. const container = document.getElementById('modal-bgp-output-networks-container');
  7334. if (container) {
  7335. container.innerHTML = '';
  7336. addOutputNetworkRow('');
  7337. }
  7338. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7339. if (removeBtn) removeBtn.classList.add('hidden');
  7340. switchBgpPeerModalTab('general');
  7341. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  7342. }
  7343. function populateFilterChainsDatalist() {
  7344. const dl = document.getElementById('filter-chains-list');
  7345. if (!dl) return;
  7346. const chains = new Set();
  7347. (state.routingFilters || []).forEach(f => {
  7348. if (f.chain) chains.add(f.chain);
  7349. });
  7350. if (chains.size === 0) {
  7351. chains.add('awmn');
  7352. chains.add('bgp-in');
  7353. chains.add('bgp-out');
  7354. }
  7355. dl.innerHTML = '';
  7356. chains.forEach(c => {
  7357. const opt = document.createElement('option');
  7358. opt.value = c;
  7359. dl.appendChild(opt);
  7360. });
  7361. }
  7362. function openEditBgpPeerModal(id) {
  7363. const p = (state.bgpPeers || []).find(item => item.id === id);
  7364. if (!p) return;
  7365. populateBgpRoutingTables();
  7366. populateFilterChainsDatalist();
  7367. document.getElementById('modal-bgp-peer-id').value = p.id;
  7368. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  7369. // General Tab
  7370. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  7371. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  7372. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  7373. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  7374. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  7375. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  7376. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  7377. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  7378. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  7379. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  7380. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  7381. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  7382. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  7383. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  7384. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  7385. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  7386. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  7387. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  7388. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  7389. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  7390. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  7391. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  7392. // Extra Tab
  7393. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  7394. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  7395. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  7396. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  7397. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  7398. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  7399. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  7400. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  7401. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  7402. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  7403. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  7404. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  7405. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  7406. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = !!p.redist_bgp_mpls_vpn;
  7407. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = !!p.redist_slaac;
  7408. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  7409. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = !!p.network_blackhole;
  7410. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = !!p.no_early_cut;
  7411. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = !!p.keep_sent_attrs;
  7412. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = p.input_affinity || '';
  7413. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = p.output_affinity || '';
  7414. // Attributes Tab
  7415. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  7416. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  7417. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  7418. 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;
  7419. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  7420. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  7421. // Filter Tab
  7422. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  7423. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = p.in_accept_nlri || '';
  7424. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = p.in_accept_communities || '';
  7425. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = p.in_accept_ext_communities || '';
  7426. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = p.in_accept_large_communities || '';
  7427. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = p.in_filter_communities || '';
  7428. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = p.in_filter_ext_communities || '';
  7429. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = p.in_filter_large_communities || '';
  7430. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = !!p.in_filter_unknown;
  7431. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  7432. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = p.out_selection_policy || 'disabled';
  7433. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  7434. // Output Networks
  7435. const container = document.getElementById('modal-bgp-output-networks-container');
  7436. if (container) {
  7437. container.innerHTML = '';
  7438. if (p.output_networks && p.output_networks.length > 0) {
  7439. p.output_networks.forEach(net => addOutputNetworkRow(net));
  7440. } else {
  7441. addOutputNetworkRow('');
  7442. }
  7443. }
  7444. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7445. if (removeBtn) removeBtn.classList.remove('hidden');
  7446. switchBgpPeerModalTab('general');
  7447. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  7448. }
  7449. function copyCurrentBgpPeer() {
  7450. document.getElementById('modal-bgp-peer-id').value = '';
  7451. const nameEl = document.getElementById('modal-bgp-peer-name');
  7452. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  7453. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  7454. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7455. if (removeBtn) removeBtn.classList.add('hidden');
  7456. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  7457. }
  7458. function removeCurrentBgpPeer() {
  7459. const id = document.getElementById('modal-bgp-peer-id')?.value;
  7460. if (!id) return;
  7461. deleteBgpPeer(id);
  7462. closeBgpPeerModal();
  7463. }
  7464. function closeBgpPeerModal() {
  7465. document.getElementById('bgp-peer-modal').classList.add('hidden');
  7466. }
  7467. function getBgpPeerFormData() {
  7468. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  7469. const outputNetworks = [];
  7470. netInputs.forEach(inp => {
  7471. const v = inp.value.trim();
  7472. if (v) outputNetworks.push(v);
  7473. });
  7474. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  7475. return {
  7476. id: document.getElementById('modal-bgp-peer-id').value,
  7477. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  7478. enabled: enabled,
  7479. disabled: !enabled,
  7480. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  7481. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  7482. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  7483. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  7484. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  7485. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  7486. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  7487. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  7488. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  7489. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  7490. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  7491. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  7492. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  7493. password: document.getElementById('modal-bgp-peer-password').value,
  7494. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  7495. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  7496. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  7497. connect: document.getElementById('modal-bgp-peer-connect').checked,
  7498. listen: document.getElementById('modal-bgp-peer-listen').checked,
  7499. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  7500. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  7501. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  7502. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  7503. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  7504. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  7505. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  7506. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  7507. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  7508. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  7509. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  7510. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  7511. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  7512. redist_bgp_mpls_vpn: document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')?.checked || false,
  7513. redist_slaac: document.getElementById('modal-bgp-peer-redist-slaac')?.checked || false,
  7514. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  7515. network_blackhole: document.getElementById('modal-bgp-peer-network-blackhole')?.checked || false,
  7516. no_early_cut: document.getElementById('modal-bgp-peer-no-early-cut')?.checked || false,
  7517. keep_sent_attrs: document.getElementById('modal-bgp-peer-keep-sent-attrs')?.checked || false,
  7518. input_affinity: (document.getElementById('modal-bgp-peer-input-affinity')?.value || '').trim(),
  7519. output_affinity: (document.getElementById('modal-bgp-peer-output-affinity')?.value || '').trim(),
  7520. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  7521. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  7522. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  7523. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  7524. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  7525. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  7526. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  7527. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  7528. in_accept_nlri: (document.getElementById('modal-bgp-peer-in-accept-nlri')?.value || '').trim(),
  7529. in_accept_communities: (document.getElementById('modal-bgp-peer-in-accept-comm')?.value || '').trim(),
  7530. in_accept_ext_communities: (document.getElementById('modal-bgp-peer-in-accept-ext-comm')?.value || '').trim(),
  7531. in_accept_large_communities: (document.getElementById('modal-bgp-peer-in-accept-large-comm')?.value || '').trim(),
  7532. in_filter_communities: (document.getElementById('modal-bgp-peer-in-filter-comm')?.value || '').trim(),
  7533. in_filter_ext_communities: (document.getElementById('modal-bgp-peer-in-filter-ext-comm')?.value || '').trim(),
  7534. in_filter_large_communities: (document.getElementById('modal-bgp-peer-in-filter-large-comm')?.value || '').trim(),
  7535. in_filter_unknown: document.getElementById('modal-bgp-peer-in-filter-unknown')?.checked || false,
  7536. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  7537. out_selection_policy: document.getElementById('modal-bgp-peer-out-selection-policy')?.value || 'disabled',
  7538. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  7539. output_networks: outputNetworks
  7540. };
  7541. }
  7542. async function submitBgpPeer(e) {
  7543. if (e) e.preventDefault();
  7544. const payload = getBgpPeerFormData();
  7545. try {
  7546. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  7547. method: 'POST',
  7548. headers: { 'Content-Type': 'application/json' },
  7549. body: JSON.stringify(payload)
  7550. });
  7551. if (res.ok) {
  7552. closeBgpPeerModal();
  7553. showToast('Success', 'BGP Connection saved', 'success');
  7554. loadDynamicRouting();
  7555. } else {
  7556. const err = await res.json();
  7557. showToast('Error', err.error || 'Failed to save peer', 'error');
  7558. }
  7559. } catch (err) {
  7560. showToast('Error', err.message, 'error');
  7561. }
  7562. }
  7563. async function applyBgpPeerModal(e) {
  7564. if (e) e.preventDefault();
  7565. const payload = getBgpPeerFormData();
  7566. try {
  7567. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  7568. method: 'POST',
  7569. headers: { 'Content-Type': 'application/json' },
  7570. body: JSON.stringify(payload)
  7571. });
  7572. if (res.ok) {
  7573. const data = await res.json();
  7574. if (data.peer && data.peer.id) {
  7575. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  7576. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  7577. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  7578. }
  7579. showToast('Applied', 'BGP Connection applied', 'success');
  7580. loadDynamicRouting();
  7581. } else {
  7582. const err = await res.json();
  7583. showToast('Error', err.error || 'Failed to apply peer', 'error');
  7584. }
  7585. } catch (err) {
  7586. showToast('Error', err.message, 'error');
  7587. }
  7588. }
  7589. async function deleteBgpPeer(id) {
  7590. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  7591. try {
  7592. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7593. if (res.ok) {
  7594. showToast('Deleted', 'BGP peer removed', 'success');
  7595. loadDynamicRouting();
  7596. }
  7597. } catch (err) {
  7598. showToast('Error', err.message, 'error');
  7599. }
  7600. }
  7601. async function toggleBgpPeerState(id, disabled) {
  7602. try {
  7603. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  7604. method: 'POST',
  7605. headers: { 'Content-Type': 'application/json' },
  7606. body: JSON.stringify({ disabled })
  7607. });
  7608. if (res.ok) {
  7609. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  7610. loadDynamicRouting();
  7611. }
  7612. } catch (err) {
  7613. showToast('Error', err.message, 'error');
  7614. }
  7615. }
  7616. function openAddBgpNetworkModal() {
  7617. document.getElementById('bgp-network-form').reset();
  7618. document.getElementById('modal-bgp-net-id').value = '';
  7619. document.getElementById('bgp-network-modal').classList.remove('hidden');
  7620. }
  7621. function closeBgpNetworkModal() {
  7622. document.getElementById('bgp-network-modal').classList.add('hidden');
  7623. }
  7624. async function submitBgpNetwork(e) {
  7625. e.preventDefault();
  7626. const payload = {
  7627. id: document.getElementById('modal-bgp-net-id').value,
  7628. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  7629. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  7630. disabled: document.getElementById('modal-bgp-net-disabled').checked
  7631. };
  7632. try {
  7633. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  7634. method: 'POST',
  7635. headers: { 'Content-Type': 'application/json' },
  7636. body: JSON.stringify(payload)
  7637. });
  7638. if (res.ok) {
  7639. closeBgpNetworkModal();
  7640. showToast('Success', 'BGP network advertisement saved', 'success');
  7641. loadDynamicRouting();
  7642. } else {
  7643. const err = await res.json();
  7644. showToast('Error', err.error || 'Failed to save network', 'error');
  7645. }
  7646. } catch (err) {
  7647. showToast('Error', err.message, 'error');
  7648. }
  7649. }
  7650. async function deleteBgpNetwork(id) {
  7651. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  7652. try {
  7653. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7654. if (res.ok) {
  7655. showToast('Deleted', 'Network advertisement removed', 'success');
  7656. loadDynamicRouting();
  7657. }
  7658. } catch (err) {
  7659. showToast('Error', err.message, 'error');
  7660. }
  7661. }
  7662. // =========================================================================
  7663. // ROUTEROS v7 OSPF MODALS & ACTIONS
  7664. // =========================================================================
  7665. // --- 1. OSPF INSTANCE ---
  7666. function openOspfInstanceModal(id = null) {
  7667. const isEdit = !!id;
  7668. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  7669. id: '',
  7670. name: 'Default',
  7671. version: 2,
  7672. vrf: 'main',
  7673. router_id: '192.168.131.56',
  7674. routing_table: 'main',
  7675. enabled: true,
  7676. redistribute_connected: false,
  7677. redistribute_static: true,
  7678. redistribute_bgp: false,
  7679. comment: ''
  7680. };
  7681. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  7682. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  7683. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  7684. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  7685. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  7686. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  7687. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  7688. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  7689. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  7690. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  7691. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  7692. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  7693. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  7694. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  7695. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  7696. }
  7697. function openEditOspfInstanceModal(id) {
  7698. openOspfInstanceModal(id);
  7699. }
  7700. function closeOspfInstanceModal() {
  7701. document.getElementById('ospf-instance-modal').classList.add('hidden');
  7702. }
  7703. async function submitOspfInstance(e) {
  7704. if (e) e.preventDefault();
  7705. const payload = {
  7706. id: document.getElementById('modal-ospf-inst-id').value,
  7707. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  7708. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  7709. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  7710. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  7711. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  7712. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  7713. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  7714. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  7715. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  7716. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  7717. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  7718. };
  7719. try {
  7720. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  7721. method: 'POST',
  7722. headers: { 'Content-Type': 'application/json' },
  7723. body: JSON.stringify(payload)
  7724. });
  7725. if (res.ok) {
  7726. closeOspfInstanceModal();
  7727. showToast('Saved', 'OSPF instance updated', 'success');
  7728. loadDynamicRouting();
  7729. } else {
  7730. const err = await res.json();
  7731. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  7732. }
  7733. } catch (err) {
  7734. showToast('Error', err.message, 'error');
  7735. }
  7736. }
  7737. function applyOspfInstanceForm() {
  7738. submitOspfInstance(null);
  7739. }
  7740. function copyOspfInstance() {
  7741. document.getElementById('modal-ospf-inst-id').value = '';
  7742. document.getElementById('modal-ospf-inst-name').value += '-copy';
  7743. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  7744. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  7745. }
  7746. async function deleteCurrentOspfInstance() {
  7747. const id = document.getElementById('modal-ospf-inst-id').value;
  7748. if (!id) return;
  7749. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  7750. try {
  7751. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7752. if (res.ok) {
  7753. closeOspfInstanceModal();
  7754. showToast('Removed', 'OSPF instance deleted', 'success');
  7755. loadDynamicRouting();
  7756. }
  7757. } catch (err) {
  7758. showToast('Error', err.message, 'error');
  7759. }
  7760. }
  7761. async function enableSelectedOspfInstance() {
  7762. const id = state.selectedOspfRow?.instances;
  7763. if (!id) return;
  7764. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  7765. method: 'POST',
  7766. headers: { 'Content-Type': 'application/json' },
  7767. body: JSON.stringify({ disabled: false })
  7768. });
  7769. loadDynamicRouting();
  7770. }
  7771. async function disableSelectedOspfInstance() {
  7772. const id = state.selectedOspfRow?.instances;
  7773. if (!id) return;
  7774. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  7775. method: 'POST',
  7776. headers: { 'Content-Type': 'application/json' },
  7777. body: JSON.stringify({ disabled: true })
  7778. });
  7779. loadDynamicRouting();
  7780. }
  7781. async function removeSelectedOspfInstance() {
  7782. const id = state.selectedOspfRow?.instances;
  7783. if (!id) return;
  7784. if (!confirm('Delete selected OSPF instance?')) return;
  7785. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7786. loadDynamicRouting();
  7787. }
  7788. async function promptCommentOspfInstance() {
  7789. const id = state.selectedOspfRow?.instances;
  7790. if (!id) return;
  7791. const inst = (state.ospfInstances || []).find(i => i.id === id);
  7792. if (!inst) return;
  7793. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  7794. if (comment === null) return;
  7795. inst.comment = comment;
  7796. await fetch(`${API_BASE}/routing/ospf/instances`, {
  7797. method: 'POST',
  7798. headers: { 'Content-Type': 'application/json' },
  7799. body: JSON.stringify(inst)
  7800. });
  7801. loadDynamicRouting();
  7802. }
  7803. // --- 2. OSPF AREA ---
  7804. function populateOspfAreaDropdowns() {
  7805. const instSelect = document.getElementById('modal-ospf-area-instance');
  7806. if (instSelect) {
  7807. const cur = instSelect.value;
  7808. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  7809. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  7810. if (cur) instSelect.value = cur;
  7811. }
  7812. }
  7813. function openOspfAreaModal(id = null) {
  7814. const isEdit = !!id;
  7815. populateOspfAreaDropdowns();
  7816. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  7817. id: '',
  7818. name: 'Default',
  7819. instance: 'Default',
  7820. area_id: '0.0.0.0',
  7821. area_type: 'default',
  7822. default_cost: 1,
  7823. no_summaries: false,
  7824. disabled: false,
  7825. comment: ''
  7826. };
  7827. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  7828. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  7829. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  7830. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  7831. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  7832. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  7833. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  7834. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  7835. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  7836. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  7837. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  7838. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  7839. document.getElementById('ospf-area-modal').classList.remove('hidden');
  7840. }
  7841. function openEditOspfAreaModal(id) {
  7842. openOspfAreaModal(id);
  7843. }
  7844. function closeOspfAreaModal() {
  7845. document.getElementById('ospf-area-modal').classList.add('hidden');
  7846. }
  7847. async function submitOspfArea(e) {
  7848. if (e) e.preventDefault();
  7849. const payload = {
  7850. id: document.getElementById('modal-ospf-area-id').value,
  7851. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  7852. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  7853. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  7854. area_type: document.getElementById('modal-ospf-area-type').value,
  7855. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  7856. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  7857. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  7858. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  7859. };
  7860. try {
  7861. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  7862. method: 'POST',
  7863. headers: { 'Content-Type': 'application/json' },
  7864. body: JSON.stringify(payload)
  7865. });
  7866. if (res.ok) {
  7867. closeOspfAreaModal();
  7868. showToast('Saved', 'OSPF area saved', 'success');
  7869. loadDynamicRouting();
  7870. } else {
  7871. const err = await res.json();
  7872. showToast('Error', err.error || 'Failed to save area', 'error');
  7873. }
  7874. } catch (err) {
  7875. showToast('Error', err.message, 'error');
  7876. }
  7877. }
  7878. function applyOspfAreaForm() {
  7879. submitOspfArea(null);
  7880. }
  7881. function copyOspfArea() {
  7882. document.getElementById('modal-ospf-area-id').value = '';
  7883. document.getElementById('modal-ospf-area-name').value += '-copy';
  7884. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  7885. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  7886. }
  7887. async function deleteCurrentOspfArea() {
  7888. const id = document.getElementById('modal-ospf-area-id').value;
  7889. if (!id) return;
  7890. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  7891. try {
  7892. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7893. if (res.ok) {
  7894. closeOspfAreaModal();
  7895. showToast('Removed', 'OSPF area deleted', 'success');
  7896. loadDynamicRouting();
  7897. }
  7898. } catch (err) {
  7899. showToast('Error', err.message, 'error');
  7900. }
  7901. }
  7902. async function enableSelectedOspfArea() {
  7903. const id = state.selectedOspfRow?.areas;
  7904. if (!id) return;
  7905. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  7906. method: 'POST',
  7907. headers: { 'Content-Type': 'application/json' },
  7908. body: JSON.stringify({ disabled: false })
  7909. });
  7910. loadDynamicRouting();
  7911. }
  7912. async function disableSelectedOspfArea() {
  7913. const id = state.selectedOspfRow?.areas;
  7914. if (!id) return;
  7915. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  7916. method: 'POST',
  7917. headers: { 'Content-Type': 'application/json' },
  7918. body: JSON.stringify({ disabled: true })
  7919. });
  7920. loadDynamicRouting();
  7921. }
  7922. async function removeSelectedOspfArea() {
  7923. const id = state.selectedOspfRow?.areas;
  7924. if (!id) return;
  7925. if (!confirm('Delete selected OSPF area?')) return;
  7926. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7927. loadDynamicRouting();
  7928. }
  7929. async function promptCommentOspfArea() {
  7930. const id = state.selectedOspfRow?.areas;
  7931. if (!id) return;
  7932. const area = (state.ospfAreas || []).find(a => a.id === id);
  7933. if (!area) return;
  7934. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  7935. if (comment === null) return;
  7936. area.comment = comment;
  7937. await fetch(`${API_BASE}/routing/ospf/areas`, {
  7938. method: 'POST',
  7939. headers: { 'Content-Type': 'application/json' },
  7940. body: JSON.stringify(area)
  7941. });
  7942. loadDynamicRouting();
  7943. }
  7944. // --- 3. OSPF AREA RANGE ---
  7945. function populateAreaRangeDropdowns() {
  7946. const select = document.getElementById('modal-ospf-range-area');
  7947. if (select) {
  7948. const cur = select.value;
  7949. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  7950. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  7951. if (cur) select.value = cur;
  7952. }
  7953. }
  7954. function openOspfAreaRangeModal(id = null) {
  7955. const isEdit = !!id;
  7956. populateAreaRangeDropdowns();
  7957. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  7958. id: '',
  7959. area: 'Default',
  7960. prefix: '',
  7961. cost: 1,
  7962. advertise: true,
  7963. disabled: false,
  7964. comment: ''
  7965. };
  7966. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  7967. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  7968. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  7969. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  7970. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  7971. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  7972. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  7973. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  7974. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  7975. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  7976. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  7977. }
  7978. function openEditOspfAreaRangeModal(id) {
  7979. openOspfAreaRangeModal(id);
  7980. }
  7981. function closeOspfAreaRangeModal() {
  7982. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  7983. }
  7984. async function submitOspfAreaRange(e) {
  7985. if (e) e.preventDefault();
  7986. const payload = {
  7987. id: document.getElementById('modal-ospf-range-id').value,
  7988. area: document.getElementById('modal-ospf-range-area').value,
  7989. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  7990. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  7991. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  7992. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  7993. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  7994. };
  7995. try {
  7996. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  7997. method: 'POST',
  7998. headers: { 'Content-Type': 'application/json' },
  7999. body: JSON.stringify(payload)
  8000. });
  8001. if (res.ok) {
  8002. closeOspfAreaRangeModal();
  8003. showToast('Saved', 'Area range saved', 'success');
  8004. loadDynamicRouting();
  8005. } else {
  8006. const err = await res.json();
  8007. showToast('Error', err.error || 'Failed to save area range', 'error');
  8008. }
  8009. } catch (err) {
  8010. showToast('Error', err.message, 'error');
  8011. }
  8012. }
  8013. function applyOspfAreaRangeForm() {
  8014. submitOspfAreaRange(null);
  8015. }
  8016. async function deleteCurrentOspfAreaRange() {
  8017. const id = document.getElementById('modal-ospf-range-id').value;
  8018. if (!id) return;
  8019. if (!confirm('Delete this area range?')) return;
  8020. try {
  8021. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8022. closeOspfAreaRangeModal();
  8023. showToast('Removed', 'Area range removed', 'success');
  8024. loadDynamicRouting();
  8025. } catch (err) {
  8026. showToast('Error', err.message, 'error');
  8027. }
  8028. }
  8029. async function enableSelectedOspfAreaRange() {
  8030. const id = state.selectedOspfRow?.['area-ranges'];
  8031. if (!id) return;
  8032. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8033. if (!r) return;
  8034. r.disabled = false;
  8035. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8036. loadDynamicRouting();
  8037. }
  8038. async function disableSelectedOspfAreaRange() {
  8039. const id = state.selectedOspfRow?.['area-ranges'];
  8040. if (!id) return;
  8041. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8042. if (!r) return;
  8043. r.disabled = true;
  8044. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8045. loadDynamicRouting();
  8046. }
  8047. async function removeSelectedOspfAreaRange() {
  8048. const id = state.selectedOspfRow?.['area-ranges'];
  8049. if (!id) return;
  8050. if (!confirm('Delete selected area range?')) return;
  8051. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8052. loadDynamicRouting();
  8053. }
  8054. async function promptCommentOspfAreaRange() {
  8055. const id = state.selectedOspfRow?.['area-ranges'];
  8056. if (!id) return;
  8057. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8058. if (!r) return;
  8059. const comment = prompt('Enter comment for area range:', r.comment || '');
  8060. if (comment === null) return;
  8061. r.comment = comment;
  8062. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8063. loadDynamicRouting();
  8064. }
  8065. // --- 4. OSPF INTERFACE TEMPLATE ---
  8066. function switchOspfTemplateTab(tab) {
  8067. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  8068. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  8069. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  8070. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  8071. if (tab === 'general') {
  8072. if (tabGen) tabGen.classList.remove('hidden');
  8073. if (tabAuth) tabAuth.classList.add('hidden');
  8074. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  8075. 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';
  8076. } else {
  8077. if (tabGen) tabGen.classList.add('hidden');
  8078. if (tabAuth) tabAuth.classList.remove('hidden');
  8079. 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';
  8080. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  8081. }
  8082. }
  8083. function populateTemplateAreaDropdowns() {
  8084. const select = document.getElementById('modal-ospf-tmpl-area');
  8085. if (select) {
  8086. const cur = select.value;
  8087. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8088. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8089. if (cur) select.value = cur;
  8090. }
  8091. }
  8092. function openOspfTemplateModal(id = null) {
  8093. const isEdit = !!id;
  8094. populateTemplateAreaDropdowns();
  8095. switchOspfTemplateTab('general');
  8096. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  8097. id: '',
  8098. interfaces: '',
  8099. area: 'Default',
  8100. networks: '',
  8101. network_type: 'broadcast',
  8102. cost: 1,
  8103. priority: 128,
  8104. passive: false,
  8105. hello_interval: 10,
  8106. dead_interval: 40,
  8107. auth: 'none',
  8108. auth_key: '',
  8109. disabled: false,
  8110. comment: ''
  8111. };
  8112. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  8113. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  8114. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  8115. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  8116. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  8117. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  8118. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  8119. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  8120. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  8121. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  8122. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  8123. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  8124. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  8125. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  8126. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  8127. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  8128. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8129. document.getElementById('ospf-template-modal').classList.remove('hidden');
  8130. }
  8131. function openEditOspfTemplateModal(id) {
  8132. openOspfTemplateModal(id);
  8133. }
  8134. function closeOspfTemplateModal() {
  8135. document.getElementById('ospf-template-modal').classList.add('hidden');
  8136. }
  8137. async function submitOspfTemplate(e) {
  8138. if (e) e.preventDefault();
  8139. const payload = {
  8140. id: document.getElementById('modal-ospf-tmpl-id').value,
  8141. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  8142. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  8143. area: document.getElementById('modal-ospf-tmpl-area').value,
  8144. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  8145. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  8146. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  8147. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  8148. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  8149. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  8150. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  8151. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  8152. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  8153. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  8154. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  8155. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  8156. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  8157. };
  8158. try {
  8159. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  8160. method: 'POST',
  8161. headers: { 'Content-Type': 'application/json' },
  8162. body: JSON.stringify(payload)
  8163. });
  8164. if (res.ok) {
  8165. closeOspfTemplateModal();
  8166. showToast('Saved', 'Interface template saved', 'success');
  8167. loadDynamicRouting();
  8168. } else {
  8169. const err = await res.json();
  8170. showToast('Error', err.error || 'Failed to save interface template', 'error');
  8171. }
  8172. } catch (err) {
  8173. showToast('Error', err.message, 'error');
  8174. }
  8175. }
  8176. function applyOspfTemplateForm() {
  8177. submitOspfTemplate(null);
  8178. }
  8179. function copyOspfTemplate() {
  8180. document.getElementById('modal-ospf-tmpl-id').value = '';
  8181. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  8182. showToast('Copied', 'Duplicated as new template', 'info');
  8183. }
  8184. async function deleteCurrentOspfTemplate() {
  8185. const id = document.getElementById('modal-ospf-tmpl-id').value;
  8186. if (!id) return;
  8187. if (!confirm('Delete this interface template?')) return;
  8188. try {
  8189. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8190. closeOspfTemplateModal();
  8191. showToast('Removed', 'Interface template deleted', 'success');
  8192. loadDynamicRouting();
  8193. } catch (err) {
  8194. showToast('Error', err.message, 'error');
  8195. }
  8196. }
  8197. async function enableSelectedOspfTemplate() {
  8198. const id = state.selectedOspfRow?.templates;
  8199. if (!id) return;
  8200. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8201. method: 'POST',
  8202. headers: { 'Content-Type': 'application/json' },
  8203. body: JSON.stringify({ disabled: false })
  8204. });
  8205. loadDynamicRouting();
  8206. }
  8207. async function disableSelectedOspfTemplate() {
  8208. const id = state.selectedOspfRow?.templates;
  8209. if (!id) return;
  8210. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8211. method: 'POST',
  8212. headers: { 'Content-Type': 'application/json' },
  8213. body: JSON.stringify({ disabled: true })
  8214. });
  8215. loadDynamicRouting();
  8216. }
  8217. async function removeSelectedOspfTemplate() {
  8218. const id = state.selectedOspfRow?.templates;
  8219. if (!id) return;
  8220. if (!confirm('Delete selected interface template?')) return;
  8221. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8222. loadDynamicRouting();
  8223. }
  8224. async function promptCommentOspfTemplate() {
  8225. const id = state.selectedOspfRow?.templates;
  8226. if (!id) return;
  8227. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  8228. if (!tmpl) return;
  8229. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  8230. if (comment === null) return;
  8231. tmpl.comment = comment;
  8232. await fetch(`${API_BASE}/routing/ospf/templates`, {
  8233. method: 'POST',
  8234. headers: { 'Content-Type': 'application/json' },
  8235. body: JSON.stringify(tmpl)
  8236. });
  8237. loadDynamicRouting();
  8238. }
  8239. // --- 5. OSPF STATIC NEIGHBOR ---
  8240. function populateStaticNbrAreaDropdowns() {
  8241. const select = document.getElementById('modal-ospf-snbr-area');
  8242. if (select) {
  8243. const cur = select.value;
  8244. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8245. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8246. if (cur) select.value = cur;
  8247. }
  8248. }
  8249. function openOspfStaticNbrModal(id = null) {
  8250. const isEdit = !!id;
  8251. populateStaticNbrAreaDropdowns();
  8252. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  8253. id: '',
  8254. address: '',
  8255. area: 'Default',
  8256. poll_interval: 120,
  8257. cost: 1,
  8258. disabled: false,
  8259. comment: ''
  8260. };
  8261. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  8262. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  8263. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  8264. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  8265. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  8266. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  8267. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  8268. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  8269. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  8270. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8271. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  8272. }
  8273. function openEditOspfStaticNbrModal(id) {
  8274. openOspfStaticNbrModal(id);
  8275. }
  8276. function closeOspfStaticNbrModal() {
  8277. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  8278. }
  8279. async function submitOspfStaticNbr(e) {
  8280. if (e) e.preventDefault();
  8281. const payload = {
  8282. id: document.getElementById('modal-ospf-snbr-id').value,
  8283. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  8284. area: document.getElementById('modal-ospf-snbr-area').value,
  8285. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  8286. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  8287. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  8288. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  8289. };
  8290. try {
  8291. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  8292. method: 'POST',
  8293. headers: { 'Content-Type': 'application/json' },
  8294. body: JSON.stringify(payload)
  8295. });
  8296. if (res.ok) {
  8297. closeOspfStaticNbrModal();
  8298. showToast('Saved', 'Static neighbor saved', 'success');
  8299. loadDynamicRouting();
  8300. } else {
  8301. const err = await res.json();
  8302. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  8303. }
  8304. } catch (err) {
  8305. showToast('Error', err.message, 'error');
  8306. }
  8307. }
  8308. function applyOspfStaticNbrForm() {
  8309. submitOspfStaticNbr(null);
  8310. }
  8311. async function deleteCurrentOspfStaticNbr() {
  8312. const id = document.getElementById('modal-ospf-snbr-id').value;
  8313. if (!id) return;
  8314. if (!confirm('Delete this static neighbor?')) return;
  8315. try {
  8316. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8317. closeOspfStaticNbrModal();
  8318. showToast('Removed', 'Static neighbor removed', 'success');
  8319. loadDynamicRouting();
  8320. } catch (err) {
  8321. showToast('Error', err.message, 'error');
  8322. }
  8323. }
  8324. async function enableSelectedOspfStaticNbr() {
  8325. const id = state.selectedOspfRow?.['static-nbrs'];
  8326. if (!id) return;
  8327. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8328. if (!n) return;
  8329. n.disabled = false;
  8330. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8331. loadDynamicRouting();
  8332. }
  8333. async function disableSelectedOspfStaticNbr() {
  8334. const id = state.selectedOspfRow?.['static-nbrs'];
  8335. if (!id) return;
  8336. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8337. if (!n) return;
  8338. n.disabled = true;
  8339. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8340. loadDynamicRouting();
  8341. }
  8342. async function removeSelectedOspfStaticNbr() {
  8343. const id = state.selectedOspfRow?.['static-nbrs'];
  8344. if (!id) return;
  8345. if (!confirm('Delete selected static neighbor?')) return;
  8346. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8347. loadDynamicRouting();
  8348. }
  8349. async function promptCommentOspfStaticNbr() {
  8350. const id = state.selectedOspfRow?.['static-nbrs'];
  8351. if (!id) return;
  8352. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8353. if (!n) return;
  8354. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  8355. if (comment === null) return;
  8356. n.comment = comment;
  8357. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8358. loadDynamicRouting();
  8359. }
  8360. // Backward-compat aliases
  8361. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  8362. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  8363. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  8364. function submitOspfInterface(e) { submitOspfTemplate(e); }
  8365. function deleteOspfInterface(id) {
  8366. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  8367. }
  8368. function toggleOspfInterfaceState(id, disabled) {
  8369. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8370. method: 'POST',
  8371. headers: { 'Content-Type': 'application/json' },
  8372. body: JSON.stringify({ disabled })
  8373. }).then(() => loadDynamicRouting());
  8374. }
  8375. function openAddOspfAreaModal() { openOspfAreaModal(); }
  8376. function deleteOspfArea(id) {
  8377. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  8378. }
  8379. // ============================================================================
  8380. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  8381. // ============================================================================
  8382. function switchBridgeSubTab(tab) {
  8383. state.bridgeSubTab = tab;
  8384. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  8385. tabs.forEach(t => {
  8386. const panel = document.getElementById(`bridge-subtab-${t}`);
  8387. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  8388. if (panel) {
  8389. if (t === tab) panel.classList.remove('hidden');
  8390. else panel.classList.add('hidden');
  8391. }
  8392. if (btn) {
  8393. if (t === tab) {
  8394. 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';
  8395. } else {
  8396. 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';
  8397. }
  8398. }
  8399. });
  8400. const addBtn = document.getElementById('bridge-top-action-btn');
  8401. if (addBtn) {
  8402. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  8403. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  8404. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  8405. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  8406. }
  8407. if (tab === 'hosts') loadBridgeHosts();
  8408. setTimeout(initTableSorting, 50);
  8409. }
  8410. function openCurrentBridgeModal() {
  8411. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  8412. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  8413. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  8414. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  8415. }
  8416. async function loadBridge() {
  8417. try {
  8418. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  8419. fetch(`${API_BASE}/bridge/bridges`),
  8420. fetch(`${API_BASE}/bridge/ports`),
  8421. fetch(`${API_BASE}/bridge/vlans`),
  8422. fetch(`${API_BASE}/bridge/summary`),
  8423. fetch(`${API_BASE}/vpn/eoip`),
  8424. fetch(`${API_BASE}/vlans`)
  8425. ]);
  8426. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  8427. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  8428. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  8429. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  8430. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  8431. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  8432. // Badges & Stats
  8433. const bBridges = document.getElementById('bridge-badge-bridges');
  8434. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  8435. const bPorts = document.getElementById('bridge-badge-ports');
  8436. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  8437. const bVlans = document.getElementById('bridge-badge-vlans');
  8438. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  8439. const bHosts = document.getElementById('bridge-badge-hosts');
  8440. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  8441. const sBr = document.getElementById('bridge-stat-bridges');
  8442. if (sBr) sBr.innerText = (state.bridges || []).length;
  8443. const sPorts = document.getElementById('bridge-stat-ports');
  8444. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  8445. const sHosts = document.getElementById('bridge-stat-hosts');
  8446. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  8447. renderBridges();
  8448. renderBridgePorts();
  8449. renderBridgeVLANs();
  8450. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  8451. } catch (err) {
  8452. console.error('Failed to load bridge subsystem:', err);
  8453. }
  8454. }
  8455. // ----------------- Bridges -----------------
  8456. function renderBridges() {
  8457. const tbody = document.getElementById('bridge-table-body');
  8458. const empty = document.getElementById('bridge-empty-bridges');
  8459. const countBadge = document.getElementById('bridge-count-badge');
  8460. if (!tbody) return;
  8461. tbody.innerHTML = '';
  8462. const bridges = state.bridges || [];
  8463. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  8464. if (bridges.length === 0) {
  8465. empty?.classList.remove('hidden');
  8466. return;
  8467. }
  8468. empty?.classList.add('hidden');
  8469. bridges.forEach((b, idx) => {
  8470. const tr = document.createElement('tr');
  8471. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  8472. // Format IP addresses pill list
  8473. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  8474. if (b.ip_addresses && b.ip_addresses.length > 0) {
  8475. ipsHtml = b.ip_addresses.map(ip => `
  8476. <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">
  8477. <span>${ip}</span>
  8478. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  8479. </span>
  8480. `).join(' ');
  8481. }
  8482. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  8483. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  8484. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  8485. tr.innerHTML = `
  8486. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  8487. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  8488. <td class="py-2.5 px-3 font-bold text-white text-sm">
  8489. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  8490. </td>
  8491. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  8492. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  8493. <td class="py-2.5 px-3">
  8494. <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>
  8495. </td>
  8496. <td class="py-2.5 px-3 text-center">
  8497. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  8498. </td>
  8499. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  8500. <td class="py-2.5 px-3">
  8501. <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>
  8502. </td>
  8503. <td class="py-2.5 px-3">
  8504. <div class="flex items-center gap-1.5 flex-wrap">
  8505. ${ipsHtml}
  8506. <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>
  8507. </div>
  8508. </td>
  8509. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  8510. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  8511. </td>
  8512. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  8513. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8514. <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>
  8515. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8516. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  8517. </td>
  8518. `;
  8519. tbody.appendChild(tr);
  8520. });
  8521. }
  8522. function openAddBridgeModal() {
  8523. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  8524. document.getElementById('bridge-modal-id').value = '';
  8525. document.getElementById('bridge-modal-name').value = 'bridge1';
  8526. document.getElementById('bridge-modal-name').disabled = false;
  8527. document.getElementById('bridge-modal-mtu').value = '1500';
  8528. document.getElementById('bridge-modal-mac').value = '';
  8529. document.getElementById('bridge-modal-stp').value = 'rstp';
  8530. document.getElementById('bridge-modal-priority').value = '32768';
  8531. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  8532. document.getElementById('bridge-modal-pvid').value = '1';
  8533. document.getElementById('bridge-modal-fastforward').checked = true;
  8534. document.getElementById('bridge-modal-comment').value = '';
  8535. document.getElementById('bridge-modal-disabled').checked = false;
  8536. toggleBridgeModalVlanFiltering();
  8537. document.getElementById('bridge-modal').classList.remove('hidden');
  8538. }
  8539. function openEditBridgeModal(id) {
  8540. const b = (state.bridges || []).find(x => x.id === id);
  8541. if (!b) return;
  8542. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  8543. document.getElementById('bridge-modal-id').value = b.id;
  8544. document.getElementById('bridge-modal-name').value = b.name;
  8545. document.getElementById('bridge-modal-name').disabled = true;
  8546. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  8547. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  8548. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  8549. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  8550. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  8551. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  8552. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  8553. document.getElementById('bridge-modal-comment').value = b.comment || '';
  8554. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  8555. toggleBridgeModalVlanFiltering();
  8556. document.getElementById('bridge-modal').classList.remove('hidden');
  8557. }
  8558. function closeBridgeModal() {
  8559. document.getElementById('bridge-modal').classList.add('hidden');
  8560. }
  8561. function toggleBridgeModalVlanFiltering() {
  8562. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  8563. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  8564. if (pvidBox) {
  8565. if (chk) pvidBox.classList.remove('opacity-40');
  8566. else pvidBox.classList.add('opacity-40');
  8567. }
  8568. }
  8569. async function submitSaveBridge(e) {
  8570. e.preventDefault();
  8571. const id = document.getElementById('bridge-modal-id').value;
  8572. const name = document.getElementById('bridge-modal-name').value.trim();
  8573. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  8574. const mac = document.getElementById('bridge-modal-mac').value.trim();
  8575. const stp = document.getElementById('bridge-modal-stp').value;
  8576. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  8577. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  8578. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  8579. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  8580. const comment = document.getElementById('bridge-modal-comment').value.trim();
  8581. const disabled = document.getElementById('bridge-modal-disabled').checked;
  8582. try {
  8583. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  8584. method: 'POST',
  8585. headers: { 'Content-Type': 'application/json' },
  8586. body: JSON.stringify({
  8587. id,
  8588. name,
  8589. mtu,
  8590. mac_address: mac,
  8591. stp,
  8592. priority,
  8593. vlan_filtering: vlanFiltering,
  8594. pvid,
  8595. fast_forward: fastForward,
  8596. comment,
  8597. disabled
  8598. })
  8599. });
  8600. if (res.ok) {
  8601. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  8602. closeBridgeModal();
  8603. loadBridge();
  8604. fetchData(false);
  8605. } else {
  8606. const err = await res.json();
  8607. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  8608. }
  8609. } catch (err) {
  8610. showToast('Error', err.message, 'error');
  8611. }
  8612. }
  8613. async function toggleBridgeState(id, disabled) {
  8614. try {
  8615. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  8616. method: 'POST',
  8617. headers: { 'Content-Type': 'application/json' },
  8618. body: JSON.stringify({ disabled })
  8619. });
  8620. if (res.ok) {
  8621. loadBridge();
  8622. fetchData(false);
  8623. }
  8624. } catch (err) {
  8625. showToast('Error', err.message, 'error');
  8626. }
  8627. }
  8628. async function deleteBridge(id) {
  8629. const b = (state.bridges || []).find(x => x.id === id);
  8630. const name = b ? b.name : id;
  8631. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  8632. try {
  8633. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8634. if (res.ok) {
  8635. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  8636. loadBridge();
  8637. fetchData(false);
  8638. } else {
  8639. const err = await res.json();
  8640. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  8641. }
  8642. } catch (err) {
  8643. showToast('Error', err.message, 'error');
  8644. }
  8645. }
  8646. // ----------------- Bridge IP Assignments -----------------
  8647. function openAddBridgeIPModal(id, name) {
  8648. document.getElementById('bridge-ip-modal-id').value = id;
  8649. document.getElementById('bridge-ip-modal-sub').innerText = name;
  8650. document.getElementById('bridge-ip-modal-cidr').value = '';
  8651. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  8652. }
  8653. function closeBridgeIPModal() {
  8654. document.getElementById('bridge-ip-modal').classList.add('hidden');
  8655. }
  8656. async function submitAddBridgeIP(e) {
  8657. e.preventDefault();
  8658. const id = document.getElementById('bridge-ip-modal-id').value;
  8659. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  8660. try {
  8661. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  8662. method: 'POST',
  8663. headers: { 'Content-Type': 'application/json' },
  8664. body: JSON.stringify({ ip })
  8665. });
  8666. if (res.ok) {
  8667. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  8668. closeBridgeIPModal();
  8669. loadBridge();
  8670. fetchData(false);
  8671. } else {
  8672. const err = await res.json();
  8673. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  8674. }
  8675. } catch (err) {
  8676. showToast('Error', err.message, 'error');
  8677. }
  8678. }
  8679. async function deleteBridgeIP(id, ip) {
  8680. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  8681. try {
  8682. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  8683. method: 'DELETE',
  8684. headers: { 'Content-Type': 'application/json' },
  8685. body: JSON.stringify({ ip })
  8686. });
  8687. if (res.ok) {
  8688. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  8689. loadBridge();
  8690. fetchData(false);
  8691. }
  8692. } catch (err) {
  8693. showToast('Error', err.message, 'error');
  8694. }
  8695. }
  8696. // ----------------- Bridge Ports -----------------
  8697. function renderBridgePorts() {
  8698. const tbody = document.getElementById('bridge-ports-table-body');
  8699. const empty = document.getElementById('bridge-empty-ports');
  8700. const countBadge = document.getElementById('bridge-ports-count-badge');
  8701. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  8702. if (!tbody) return;
  8703. tbody.innerHTML = '';
  8704. // Update filter select
  8705. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  8706. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  8707. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  8708. if (ports.length === 0) {
  8709. empty?.classList.remove('hidden');
  8710. return;
  8711. }
  8712. empty?.classList.add('hidden');
  8713. ports.forEach((p, idx) => {
  8714. const tr = document.createElement('tr');
  8715. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  8716. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  8717. tr.innerHTML = `
  8718. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  8719. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  8720. <td class="py-2.5 px-3 font-bold text-white text-sm">
  8721. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  8722. </td>
  8723. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  8724. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  8725. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  8726. <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>
  8727. <td class="py-2.5 px-3">
  8728. ${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>'}
  8729. </td>
  8730. <td class="py-2.5 px-3">
  8731. <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>
  8732. </td>
  8733. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  8734. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8735. <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>
  8736. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8737. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  8738. </td>
  8739. `;
  8740. tbody.appendChild(tr);
  8741. });
  8742. }
  8743. function openAddBridgePortModal() {
  8744. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  8745. document.getElementById('bridge-port-modal-id').value = '';
  8746. populateBridgeSelect('bridge-port-modal-bridge');
  8747. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  8748. document.getElementById('bridge-port-modal-pvid').value = '1';
  8749. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  8750. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  8751. document.getElementById('bridge-port-modal-horizon').value = '0';
  8752. document.getElementById('bridge-port-modal-pathcost').value = '10';
  8753. document.getElementById('bridge-port-modal-priority').value = '128';
  8754. document.getElementById('bridge-port-modal-learn').checked = true;
  8755. document.getElementById('bridge-port-modal-comment').value = '';
  8756. document.getElementById('bridge-port-modal-disabled').checked = false;
  8757. document.getElementById('bridge-port-modal').classList.remove('hidden');
  8758. }
  8759. function openEditBridgePortModal(id) {
  8760. const p = (state.bridgePorts || []).find(x => x.id === id);
  8761. if (!p) return;
  8762. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  8763. document.getElementById('bridge-port-modal-id').value = p.id;
  8764. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  8765. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  8766. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  8767. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  8768. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  8769. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  8770. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  8771. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  8772. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  8773. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  8774. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  8775. document.getElementById('bridge-port-modal').classList.remove('hidden');
  8776. }
  8777. function closeBridgePortModal() {
  8778. document.getElementById('bridge-port-modal').classList.add('hidden');
  8779. }
  8780. async function submitSaveBridgePort(e) {
  8781. e.preventDefault();
  8782. const id = document.getElementById('bridge-port-modal-id').value;
  8783. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  8784. const iface = document.getElementById('bridge-port-modal-interface').value;
  8785. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  8786. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  8787. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  8788. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  8789. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  8790. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  8791. const learn = document.getElementById('bridge-port-modal-learn').checked;
  8792. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  8793. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  8794. try {
  8795. const res = await fetch(`${API_BASE}/bridge/ports`, {
  8796. method: 'POST',
  8797. headers: { 'Content-Type': 'application/json' },
  8798. body: JSON.stringify({
  8799. id,
  8800. bridge,
  8801. interface: iface,
  8802. pvid,
  8803. frame_types: frameTypes,
  8804. ingress_filtering: ingressFiltering,
  8805. horizon,
  8806. path_cost: pathCost,
  8807. priority,
  8808. learn,
  8809. comment,
  8810. disabled
  8811. })
  8812. });
  8813. if (res.ok) {
  8814. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  8815. closeBridgePortModal();
  8816. loadBridge();
  8817. fetchData(false);
  8818. } else {
  8819. const err = await res.json();
  8820. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  8821. }
  8822. } catch (err) {
  8823. showToast('Error', err.message, 'error');
  8824. }
  8825. }
  8826. async function toggleBridgePortState(id, disabled) {
  8827. try {
  8828. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  8829. method: 'POST',
  8830. headers: { 'Content-Type': 'application/json' },
  8831. body: JSON.stringify({ disabled })
  8832. });
  8833. if (res.ok) {
  8834. loadBridge();
  8835. fetchData(false);
  8836. }
  8837. } catch (err) {
  8838. showToast('Error', err.message, 'error');
  8839. }
  8840. }
  8841. async function deleteBridgePort(id) {
  8842. const p = (state.bridgePorts || []).find(x => x.id === id);
  8843. const iface = p ? p.interface : id;
  8844. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  8845. try {
  8846. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8847. if (res.ok) {
  8848. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  8849. loadBridge();
  8850. fetchData(false);
  8851. }
  8852. } catch (err) {
  8853. showToast('Error', err.message, 'error');
  8854. }
  8855. }
  8856. // ----------------- Bridge VLANs -----------------
  8857. function renderBridgeVLANs() {
  8858. const tbody = document.getElementById('bridge-vlans-table-body');
  8859. const empty = document.getElementById('bridge-empty-vlans');
  8860. const countBadge = document.getElementById('bridge-vlans-count-badge');
  8861. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  8862. if (!tbody) return;
  8863. tbody.innerHTML = '';
  8864. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  8865. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  8866. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  8867. if (vlans.length === 0) {
  8868. empty?.classList.remove('hidden');
  8869. return;
  8870. }
  8871. empty?.classList.add('hidden');
  8872. vlans.forEach((v, idx) => {
  8873. const tr = document.createElement('tr');
  8874. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  8875. const taggedHtml = (v.tagged && v.tagged.length > 0)
  8876. ? 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(' ')
  8877. : '<span class="text-slate-600">none</span>';
  8878. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  8879. ? 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(' ')
  8880. : '<span class="text-slate-600">none</span>';
  8881. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  8882. tr.innerHTML = `
  8883. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  8884. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  8885. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  8886. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  8887. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  8888. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  8889. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  8890. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8891. <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>
  8892. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8893. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  8894. </td>
  8895. `;
  8896. tbody.appendChild(tr);
  8897. });
  8898. }
  8899. function openAddBridgeVLANModal() {
  8900. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  8901. document.getElementById('bridge-vlan-modal-id').value = '';
  8902. populateBridgeSelect('bridge-vlan-modal-bridge');
  8903. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  8904. document.getElementById('bridge-vlan-modal-comment').value = '';
  8905. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  8906. updateBridgeVlanPortCheckboxes();
  8907. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  8908. }
  8909. function openEditBridgeVLANModal(id) {
  8910. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  8911. if (!v) return;
  8912. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  8913. document.getElementById('bridge-vlan-modal-id').value = v.id;
  8914. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  8915. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  8916. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  8917. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  8918. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  8919. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  8920. }
  8921. function closeBridgeVlanModal() {
  8922. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  8923. }
  8924. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  8925. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  8926. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  8927. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  8928. if (!taggedBox || !untaggedBox) return;
  8929. // Ports belonging to the selected bridge
  8930. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  8931. if (memberPorts.length === 0) {
  8932. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  8933. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  8934. return;
  8935. }
  8936. taggedBox.innerHTML = memberPorts.map(p => `
  8937. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  8938. <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">
  8939. <span>${p.interface}</span>
  8940. </label>
  8941. `).join('');
  8942. untaggedBox.innerHTML = memberPorts.map(p => `
  8943. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  8944. <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">
  8945. <span>${p.interface}</span>
  8946. </label>
  8947. `).join('');
  8948. }
  8949. async function submitSaveBridgeVLAN(e) {
  8950. e.preventDefault();
  8951. const id = document.getElementById('bridge-vlan-modal-id').value;
  8952. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  8953. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  8954. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  8955. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  8956. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  8957. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  8958. try {
  8959. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  8960. method: 'POST',
  8961. headers: { 'Content-Type': 'application/json' },
  8962. body: JSON.stringify({
  8963. id,
  8964. bridge,
  8965. vlan_ids: vlanIDs,
  8966. tagged,
  8967. untagged,
  8968. comment,
  8969. disabled
  8970. })
  8971. });
  8972. if (res.ok) {
  8973. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  8974. closeBridgeVlanModal();
  8975. loadBridge();
  8976. } else {
  8977. const err = await res.json();
  8978. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  8979. }
  8980. } catch (err) {
  8981. showToast('Error', err.message, 'error');
  8982. }
  8983. }
  8984. async function toggleBridgeVLANState(id, disabled) {
  8985. try {
  8986. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  8987. method: 'POST',
  8988. headers: { 'Content-Type': 'application/json' },
  8989. body: JSON.stringify({ disabled })
  8990. });
  8991. if (res.ok) loadBridge();
  8992. } catch (err) {
  8993. showToast('Error', err.message, 'error');
  8994. }
  8995. }
  8996. async function deleteBridgeVLAN(id) {
  8997. if (!confirm('Delete this bridge VLAN entry?')) return;
  8998. try {
  8999. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9000. if (res.ok) {
  9001. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  9002. loadBridge();
  9003. }
  9004. } catch (err) {
  9005. showToast('Error', err.message, 'error');
  9006. }
  9007. }
  9008. // ----------------- Hosts / MAC Table -----------------
  9009. async function loadBridgeHosts() {
  9010. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  9011. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  9012. try {
  9013. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  9014. const res = await fetch(url);
  9015. if (res.ok) {
  9016. state.bridgeHosts = await res.json();
  9017. renderBridgeHosts();
  9018. }
  9019. } catch (err) {
  9020. console.error('Failed to load bridge hosts:', err);
  9021. }
  9022. }
  9023. function renderBridgeHosts() {
  9024. const tbody = document.getElementById('bridge-hosts-table-body');
  9025. const empty = document.getElementById('bridge-empty-hosts');
  9026. const countBadge = document.getElementById('bridge-hosts-count-badge');
  9027. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  9028. if (!tbody) return;
  9029. tbody.innerHTML = '';
  9030. const hosts = (state.bridgeHosts || []).filter(h => {
  9031. if (!search) return true;
  9032. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  9033. });
  9034. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  9035. if (hosts.length === 0) {
  9036. empty?.classList.remove('hidden');
  9037. return;
  9038. }
  9039. empty?.classList.add('hidden');
  9040. hosts.forEach(h => {
  9041. const tr = document.createElement('tr');
  9042. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  9043. let flagBadges = '';
  9044. 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>';
  9045. 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>';
  9046. 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>';
  9047. tr.innerHTML = `
  9048. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  9049. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  9050. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  9051. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  9052. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  9053. <td class="py-2.5 px-3">${flagBadges}</td>
  9054. `;
  9055. tbody.appendChild(tr);
  9056. });
  9057. }
  9058. async function flushBridgeHosts() {
  9059. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  9060. if (!selBridge) {
  9061. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  9062. return;
  9063. }
  9064. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  9065. try {
  9066. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  9067. method: 'POST',
  9068. headers: { 'Content-Type': 'application/json' },
  9069. body: JSON.stringify({ bridge: selBridge })
  9070. });
  9071. if (res.ok) {
  9072. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  9073. loadBridgeHosts();
  9074. }
  9075. } catch (err) {
  9076. showToast('Error', err.message, 'error');
  9077. }
  9078. }
  9079. // ----------------- Helpers -----------------
  9080. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  9081. const sel = document.getElementById(selectId);
  9082. if (!sel) return;
  9083. const prevVal = currentVal || sel.value;
  9084. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  9085. (state.bridges || []).forEach(b => {
  9086. const opt = document.createElement('option');
  9087. opt.value = b.name;
  9088. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  9089. if (b.name === prevVal) opt.selected = true;
  9090. sel.appendChild(opt);
  9091. });
  9092. }
  9093. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  9094. const sel = document.getElementById(selectId);
  9095. if (!sel) return;
  9096. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  9097. // 1. Physical Interfaces
  9098. const grpPhys = document.createElement('optgroup');
  9099. grpPhys.label = 'Physical Interfaces';
  9100. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  9101. const opt = document.createElement('option');
  9102. opt.value = i.name;
  9103. opt.innerText = `${i.name} (${i.role || i.type})`;
  9104. if (i.name === currentVal) opt.selected = true;
  9105. grpPhys.appendChild(opt);
  9106. });
  9107. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  9108. // 2. VLAN Sub-interfaces
  9109. const grpVlans = document.createElement('optgroup');
  9110. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  9111. (state.vlans || []).forEach(v => {
  9112. const opt = document.createElement('option');
  9113. opt.value = v.name;
  9114. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  9115. if (v.name === currentVal) opt.selected = true;
  9116. grpVlans.appendChild(opt);
  9117. });
  9118. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  9119. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  9120. const grpEoip = document.createElement('optgroup');
  9121. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  9122. (state.eoipTunnels || []).forEach(t => {
  9123. const opt = document.createElement('option');
  9124. opt.value = t.name;
  9125. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  9126. if (t.name === currentVal) opt.selected = true;
  9127. grpEoip.appendChild(opt);
  9128. });
  9129. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  9130. }
  9131. // -------------------------------------------------------------
  9132. // RouterOS v7 Routing Filters Management (/routing filter)
  9133. // -------------------------------------------------------------
  9134. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  9135. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  9136. if (!state.rfSort) state.rfSort = {};
  9137. function switchRoutingFilterTab(tab) {
  9138. state.activeRoutingFilterTab = tab;
  9139. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  9140. tabs.forEach(t => {
  9141. const btn = document.getElementById(`tab-rf-${t}`);
  9142. const content = document.getElementById(`tab-content-rf-${t}`);
  9143. if (btn) {
  9144. if (t === tab) {
  9145. 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';
  9146. } else {
  9147. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  9148. }
  9149. }
  9150. if (content) {
  9151. if (t === tab) content.classList.remove('hidden');
  9152. else content.classList.add('hidden');
  9153. }
  9154. });
  9155. const chainContainer = document.getElementById('rf-chain-filter-container');
  9156. if (chainContainer) {
  9157. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  9158. else chainContainer.classList.add('hidden');
  9159. }
  9160. renderRoutingFilters();
  9161. }
  9162. function selectFilterRow(tab, id) {
  9163. if (state.selectedFilterRow[tab] === id) {
  9164. delete state.selectedFilterRow[tab];
  9165. } else {
  9166. state.selectedFilterRow[tab] = id;
  9167. }
  9168. if (tab === 'rules') renderRoutingFilterRules();
  9169. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  9170. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  9171. else if (tab === 'as-lists') renderRoutingFilterASLists();
  9172. }
  9173. function openRoutingFilterNewModal() {
  9174. const tab = state.activeRoutingFilterTab || 'rules';
  9175. if (tab === 'rules') openAddRoutingFilterModal();
  9176. else if (tab === 'select-rules') openAddSelectRuleModal();
  9177. else if (tab === 'community-lists') openAddCommunityListModal();
  9178. else if (tab === 'as-lists') openAddASListModal();
  9179. }
  9180. function toggleSelectedRoutingFilter(disabled) {
  9181. const tab = state.activeRoutingFilterTab || 'rules';
  9182. const id = state.selectedFilterRow[tab];
  9183. if (!id) {
  9184. showToast('Select Row', 'Please click on a row to select it first', 'info');
  9185. return;
  9186. }
  9187. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  9188. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  9189. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  9190. else if (tab === 'as-lists') toggleASListState(id, disabled);
  9191. }
  9192. function removeSelectedRoutingFilter() {
  9193. const tab = state.activeRoutingFilterTab || 'rules';
  9194. const id = state.selectedFilterRow[tab];
  9195. if (!id) {
  9196. showToast('Select Row', 'Please click on a row to select it first', 'info');
  9197. return;
  9198. }
  9199. if (tab === 'rules') deleteRoutingFilter(id);
  9200. else if (tab === 'select-rules') deleteSelectRule(id);
  9201. else if (tab === 'community-lists') deleteCommunityList(id);
  9202. else if (tab === 'as-lists') deleteASList(id);
  9203. }
  9204. function searchRoutingFilters(q) {
  9205. state.rfSearchQuery = (q || '').trim().toLowerCase();
  9206. renderRoutingFilters();
  9207. }
  9208. function sortFilterTable(tab, col) {
  9209. if (!state.rfSort) state.rfSort = {};
  9210. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  9211. if (state.rfSort[tab].col === col) {
  9212. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  9213. } else {
  9214. state.rfSort[tab].col = col;
  9215. state.rfSort[tab].asc = true;
  9216. }
  9217. const asc = state.rfSort[tab].asc;
  9218. let list = [];
  9219. if (tab === 'rules') list = state.routingFilters || [];
  9220. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  9221. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  9222. else if (tab === 'as-lists') list = state.routingASLists || [];
  9223. list.sort((a, b) => {
  9224. let valA = a[col] ?? '';
  9225. let valB = b[col] ?? '';
  9226. if (col === 'flags') {
  9227. valA = a.disabled ? 'X' : 'A';
  9228. valB = b.disabled ? 'X' : 'A';
  9229. }
  9230. if (typeof valA === 'number' && typeof valB === 'number') {
  9231. return asc ? valA - valB : valB - valA;
  9232. }
  9233. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  9234. });
  9235. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  9236. allCols.forEach(c => {
  9237. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  9238. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  9239. });
  9240. if (tab === 'rules') renderRoutingFilterRules();
  9241. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  9242. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  9243. else if (tab === 'as-lists') renderRoutingFilterASLists();
  9244. }
  9245. function renderRoutingFilters() {
  9246. const navBadge = document.getElementById('badge-filters-count');
  9247. const allRules = state.routingFilters || [];
  9248. if (navBadge) navBadge.innerText = allRules.length;
  9249. // Populate chain filter select options and datalist
  9250. const chainSelect = document.getElementById('routing-filter-chain-select');
  9251. const chainDatalist = document.getElementById('dl-routing-chains');
  9252. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  9253. if (chainSelect) {
  9254. const currentVal = state.filterChainSelected || 'all';
  9255. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  9256. uniqueChains.map(ch => {
  9257. const count = allRules.filter(r => r.chain === ch).length;
  9258. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  9259. }).join('');
  9260. chainSelect.value = currentVal;
  9261. }
  9262. if (chainDatalist) {
  9263. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  9264. }
  9265. renderRoutingFilterRules();
  9266. renderRoutingFilterSelectRules();
  9267. renderRoutingFilterCommunityLists();
  9268. renderRoutingFilterASLists();
  9269. }
  9270. function filterRoutingFiltersByChain(chain) {
  9271. state.filterChainSelected = chain;
  9272. renderRoutingFilters();
  9273. }
  9274. // -------------------------------------------------------------
  9275. // TAB 1: RULES (/routing filter rule)
  9276. // -------------------------------------------------------------
  9277. function renderRoutingFilterRules() {
  9278. const tbody = document.getElementById('routing-filter-rules-tbody');
  9279. if (!tbody) return;
  9280. const empty = document.getElementById('rf-rules-empty');
  9281. const statusCount = document.getElementById('rf-status-count');
  9282. let list = (state.routingFilters || []).slice();
  9283. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  9284. list = list.filter(r => r.chain === state.filterChainSelected);
  9285. }
  9286. const q = state.rfSearchQuery;
  9287. if (q) {
  9288. list = list.filter(r =>
  9289. (r.chain && r.chain.toLowerCase().includes(q)) ||
  9290. (r.rule && r.rule.toLowerCase().includes(q)) ||
  9291. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  9292. (r.comment && r.comment.toLowerCase().includes(q))
  9293. );
  9294. }
  9295. if (!state.rfSort?.['rules']) {
  9296. list.sort((a, b) => {
  9297. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  9298. return (a.rule_order || 0) - (b.rule_order || 0);
  9299. });
  9300. }
  9301. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  9302. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9303. }
  9304. if (list.length === 0) {
  9305. tbody.innerHTML = '';
  9306. if (empty) empty.classList.remove('hidden');
  9307. return;
  9308. }
  9309. if (empty) empty.classList.add('hidden');
  9310. tbody.innerHTML = list.map(r => {
  9311. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  9312. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  9313. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9314. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  9315. let ruleDisplay = '';
  9316. if (r.rule && r.rule.trim() !== '') {
  9317. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  9318. } else {
  9319. let conds = [];
  9320. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  9321. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  9322. let act = r.action || 'accept';
  9323. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  9324. }
  9325. return `
  9326. <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'}">
  9327. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  9328. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  9329. <td class="py-2 px-3">
  9330. <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>
  9331. </td>
  9332. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  9333. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  9334. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9335. <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>
  9336. <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>
  9337. <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'}">
  9338. ${r.disabled ? 'Enable' : 'Disable'}
  9339. </button>
  9340. <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">
  9341. Edit
  9342. </button>
  9343. <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">
  9344. ✕
  9345. </button>
  9346. </td>
  9347. </tr>
  9348. `;
  9349. }).join('');
  9350. }
  9351. // -------------------------------------------------------------
  9352. // TAB 2: SELECT RULES (/routing filter select-rule)
  9353. // -------------------------------------------------------------
  9354. function renderRoutingFilterSelectRules() {
  9355. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  9356. if (!tbody) return;
  9357. const empty = document.getElementById('rf-select-rules-empty');
  9358. const statusCount = document.getElementById('rf-status-count');
  9359. let list = (state.routingSelectRules || []).slice();
  9360. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  9361. list = list.filter(r => r.chain === state.filterChainSelected);
  9362. }
  9363. const q = state.rfSearchQuery;
  9364. if (q) {
  9365. list = list.filter(r =>
  9366. (r.chain && r.chain.toLowerCase().includes(q)) ||
  9367. (r.rule && r.rule.toLowerCase().includes(q)) ||
  9368. (r.comment && r.comment.toLowerCase().includes(q))
  9369. );
  9370. }
  9371. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  9372. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9373. }
  9374. if (list.length === 0) {
  9375. tbody.innerHTML = '';
  9376. if (empty) empty.classList.remove('hidden');
  9377. return;
  9378. }
  9379. if (empty) empty.classList.add('hidden');
  9380. tbody.innerHTML = list.map(r => {
  9381. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  9382. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9383. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9384. return `
  9385. <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'}">
  9386. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9387. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  9388. <td class="py-2 px-3">
  9389. <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>
  9390. </td>
  9391. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  9392. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  9393. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9394. <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'}">
  9395. ${r.disabled ? 'Enable' : 'Disable'}
  9396. </button>
  9397. <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">
  9398. Edit
  9399. </button>
  9400. <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">
  9401. ✕
  9402. </button>
  9403. </td>
  9404. </tr>
  9405. `;
  9406. }).join('');
  9407. }
  9408. // -------------------------------------------------------------
  9409. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  9410. // -------------------------------------------------------------
  9411. function renderRoutingFilterCommunityLists() {
  9412. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  9413. if (!tbody) return;
  9414. const empty = document.getElementById('rf-comm-lists-empty');
  9415. const statusCount = document.getElementById('rf-status-count');
  9416. let list = (state.routingCommunityLists || []).slice();
  9417. const q = state.rfSearchQuery;
  9418. if (q) {
  9419. list = list.filter(cl =>
  9420. (cl.name && cl.name.toLowerCase().includes(q)) ||
  9421. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  9422. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  9423. );
  9424. }
  9425. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  9426. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9427. }
  9428. if (list.length === 0) {
  9429. tbody.innerHTML = '';
  9430. if (empty) empty.classList.remove('hidden');
  9431. return;
  9432. }
  9433. if (empty) empty.classList.add('hidden');
  9434. tbody.innerHTML = list.map(cl => {
  9435. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  9436. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9437. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9438. const commBadges = (cl.communities || []).map(c =>
  9439. `<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>`
  9440. ).join(' ');
  9441. return `
  9442. <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'}">
  9443. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9444. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  9445. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  9446. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  9447. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  9448. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9449. <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'}">
  9450. ${cl.disabled ? 'Enable' : 'Disable'}
  9451. </button>
  9452. <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">
  9453. Edit
  9454. </button>
  9455. <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">
  9456. ✕
  9457. </button>
  9458. </td>
  9459. </tr>
  9460. `;
  9461. }).join('');
  9462. }
  9463. // -------------------------------------------------------------
  9464. // TAB 4: AS LISTS (/routing filter num-list)
  9465. // -------------------------------------------------------------
  9466. function renderRoutingFilterASLists() {
  9467. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  9468. if (!tbody) return;
  9469. const empty = document.getElementById('rf-as-lists-empty');
  9470. const statusCount = document.getElementById('rf-status-count');
  9471. let list = (state.routingASLists || []).slice();
  9472. const q = state.rfSearchQuery;
  9473. if (q) {
  9474. list = list.filter(al =>
  9475. (al.name && al.name.toLowerCase().includes(q)) ||
  9476. (al.range && al.range.toLowerCase().includes(q)) ||
  9477. (al.comment && al.comment.toLowerCase().includes(q))
  9478. );
  9479. }
  9480. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  9481. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9482. }
  9483. if (list.length === 0) {
  9484. tbody.innerHTML = '';
  9485. if (empty) empty.classList.remove('hidden');
  9486. return;
  9487. }
  9488. if (empty) empty.classList.add('hidden');
  9489. tbody.innerHTML = list.map(al => {
  9490. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  9491. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9492. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9493. return `
  9494. <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'}">
  9495. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9496. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  9497. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  9498. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  9499. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9500. <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'}">
  9501. ${al.disabled ? 'Enable' : 'Disable'}
  9502. </button>
  9503. <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">
  9504. Edit
  9505. </button>
  9506. <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">
  9507. ✕
  9508. </button>
  9509. </td>
  9510. </tr>
  9511. `;
  9512. }).join('');
  9513. }
  9514. // -------------------------------------------------------------
  9515. // SNIPPETS & WIZARD HELPERS
  9516. // -------------------------------------------------------------
  9517. function insertRuleSnippet(type) {
  9518. const textarea = document.getElementById('modal-rf-rule');
  9519. if (!textarea) return;
  9520. let snippet = '';
  9521. switch (type) {
  9522. case 'accept-default':
  9523. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  9524. break;
  9525. case 'drop-rfc1918':
  9526. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  9527. break;
  9528. case 'len-24':
  9529. snippet = 'if (dst-len > 24) { reject; }';
  9530. break;
  9531. case 'local-pref-150':
  9532. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  9533. break;
  9534. case 'as-prepend-2':
  9535. snippet = 'set bgp-path-prepend 2; accept;';
  9536. break;
  9537. case 'set-comm':
  9538. snippet = 'set bgp-communities.add 65000:100; accept;';
  9539. break;
  9540. case 'match-comm':
  9541. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  9542. break;
  9543. case 'reject-all':
  9544. snippet = 'reject;';
  9545. break;
  9546. }
  9547. if (!snippet) return;
  9548. if (!textarea.value.trim()) {
  9549. textarea.value = snippet;
  9550. } else {
  9551. textarea.value = textarea.value.trim() + '\n' + snippet;
  9552. }
  9553. }
  9554. function generateScriptFromWizard() {
  9555. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  9556. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  9557. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  9558. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  9559. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  9560. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  9561. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  9562. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  9563. const conds = [];
  9564. if (pfx) {
  9565. if (pfxLen) {
  9566. if (pfxLen.includes('-')) {
  9567. const parts = pfxLen.split('-');
  9568. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  9569. } else {
  9570. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  9571. }
  9572. } else {
  9573. conds.push(`dst in ${pfx}`);
  9574. }
  9575. }
  9576. if (proto && proto !== 'any') {
  9577. conds.push(`protocol ${proto}`);
  9578. }
  9579. if (asp) {
  9580. conds.push(`bgp-as-path "${asp}"`);
  9581. }
  9582. if (comm) {
  9583. conds.push(`bgp-communities includes ${comm}`);
  9584. }
  9585. const actions = [];
  9586. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  9587. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  9588. actions.push(`${act};`);
  9589. let code = '';
  9590. if (conds.length > 0) {
  9591. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  9592. } else {
  9593. code = actions.join(' ');
  9594. }
  9595. const textarea = document.getElementById('modal-rf-rule');
  9596. if (textarea) textarea.value = code;
  9597. }
  9598. // -------------------------------------------------------------
  9599. // MODAL CRUD: RULES (/routing filter rule)
  9600. // -------------------------------------------------------------
  9601. function openAddRoutingFilterModal(defaultChain = '') {
  9602. const form = document.getElementById('routing-filter-form');
  9603. if (form) form.reset();
  9604. const idEl = document.getElementById('modal-rf-id');
  9605. if (idEl) idEl.value = '';
  9606. const titleEl = document.getElementById('modal-rf-title');
  9607. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  9608. const chainEl = document.getElementById('modal-rf-chain');
  9609. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  9610. const orderEl = document.getElementById('modal-rf-order');
  9611. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  9612. const ruleEl = document.getElementById('modal-rf-rule');
  9613. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  9614. const disEl = document.getElementById('modal-rf-disabled');
  9615. if (disEl) disEl.checked = false;
  9616. const modal = document.getElementById('modal-routing-filter');
  9617. if (modal) modal.classList.remove('hidden');
  9618. }
  9619. function openEditRoutingFilterModal(id) {
  9620. const r = (state.routingFilters || []).find(item => item.id === id);
  9621. if (!r) return;
  9622. const idEl = document.getElementById('modal-rf-id');
  9623. if (idEl) idEl.value = r.id;
  9624. const titleEl = document.getElementById('modal-rf-title');
  9625. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  9626. const chainEl = document.getElementById('modal-rf-chain');
  9627. if (chainEl) chainEl.value = r.chain || '';
  9628. const orderEl = document.getElementById('modal-rf-order');
  9629. if (orderEl) orderEl.value = r.rule_order || 10;
  9630. const ruleEl = document.getElementById('modal-rf-rule');
  9631. if (ruleEl) {
  9632. if (r.rule) {
  9633. ruleEl.value = r.rule;
  9634. } else {
  9635. let conds = [];
  9636. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  9637. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  9638. let act = r.action || 'accept';
  9639. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  9640. }
  9641. }
  9642. const comEl = document.getElementById('modal-rf-comment');
  9643. if (comEl) comEl.value = r.comment || '';
  9644. const disEl = document.getElementById('modal-rf-disabled');
  9645. if (disEl) disEl.checked = !!r.disabled;
  9646. const modal = document.getElementById('modal-routing-filter');
  9647. if (modal) modal.classList.remove('hidden');
  9648. }
  9649. function closeRoutingFilterModal() {
  9650. const modal = document.getElementById('modal-routing-filter');
  9651. if (modal) modal.classList.add('hidden');
  9652. }
  9653. async function submitRoutingFilter(e) {
  9654. if (e) e.preventDefault();
  9655. const payload = {
  9656. id: document.getElementById('modal-rf-id').value,
  9657. chain: document.getElementById('modal-rf-chain').value.trim(),
  9658. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  9659. rule: document.getElementById('modal-rf-rule').value.trim(),
  9660. comment: document.getElementById('modal-rf-comment').value.trim(),
  9661. disabled: document.getElementById('modal-rf-disabled').checked
  9662. };
  9663. try {
  9664. const res = await fetch(`${API_BASE}/routing/filters`, {
  9665. method: 'POST',
  9666. headers: { 'Content-Type': 'application/json' },
  9667. body: JSON.stringify(payload)
  9668. });
  9669. if (res.ok) {
  9670. closeRoutingFilterModal();
  9671. showToast('Success', 'Routing filter rule saved', 'success');
  9672. loadDynamicRouting();
  9673. } else {
  9674. const err = await res.json();
  9675. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  9676. }
  9677. } catch (err) {
  9678. showToast('Error', err.message, 'error');
  9679. }
  9680. }
  9681. async function applyRoutingFilterForm() {
  9682. const payload = {
  9683. id: document.getElementById('modal-rf-id').value,
  9684. chain: document.getElementById('modal-rf-chain').value.trim(),
  9685. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  9686. rule: document.getElementById('modal-rf-rule').value.trim(),
  9687. comment: document.getElementById('modal-rf-comment').value.trim(),
  9688. disabled: document.getElementById('modal-rf-disabled').checked
  9689. };
  9690. try {
  9691. const res = await fetch(`${API_BASE}/routing/filters`, {
  9692. method: 'POST',
  9693. headers: { 'Content-Type': 'application/json' },
  9694. body: JSON.stringify(payload)
  9695. });
  9696. if (res.ok) {
  9697. const data = await res.json();
  9698. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  9699. showToast('Applied', 'Routing filter configuration applied', 'success');
  9700. loadDynamicRouting();
  9701. } else {
  9702. const err = await res.json();
  9703. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  9704. }
  9705. } catch (err) {
  9706. showToast('Error', err.message, 'error');
  9707. }
  9708. }
  9709. async function moveRoutingFilterOrder(id, delta) {
  9710. const list = state.routingFilters || [];
  9711. const idx = list.findIndex(r => r.id === id);
  9712. if (idx < 0) return;
  9713. const targetIdx = idx + delta;
  9714. if (targetIdx < 0 || targetIdx >= list.length) return;
  9715. const currentOrder = list[idx].rule_order || 10;
  9716. const targetOrder = list[targetIdx].rule_order || 20;
  9717. list[idx].rule_order = targetOrder;
  9718. list[targetIdx].rule_order = currentOrder;
  9719. try {
  9720. await fetch(`${API_BASE}/routing/filters`, {
  9721. method: 'POST',
  9722. headers: { 'Content-Type': 'application/json' },
  9723. body: JSON.stringify(list[idx])
  9724. });
  9725. await fetch(`${API_BASE}/routing/filters`, {
  9726. method: 'POST',
  9727. headers: { 'Content-Type': 'application/json' },
  9728. body: JSON.stringify(list[targetIdx])
  9729. });
  9730. loadDynamicRouting();
  9731. } catch (e) {
  9732. console.error('Reorder error:', e);
  9733. }
  9734. }
  9735. async function deleteRoutingFilter(id) {
  9736. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  9737. try {
  9738. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9739. if (res.ok) {
  9740. showToast('Deleted', 'Routing filter rule removed', 'info');
  9741. loadDynamicRouting();
  9742. } else {
  9743. const err = await res.json();
  9744. showToast('Error', err.error || 'Failed to delete rule', 'error');
  9745. }
  9746. } catch (err) {
  9747. showToast('Error', err.message, 'error');
  9748. }
  9749. }
  9750. async function toggleRoutingFilterState(id, disabled) {
  9751. try {
  9752. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  9753. method: 'POST',
  9754. headers: { 'Content-Type': 'application/json' },
  9755. body: JSON.stringify({ disabled })
  9756. });
  9757. if (res.ok) {
  9758. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  9759. loadDynamicRouting();
  9760. } else {
  9761. const err = await res.json();
  9762. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  9763. }
  9764. } catch (err) {
  9765. showToast('Error', err.message, 'error');
  9766. }
  9767. }
  9768. // -------------------------------------------------------------
  9769. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  9770. // -------------------------------------------------------------
  9771. function openAddSelectRuleModal() {
  9772. document.getElementById('modal-rf-sr-id').value = '';
  9773. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  9774. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  9775. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  9776. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  9777. document.getElementById('modal-rf-sr-comment').value = '';
  9778. document.getElementById('modal-rf-sr-disabled').checked = false;
  9779. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  9780. }
  9781. function openEditSelectRuleModal(id) {
  9782. const r = (state.routingSelectRules || []).find(item => item.id === id);
  9783. if (!r) return;
  9784. document.getElementById('modal-rf-sr-id').value = r.id;
  9785. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  9786. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  9787. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  9788. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  9789. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  9790. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  9791. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  9792. }
  9793. function closeSelectRuleModal() {
  9794. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  9795. }
  9796. async function submitSelectRule(e) {
  9797. e.preventDefault();
  9798. const payload = {
  9799. id: document.getElementById('modal-rf-sr-id').value,
  9800. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  9801. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  9802. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  9803. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  9804. disabled: document.getElementById('modal-rf-sr-disabled').checked
  9805. };
  9806. try {
  9807. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  9808. method: 'POST',
  9809. headers: { 'Content-Type': 'application/json' },
  9810. body: JSON.stringify(payload)
  9811. });
  9812. if (res.ok) {
  9813. closeSelectRuleModal();
  9814. showToast('Success', 'Select rule saved', 'success');
  9815. loadDynamicRouting();
  9816. } else {
  9817. const err = await res.json();
  9818. showToast('Error', err.error || 'Failed to save select rule', 'error');
  9819. }
  9820. } catch (err) {
  9821. showToast('Error', err.message, 'error');
  9822. }
  9823. }
  9824. async function deleteSelectRule(id) {
  9825. if (!confirm('Are you sure you want to delete this select rule?')) return;
  9826. try {
  9827. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9828. if (res.ok) {
  9829. showToast('Deleted', 'Select rule removed', 'info');
  9830. loadDynamicRouting();
  9831. } else {
  9832. const err = await res.json();
  9833. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  9834. }
  9835. } catch (err) {
  9836. showToast('Error', err.message, 'error');
  9837. }
  9838. }
  9839. async function toggleSelectRuleState(id, disabled) {
  9840. try {
  9841. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  9842. method: 'POST',
  9843. headers: { 'Content-Type': 'application/json' },
  9844. body: JSON.stringify({ disabled })
  9845. });
  9846. if (res.ok) {
  9847. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  9848. loadDynamicRouting();
  9849. } else {
  9850. const err = await res.json();
  9851. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  9852. }
  9853. } catch (err) {
  9854. showToast('Error', err.message, 'error');
  9855. }
  9856. }
  9857. // -------------------------------------------------------------
  9858. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  9859. // -------------------------------------------------------------
  9860. function openAddCommunityListModal() {
  9861. document.getElementById('modal-rf-cl-id').value = '';
  9862. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  9863. document.getElementById('modal-rf-cl-name').value = '';
  9864. document.getElementById('modal-rf-cl-communities').value = '';
  9865. document.getElementById('modal-rf-cl-regexp').value = '';
  9866. document.getElementById('modal-rf-cl-comment').value = '';
  9867. document.getElementById('modal-rf-cl-disabled').checked = false;
  9868. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  9869. }
  9870. function openEditCommunityListModal(id) {
  9871. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  9872. if (!cl) return;
  9873. document.getElementById('modal-rf-cl-id').value = cl.id;
  9874. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  9875. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  9876. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  9877. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  9878. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  9879. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  9880. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  9881. }
  9882. function closeCommunityListModal() {
  9883. document.getElementById('modal-rf-community-list').classList.add('hidden');
  9884. }
  9885. async function submitCommunityList(e) {
  9886. e.preventDefault();
  9887. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  9888. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  9889. const payload = {
  9890. id: document.getElementById('modal-rf-cl-id').value,
  9891. name: document.getElementById('modal-rf-cl-name').value.trim(),
  9892. communities: comms,
  9893. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  9894. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  9895. disabled: document.getElementById('modal-rf-cl-disabled').checked
  9896. };
  9897. try {
  9898. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  9899. method: 'POST',
  9900. headers: { 'Content-Type': 'application/json' },
  9901. body: JSON.stringify(payload)
  9902. });
  9903. if (res.ok) {
  9904. closeCommunityListModal();
  9905. showToast('Success', 'Community list saved', 'success');
  9906. loadDynamicRouting();
  9907. } else {
  9908. const err = await res.json();
  9909. showToast('Error', err.error || 'Failed to save community list', 'error');
  9910. }
  9911. } catch (err) {
  9912. showToast('Error', err.message, 'error');
  9913. }
  9914. }
  9915. async function deleteCommunityList(id) {
  9916. if (!confirm('Are you sure you want to delete this community list?')) return;
  9917. try {
  9918. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9919. if (res.ok) {
  9920. showToast('Deleted', 'Community list removed', 'info');
  9921. loadDynamicRouting();
  9922. } else {
  9923. const err = await res.json();
  9924. showToast('Error', err.error || 'Failed to delete community list', 'error');
  9925. }
  9926. } catch (err) {
  9927. showToast('Error', err.message, 'error');
  9928. }
  9929. }
  9930. async function toggleCommunityListState(id, disabled) {
  9931. try {
  9932. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  9933. method: 'POST',
  9934. headers: { 'Content-Type': 'application/json' },
  9935. body: JSON.stringify({ disabled })
  9936. });
  9937. if (res.ok) {
  9938. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  9939. loadDynamicRouting();
  9940. } else {
  9941. const err = await res.json();
  9942. showToast('Error', err.error || 'Failed to update community list state', 'error');
  9943. }
  9944. } catch (err) {
  9945. showToast('Error', err.message, 'error');
  9946. }
  9947. }
  9948. // -------------------------------------------------------------
  9949. // MODAL CRUD: AS LISTS (/routing filter num-list)
  9950. // -------------------------------------------------------------
  9951. function openAddASListModal() {
  9952. document.getElementById('modal-rf-al-id').value = '';
  9953. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  9954. document.getElementById('modal-rf-al-name').value = '';
  9955. document.getElementById('modal-rf-al-range').value = '';
  9956. document.getElementById('modal-rf-al-comment').value = '';
  9957. document.getElementById('modal-rf-al-disabled').checked = false;
  9958. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  9959. }
  9960. function openEditASListModal(id) {
  9961. const al = (state.routingASLists || []).find(item => item.id === id);
  9962. if (!al) return;
  9963. document.getElementById('modal-rf-al-id').value = al.id;
  9964. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  9965. document.getElementById('modal-rf-al-name').value = al.name || '';
  9966. document.getElementById('modal-rf-al-range').value = al.range || '';
  9967. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  9968. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  9969. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  9970. }
  9971. function closeASListModal() {
  9972. document.getElementById('modal-rf-as-list').classList.add('hidden');
  9973. }
  9974. async function submitASList(e) {
  9975. e.preventDefault();
  9976. const payload = {
  9977. id: document.getElementById('modal-rf-al-id').value,
  9978. name: document.getElementById('modal-rf-al-name').value.trim(),
  9979. range: document.getElementById('modal-rf-al-range').value.trim(),
  9980. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  9981. disabled: document.getElementById('modal-rf-al-disabled').checked
  9982. };
  9983. try {
  9984. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  9985. method: 'POST',
  9986. headers: { 'Content-Type': 'application/json' },
  9987. body: JSON.stringify(payload)
  9988. });
  9989. if (res.ok) {
  9990. closeASListModal();
  9991. showToast('Success', 'AS number list saved', 'success');
  9992. loadDynamicRouting();
  9993. } else {
  9994. const err = await res.json();
  9995. showToast('Error', err.error || 'Failed to save AS list', 'error');
  9996. }
  9997. } catch (err) {
  9998. showToast('Error', err.message, 'error');
  9999. }
  10000. }
  10001. async function deleteASList(id) {
  10002. if (!confirm('Are you sure you want to delete this AS list?')) return;
  10003. try {
  10004. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10005. if (res.ok) {
  10006. showToast('Deleted', 'AS list removed', 'info');
  10007. loadDynamicRouting();
  10008. } else {
  10009. const err = await res.json();
  10010. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  10011. }
  10012. } catch (err) {
  10013. showToast('Error', err.message, 'error');
  10014. }
  10015. }
  10016. async function toggleASListState(id, disabled) {
  10017. try {
  10018. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  10019. method: 'POST',
  10020. headers: { 'Content-Type': 'application/json' },
  10021. body: JSON.stringify({ disabled })
  10022. });
  10023. if (res.ok) {
  10024. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10025. loadDynamicRouting();
  10026. } else {
  10027. const err = await res.json();
  10028. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  10029. }
  10030. } catch (err) {
  10031. showToast('Error', err.message, 'error');
  10032. }
  10033. }
  10034. // ==========================================
  10035. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  10036. // ==========================================
  10037. function loadToolsView() {
  10038. populateToolsInterfaces();
  10039. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  10040. }
  10041. function populateToolsInterfaces() {
  10042. const pingSel = document.getElementById('tools-ping-iface');
  10043. const traceSel = document.getElementById('tools-tr-iface');
  10044. let opts = '<option value="">Auto (Default Route)</option>';
  10045. if (Array.isArray(state.interfaces)) {
  10046. state.interfaces.forEach(iface => {
  10047. if (iface.name) {
  10048. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  10049. }
  10050. });
  10051. }
  10052. if (pingSel) {
  10053. const cur = pingSel.value;
  10054. pingSel.innerHTML = opts;
  10055. if (cur) pingSel.value = cur;
  10056. }
  10057. if (traceSel) {
  10058. const cur = traceSel.value;
  10059. traceSel.innerHTML = opts;
  10060. if (cur) traceSel.value = cur;
  10061. }
  10062. }
  10063. function switchToolsSubTab(subTab) {
  10064. state.activeToolsSubTab = subTab;
  10065. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  10066. tabs.forEach(t => {
  10067. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  10068. const view = document.getElementById(`tools-view-${t}`);
  10069. if (btn) {
  10070. if (t === subTab) {
  10071. 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';
  10072. } else {
  10073. 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';
  10074. }
  10075. }
  10076. if (view) {
  10077. if (t === subTab) {
  10078. view.classList.remove('hidden');
  10079. } else {
  10080. view.classList.add('hidden');
  10081. }
  10082. }
  10083. });
  10084. }
  10085. function setPortPreset(port) {
  10086. const input = document.getElementById('tools-port-num');
  10087. if (input) input.value = port;
  10088. }
  10089. let pingAbortController = null;
  10090. let tracerouteAbortController = null;
  10091. function clearPingTable() {
  10092. const tbody = document.getElementById('tools-ping-tbody');
  10093. if (tbody) tbody.innerHTML = '';
  10094. const rawEl = document.getElementById('tools-ping-raw');
  10095. if (rawEl) rawEl.innerText = '';
  10096. const sentEl = document.getElementById('tools-ping-stat-sent');
  10097. if (sentEl) sentEl.innerText = '0';
  10098. const recvEl = document.getElementById('tools-ping-stat-recv');
  10099. if (recvEl) recvEl.innerText = '0';
  10100. const lossEl = document.getElementById('tools-ping-stat-loss');
  10101. if (lossEl) lossEl.innerText = '0%';
  10102. const avgEl = document.getElementById('tools-ping-stat-avg');
  10103. if (avgEl) avgEl.innerText = '0 ms';
  10104. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  10105. if (minMaxEl) minMaxEl.innerText = '-';
  10106. const badge = document.getElementById('tools-ping-status-badge');
  10107. if (badge) {
  10108. badge.className = '';
  10109. badge.innerText = '';
  10110. }
  10111. }
  10112. function clearTracerouteTable() {
  10113. const tbody = document.getElementById('tools-tr-tbody');
  10114. if (tbody) tbody.innerHTML = '';
  10115. const rawEl = document.getElementById('tools-tr-raw');
  10116. if (rawEl) rawEl.innerText = '';
  10117. const statHops = document.getElementById('tools-tr-hops-count');
  10118. if (statHops) statHops.innerText = '0 Hops';
  10119. }
  10120. function resetPingButton() {
  10121. const btn = document.getElementById('tools-ping-btn');
  10122. const btnText = document.getElementById('tools-ping-btn-text');
  10123. const spinner = document.getElementById('tools-ping-spinner');
  10124. if (btn) {
  10125. btn.disabled = false;
  10126. 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';
  10127. }
  10128. if (btnText) btnText.innerText = 'Start Ping';
  10129. if (spinner) spinner.classList.add('hidden');
  10130. }
  10131. function setPingRunningButton() {
  10132. const btn = document.getElementById('tools-ping-btn');
  10133. const btnText = document.getElementById('tools-ping-btn-text');
  10134. const spinner = document.getElementById('tools-ping-spinner');
  10135. if (btn) {
  10136. btn.disabled = false;
  10137. 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';
  10138. }
  10139. if (btnText) btnText.innerText = 'Stop Ping';
  10140. if (spinner) spinner.classList.remove('hidden');
  10141. }
  10142. function resetTracerouteButton() {
  10143. const btn = document.getElementById('tools-tr-btn');
  10144. const btnText = document.getElementById('tools-tr-btn-text');
  10145. const spinner = document.getElementById('tools-tr-spinner');
  10146. if (btn) {
  10147. btn.disabled = false;
  10148. 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';
  10149. }
  10150. if (btnText) btnText.innerText = 'Start Traceroute';
  10151. if (spinner) spinner.classList.add('hidden');
  10152. }
  10153. function setTracerouteRunningButton() {
  10154. const btn = document.getElementById('tools-tr-btn');
  10155. const btnText = document.getElementById('tools-tr-btn-text');
  10156. const spinner = document.getElementById('tools-tr-spinner');
  10157. if (btn) {
  10158. btn.disabled = false;
  10159. 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';
  10160. }
  10161. if (btnText) btnText.innerText = 'Stop Traceroute';
  10162. if (spinner) spinner.classList.remove('hidden');
  10163. }
  10164. async function executePing(e) {
  10165. if (e) e.preventDefault();
  10166. // If already running, clicking the button stops the stream!
  10167. if (pingAbortController) {
  10168. pingAbortController.abort();
  10169. pingAbortController = null;
  10170. resetPingButton();
  10171. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  10172. return;
  10173. }
  10174. const target = document.getElementById('tools-ping-target')?.value?.trim();
  10175. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  10176. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  10177. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  10178. const iface = document.getElementById('tools-ping-iface')?.value || '';
  10179. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  10180. if (!target) {
  10181. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10182. return;
  10183. }
  10184. clearPingTable();
  10185. const resCard = document.getElementById('tools-ping-results');
  10186. if (resCard) resCard.classList.remove('hidden');
  10187. pingAbortController = new AbortController();
  10188. setPingRunningButton();
  10189. try {
  10190. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  10191. method: 'POST',
  10192. headers: { 'Content-Type': 'application/json' },
  10193. body: JSON.stringify({
  10194. target,
  10195. count,
  10196. size,
  10197. timeout,
  10198. interface: iface,
  10199. dont_frag: dontFrag
  10200. }),
  10201. signal: pingAbortController.signal
  10202. });
  10203. if (!res.ok) {
  10204. const errText = await res.text();
  10205. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  10206. resetPingButton();
  10207. pingAbortController = null;
  10208. return;
  10209. }
  10210. const reader = res.body.getReader();
  10211. const decoder = new TextDecoder('utf-8');
  10212. let buffer = '';
  10213. while (true) {
  10214. const { done, value } = await reader.read();
  10215. if (done) break;
  10216. buffer += decoder.decode(value, { stream: true });
  10217. const blocks = buffer.split('\n\n');
  10218. buffer = blocks.pop() || '';
  10219. for (const block of blocks) {
  10220. const trimmed = block.trim();
  10221. if (!trimmed) continue;
  10222. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  10223. try {
  10224. const evt = JSON.parse(line);
  10225. handleLivePingEvent(evt);
  10226. } catch (parseErr) {
  10227. console.warn('Ping SSE parse error:', parseErr, line);
  10228. }
  10229. }
  10230. }
  10231. } catch (err) {
  10232. if (err.name === 'AbortError') {
  10233. // User aborted normally
  10234. } else {
  10235. showToast('Ping Error', err.message, 'error');
  10236. }
  10237. } finally {
  10238. pingAbortController = null;
  10239. resetPingButton();
  10240. }
  10241. }
  10242. function handleLivePingEvent(evt) {
  10243. const sentEl = document.getElementById('tools-ping-stat-sent');
  10244. const recvEl = document.getElementById('tools-ping-stat-recv');
  10245. const lossEl = document.getElementById('tools-ping-stat-loss');
  10246. const avgEl = document.getElementById('tools-ping-stat-avg');
  10247. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  10248. const badge = document.getElementById('tools-ping-status-badge');
  10249. const tbody = document.getElementById('tools-ping-tbody');
  10250. const rawEl = document.getElementById('tools-ping-raw');
  10251. if (evt.raw && rawEl) {
  10252. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  10253. rawEl.scrollTop = rawEl.scrollHeight;
  10254. }
  10255. if (evt.type === 'reply') {
  10256. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10257. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  10258. if (lossEl && evt.packet_loss_pct !== undefined) {
  10259. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10260. lossEl.className = evt.packet_loss_pct === 0
  10261. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  10262. : (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');
  10263. }
  10264. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  10265. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  10266. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  10267. }
  10268. if (badge) {
  10269. if (evt.packet_loss_pct === 0) {
  10270. 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';
  10271. badge.innerText = '100% OK';
  10272. } else {
  10273. 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';
  10274. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  10275. }
  10276. }
  10277. if (tbody) {
  10278. const tr = document.createElement('tr');
  10279. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  10280. tr.innerHTML = `
  10281. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  10282. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  10283. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  10284. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  10285. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  10286. <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>
  10287. `;
  10288. tbody.appendChild(tr);
  10289. }
  10290. } else if (evt.type === 'timeout') {
  10291. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10292. if (lossEl && evt.packet_loss_pct !== undefined) {
  10293. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10294. 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';
  10295. }
  10296. if (badge) {
  10297. 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';
  10298. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  10299. }
  10300. if (tbody) {
  10301. const tr = document.createElement('tr');
  10302. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  10303. tr.innerHTML = `
  10304. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  10305. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  10306. <td class="py-2 px-3 text-slate-600">--</td>
  10307. <td class="py-2 px-3 text-slate-600">--</td>
  10308. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  10309. <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>
  10310. `;
  10311. tbody.appendChild(tr);
  10312. }
  10313. } else if (evt.type === 'unreach') {
  10314. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10315. if (lossEl && evt.packet_loss_pct !== undefined) {
  10316. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10317. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  10318. }
  10319. if (badge) {
  10320. 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';
  10321. badge.innerText = 'UNREACHABLE';
  10322. }
  10323. if (tbody) {
  10324. const tr = document.createElement('tr');
  10325. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  10326. tr.innerHTML = `
  10327. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  10328. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  10329. <td class="py-2 px-3 text-slate-600">--</td>
  10330. <td class="py-2 px-3 text-slate-600">--</td>
  10331. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  10332. <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>
  10333. `;
  10334. tbody.appendChild(tr);
  10335. }
  10336. } else if (evt.type === 'stats') {
  10337. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10338. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  10339. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10340. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  10341. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  10342. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  10343. }
  10344. } else if (evt.type === 'done') {
  10345. 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');
  10346. }
  10347. }
  10348. async function executeTraceroute(e) {
  10349. if (e) e.preventDefault();
  10350. if (tracerouteAbortController) {
  10351. tracerouteAbortController.abort();
  10352. tracerouteAbortController = null;
  10353. resetTracerouteButton();
  10354. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  10355. return;
  10356. }
  10357. const target = document.getElementById('tools-tr-target')?.value?.trim();
  10358. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  10359. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  10360. const iface = document.getElementById('tools-tr-iface')?.value || '';
  10361. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  10362. if (!target) {
  10363. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10364. return;
  10365. }
  10366. clearTracerouteTable();
  10367. const resCard = document.getElementById('tools-tr-results');
  10368. if (resCard) resCard.classList.remove('hidden');
  10369. tracerouteAbortController = new AbortController();
  10370. setTracerouteRunningButton();
  10371. try {
  10372. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  10373. method: 'POST',
  10374. headers: { 'Content-Type': 'application/json' },
  10375. body: JSON.stringify({
  10376. target,
  10377. max_hops: maxHops,
  10378. protocol,
  10379. interface: iface,
  10380. resolve
  10381. }),
  10382. signal: tracerouteAbortController.signal
  10383. });
  10384. if (!res.ok) {
  10385. const errText = await res.text();
  10386. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  10387. resetTracerouteButton();
  10388. tracerouteAbortController = null;
  10389. return;
  10390. }
  10391. const reader = res.body.getReader();
  10392. const decoder = new TextDecoder('utf-8');
  10393. let buffer = '';
  10394. while (true) {
  10395. const { done, value } = await reader.read();
  10396. if (done) break;
  10397. buffer += decoder.decode(value, { stream: true });
  10398. const blocks = buffer.split('\n\n');
  10399. buffer = blocks.pop() || '';
  10400. for (const block of blocks) {
  10401. const trimmed = block.trim();
  10402. if (!trimmed) continue;
  10403. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  10404. try {
  10405. const evt = JSON.parse(line);
  10406. handleLiveTracerouteEvent(evt);
  10407. } catch (parseErr) {
  10408. console.warn('Traceroute SSE parse error:', parseErr, line);
  10409. }
  10410. }
  10411. }
  10412. } catch (err) {
  10413. if (err.name === 'AbortError') {
  10414. // User aborted normally
  10415. } else {
  10416. showToast('Traceroute Error', err.message, 'error');
  10417. }
  10418. } finally {
  10419. tracerouteAbortController = null;
  10420. resetTracerouteButton();
  10421. }
  10422. }
  10423. function handleLiveTracerouteEvent(evt) {
  10424. const statHops = document.getElementById('tools-tr-hops-count');
  10425. const tbody = document.getElementById('tools-tr-tbody');
  10426. const rawEl = document.getElementById('tools-tr-raw');
  10427. if (evt.raw && rawEl) {
  10428. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  10429. rawEl.scrollTop = rawEl.scrollHeight;
  10430. }
  10431. if (evt.hops_count !== undefined && statHops) {
  10432. statHops.innerText = `${evt.hops_count} Hops`;
  10433. }
  10434. if (evt.type === 'hop' && evt.hop && tbody) {
  10435. const h = evt.hop;
  10436. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  10437. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  10438. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  10439. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  10440. const tr = document.createElement('tr');
  10441. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  10442. tr.innerHTML = `
  10443. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  10444. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  10445. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  10446. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  10447. <td class="py-2.5 px-3 text-right">
  10448. ${isTimeout
  10449. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  10450. : '<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>'}
  10451. </td>
  10452. `;
  10453. tbody.appendChild(tr);
  10454. } else if (evt.type === 'done') {
  10455. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  10456. }
  10457. }
  10458. async function executeMTR(e) {
  10459. if (e) e.preventDefault();
  10460. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  10461. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  10462. if (!target) {
  10463. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10464. return;
  10465. }
  10466. const btn = document.getElementById('tools-mtr-btn');
  10467. const spinner = document.getElementById('tools-mtr-spinner');
  10468. if (btn) btn.disabled = true;
  10469. if (spinner) spinner.classList.remove('hidden');
  10470. try {
  10471. const res = await fetch(`${API_BASE}/tools/mtr`, {
  10472. method: 'POST',
  10473. headers: { 'Content-Type': 'application/json' },
  10474. body: JSON.stringify({ target, count: cycles })
  10475. });
  10476. const data = await res.json();
  10477. if (!res.ok) {
  10478. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  10479. return;
  10480. }
  10481. const resCard = document.getElementById('tools-mtr-results');
  10482. if (resCard) resCard.classList.remove('hidden');
  10483. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  10484. const statHops = document.getElementById('tools-mtr-hops-count');
  10485. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  10486. const tbody = document.getElementById('tools-mtr-tbody');
  10487. if (tbody) {
  10488. if (hopsCount > 0) {
  10489. tbody.innerHTML = data.hops.map(h => {
  10490. 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');
  10491. return `
  10492. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  10493. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  10494. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  10495. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  10496. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  10497. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  10498. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  10499. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  10500. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  10501. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  10502. </tr>
  10503. `;
  10504. }).join('');
  10505. } else {
  10506. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  10507. }
  10508. }
  10509. const rawEl = document.getElementById('tools-mtr-raw');
  10510. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  10511. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  10512. } catch (err) {
  10513. showToast('MTR Error', err.message, 'error');
  10514. } finally {
  10515. if (btn) btn.disabled = false;
  10516. if (spinner) spinner.classList.add('hidden');
  10517. }
  10518. }
  10519. async function executeDNS(e) {
  10520. if (e) e.preventDefault();
  10521. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  10522. const type = document.getElementById('tools-dns-type')?.value || 'A';
  10523. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  10524. if (!domain) {
  10525. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  10526. return;
  10527. }
  10528. const btn = document.getElementById('tools-dns-btn');
  10529. const spinner = document.getElementById('tools-dns-spinner');
  10530. if (btn) btn.disabled = true;
  10531. if (spinner) spinner.classList.remove('hidden');
  10532. try {
  10533. const res = await fetch(`${API_BASE}/tools/dns`, {
  10534. method: 'POST',
  10535. headers: { 'Content-Type': 'application/json' },
  10536. body: JSON.stringify({ domain, type, server })
  10537. });
  10538. const data = await res.json();
  10539. if (!res.ok) {
  10540. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  10541. return;
  10542. }
  10543. const resCard = document.getElementById('tools-dns-results');
  10544. if (resCard) resCard.classList.remove('hidden');
  10545. const metaEl = document.getElementById('tools-dns-meta');
  10546. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  10547. const tbody = document.getElementById('tools-dns-tbody');
  10548. if (tbody) {
  10549. if (Array.isArray(data.records) && data.records.length > 0) {
  10550. tbody.innerHTML = data.records.map(r => `
  10551. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  10552. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  10553. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  10554. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  10555. <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>
  10556. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  10557. </tr>
  10558. `).join('');
  10559. } else {
  10560. 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>`;
  10561. }
  10562. }
  10563. const rawEl = document.getElementById('tools-dns-raw');
  10564. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  10565. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  10566. } catch (err) {
  10567. showToast('DNS Error', err.message, 'error');
  10568. } finally {
  10569. if (btn) btn.disabled = false;
  10570. if (spinner) spinner.classList.add('hidden');
  10571. }
  10572. }
  10573. async function executePortProbe(e) {
  10574. if (e) e.preventDefault();
  10575. const target = document.getElementById('tools-port-target')?.value?.trim();
  10576. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  10577. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  10578. if (!target || !port) {
  10579. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  10580. return;
  10581. }
  10582. const btn = document.getElementById('tools-port-btn');
  10583. const spinner = document.getElementById('tools-port-spinner');
  10584. if (btn) btn.disabled = true;
  10585. if (spinner) spinner.classList.remove('hidden');
  10586. try {
  10587. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  10588. method: 'POST',
  10589. headers: { 'Content-Type': 'application/json' },
  10590. body: JSON.stringify({ target, port, timeout })
  10591. });
  10592. const data = await res.json();
  10593. if (!res.ok) {
  10594. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  10595. return;
  10596. }
  10597. const resCard = document.getElementById('tools-port-results');
  10598. if (resCard) resCard.classList.remove('hidden');
  10599. const banner = document.getElementById('tools-port-banner');
  10600. const icon = document.getElementById('tools-port-icon');
  10601. const title = document.getElementById('tools-port-title');
  10602. const sub = document.getElementById('tools-port-sub');
  10603. const latency = document.getElementById('tools-port-latency');
  10604. if (data.open) {
  10605. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  10606. if (icon) {
  10607. 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';
  10608. icon.innerText = '✓';
  10609. }
  10610. if (title) {
  10611. title.className = 'text-sm font-bold text-emerald-300';
  10612. title.innerText = `PORT ${port} OPEN / LISTENING`;
  10613. }
  10614. if (sub) {
  10615. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  10616. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  10617. }
  10618. if (latency) {
  10619. latency.className = 'text-base font-bold font-mono text-emerald-300';
  10620. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  10621. }
  10622. } else {
  10623. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  10624. if (icon) {
  10625. 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';
  10626. icon.innerText = '✕';
  10627. }
  10628. if (title) {
  10629. title.className = 'text-sm font-bold text-rose-300';
  10630. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  10631. }
  10632. if (sub) {
  10633. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  10634. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  10635. }
  10636. if (latency) {
  10637. latency.className = 'text-base font-bold font-mono text-slate-500';
  10638. latency.innerText = '--';
  10639. }
  10640. }
  10641. const rawEl = document.getElementById('tools-port-raw');
  10642. 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'}`);
  10643. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  10644. } catch (err) {
  10645. showToast('Probe Error', err.message, 'error');
  10646. } finally {
  10647. if (btn) btn.disabled = false;
  10648. if (spinner) spinner.classList.add('hidden');
  10649. }
  10650. }
  10651. // ==========================================
  10652. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  10653. // ==========================================
  10654. async function loadDHCPClients(showToastMsg = false) {
  10655. try {
  10656. const [clientsRes, sumRes] = await Promise.all([
  10657. fetch(`${API_BASE}/dhcp/clients`),
  10658. fetch(`${API_BASE}/dhcp/clients/summary`)
  10659. ]);
  10660. if (clientsRes.ok) {
  10661. state.dhcpClients = await clientsRes.json();
  10662. }
  10663. if (sumRes.ok) {
  10664. state.dhcpSummary = await sumRes.json();
  10665. }
  10666. renderDHCPClients();
  10667. updateDHCPSummaryCards();
  10668. const bDhcp = document.getElementById('badge-dhcp-client-count');
  10669. if (bDhcp && state.dhcpSummary) {
  10670. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  10671. }
  10672. if (showToastMsg) {
  10673. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  10674. }
  10675. } catch (err) {
  10676. console.error('Failed to load DHCP clients:', err);
  10677. if (showToastMsg) {
  10678. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  10679. }
  10680. }
  10681. }
  10682. function updateDHCPSummaryCards() {
  10683. const sum = state.dhcpSummary || {
  10684. total_clients: (state.dhcpClients || []).length,
  10685. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  10686. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  10687. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  10688. };
  10689. const totalEl = document.getElementById('dhcp-stat-total');
  10690. const boundEl = document.getElementById('dhcp-stat-bound');
  10691. const searchEl = document.getElementById('dhcp-stat-searching');
  10692. const disEl = document.getElementById('dhcp-stat-disabled');
  10693. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  10694. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  10695. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  10696. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  10697. }
  10698. function renderDHCPClients() {
  10699. const tbody = document.getElementById('dhcp-clients-tbody');
  10700. const emptyState = document.getElementById('dhcp-clients-empty');
  10701. if (!tbody) return;
  10702. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  10703. if (clients.length === 0) {
  10704. tbody.innerHTML = '';
  10705. if (emptyState) emptyState.classList.remove('hidden');
  10706. return;
  10707. }
  10708. if (emptyState) emptyState.classList.add('hidden');
  10709. tbody.innerHTML = clients.map(c => {
  10710. let statusBadge = '';
  10711. if (!c.enabled) {
  10712. 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>';
  10713. } else if (c.status === 'bound') {
  10714. 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>';
  10715. } else if (c.status === 'searching') {
  10716. 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>';
  10717. } else if (c.status === 'stopped') {
  10718. 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>';
  10719. } else {
  10720. 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>`;
  10721. }
  10722. 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>';
  10723. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  10724. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  10725. 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>';
  10726. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  10727. // Option flags
  10728. const flags = [];
  10729. 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>');
  10730. 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>');
  10731. 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>');
  10732. 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>`);
  10733. return `
  10734. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  10735. <td class="py-3 px-4">
  10736. <div class="flex items-center gap-2">
  10737. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  10738. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  10739. </div>
  10740. </td>
  10741. <td class="py-3 px-4">${statusBadge}</td>
  10742. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  10743. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  10744. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  10745. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  10746. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  10747. <td class="py-3 px-4">
  10748. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  10749. </td>
  10750. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  10751. ${c.enabled ? `
  10752. <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>
  10753. <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>
  10754. <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>
  10755. ` : `
  10756. <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>
  10757. `}
  10758. <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>
  10759. <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>
  10760. </td>
  10761. </tr>
  10762. `;
  10763. }).join('');
  10764. }
  10765. function openDHCPClientModal(clientId = null) {
  10766. const modal = document.getElementById('modal-dhcp-client');
  10767. if (!modal) return;
  10768. const title = document.getElementById('modal-dhcp-title');
  10769. const idInput = document.getElementById('modal-dhcp-id');
  10770. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  10771. const distInput = document.getElementById('modal-dhcp-distance');
  10772. const commentInput = document.getElementById('modal-dhcp-comment');
  10773. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  10774. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  10775. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  10776. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  10777. // Populate interfaces
  10778. if (ifaceSelect) {
  10779. let opts = '<option value="">Select interface...</option>';
  10780. const allIfaces = state.interfaces || [];
  10781. const allVlans = state.vlans || [];
  10782. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  10783. // Group 1: Physical & Bridge Interfaces
  10784. opts += '<optgroup label="Physical & Bridge Interfaces">';
  10785. allIfaces.forEach(i => {
  10786. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  10787. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  10788. });
  10789. opts += '</optgroup>';
  10790. // Group 2: VLAN Interfaces
  10791. if (allVlans.length > 0) {
  10792. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  10793. allVlans.forEach(v => {
  10794. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  10795. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  10796. });
  10797. opts += '</optgroup>';
  10798. }
  10799. ifaceSelect.innerHTML = opts;
  10800. }
  10801. if (clientId) {
  10802. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  10803. if (client) {
  10804. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  10805. if (idInput) idInput.value = client.id;
  10806. if (ifaceSelect) {
  10807. ifaceSelect.value = client.interface;
  10808. ifaceSelect.disabled = true; // interface cannot be changed on edit
  10809. }
  10810. if (distInput) distInput.value = client.default_route_distance || 1;
  10811. if (commentInput) commentInput.value = client.comment || '';
  10812. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  10813. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  10814. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  10815. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  10816. }
  10817. } else {
  10818. if (title) title.innerText = 'Add DHCP Client';
  10819. if (idInput) idInput.value = '';
  10820. if (ifaceSelect) {
  10821. ifaceSelect.value = '';
  10822. ifaceSelect.disabled = false;
  10823. }
  10824. if (distInput) distInput.value = 1;
  10825. if (commentInput) commentInput.value = '';
  10826. if (defRouteCheck) defRouteCheck.checked = true;
  10827. if (peerDnsCheck) peerDnsCheck.checked = true;
  10828. if (peerNtpCheck) peerNtpCheck.checked = true;
  10829. if (enabledCheck) enabledCheck.checked = true;
  10830. }
  10831. modal.classList.remove('hidden');
  10832. }
  10833. function openDHCPClientModalForIface(ifaceName) {
  10834. openDHCPClientModal();
  10835. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  10836. if (ifaceSelect && ifaceName) {
  10837. ifaceSelect.value = ifaceName;
  10838. }
  10839. }
  10840. function closeDHCPClientModal() {
  10841. const modal = document.getElementById('modal-dhcp-client');
  10842. if (modal) modal.classList.add('hidden');
  10843. }
  10844. async function submitSaveDHCPClient(e) {
  10845. if (e) e.preventDefault();
  10846. const id = document.getElementById('modal-dhcp-id')?.value;
  10847. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  10848. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  10849. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  10850. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  10851. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  10852. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  10853. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  10854. if (!id && !iface) {
  10855. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  10856. return;
  10857. }
  10858. try {
  10859. let res;
  10860. if (id) {
  10861. // PUT update
  10862. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  10863. method: 'PUT',
  10864. headers: { 'Content-Type': 'application/json' },
  10865. body: JSON.stringify({
  10866. enabled,
  10867. add_default_route: defRoute,
  10868. default_route_distance: distance,
  10869. use_peer_dns: peerDns,
  10870. use_peer_ntp: peerNtp,
  10871. comment
  10872. })
  10873. });
  10874. } else {
  10875. // POST create
  10876. res = await fetch(`${API_BASE}/dhcp/clients`, {
  10877. method: 'POST',
  10878. headers: { 'Content-Type': 'application/json' },
  10879. body: JSON.stringify({
  10880. interface: iface,
  10881. enabled,
  10882. add_default_route: defRoute,
  10883. default_route_distance: distance,
  10884. use_peer_dns: peerDns,
  10885. use_peer_ntp: peerNtp,
  10886. comment
  10887. })
  10888. });
  10889. }
  10890. const data = await res.json();
  10891. if (!res.ok) {
  10892. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  10893. return;
  10894. }
  10895. closeDHCPClientModal();
  10896. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  10897. await loadDHCPClients();
  10898. fetchData(); // refresh interfaces list with new lease/status
  10899. } catch (err) {
  10900. showToast('Error', err.message, 'error');
  10901. }
  10902. }
  10903. async function toggleDHCPClientState(id, enabled) {
  10904. try {
  10905. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  10906. method: 'POST',
  10907. headers: { 'Content-Type': 'application/json' },
  10908. body: JSON.stringify({ enabled })
  10909. });
  10910. const data = await res.json();
  10911. if (!res.ok) {
  10912. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  10913. return;
  10914. }
  10915. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  10916. await loadDHCPClients();
  10917. fetchData();
  10918. } catch (err) {
  10919. showToast('Error', err.message, 'error');
  10920. }
  10921. }
  10922. async function renewDHCPClient(id) {
  10923. try {
  10924. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  10925. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  10926. method: 'POST'
  10927. });
  10928. const data = await res.json();
  10929. if (!res.ok) {
  10930. showToast('Error', data.error || 'Failed to renew lease', 'error');
  10931. return;
  10932. }
  10933. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  10934. setTimeout(() => {
  10935. loadDHCPClients();
  10936. fetchData();
  10937. }, 1500);
  10938. } catch (err) {
  10939. showToast('Error', err.message, 'error');
  10940. }
  10941. }
  10942. async function releaseDHCPClient(id) {
  10943. try {
  10944. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  10945. method: 'POST'
  10946. });
  10947. const data = await res.json();
  10948. if (!res.ok) {
  10949. showToast('Error', data.error || 'Failed to release lease', 'error');
  10950. return;
  10951. }
  10952. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  10953. await loadDHCPClients();
  10954. fetchData();
  10955. } catch (err) {
  10956. showToast('Error', err.message, 'error');
  10957. }
  10958. }
  10959. async function deleteDHCPClient(id, ifaceName) {
  10960. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  10961. return;
  10962. }
  10963. try {
  10964. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  10965. method: 'DELETE'
  10966. });
  10967. const data = await res.json();
  10968. if (!res.ok) {
  10969. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  10970. return;
  10971. }
  10972. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  10973. await loadDHCPClients();
  10974. fetchData();
  10975. } catch (err) {
  10976. showToast('Error', err.message, 'error');
  10977. }
  10978. }
  10979. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  10980. function initTableSorting() {
  10981. document.querySelectorAll('table').forEach(setupSortableTable);
  10982. }
  10983. function setupSortableTable(table) {
  10984. const thead = table.querySelector('thead');
  10985. const tbody = table.querySelector('tbody');
  10986. if (!thead || !tbody) return;
  10987. const headerRows = thead.querySelectorAll('tr');
  10988. if (headerRows.length === 0) return;
  10989. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  10990. ths.forEach((th, colIdx) => {
  10991. if (th._sortBound) return;
  10992. th._sortBound = true;
  10993. const rawText = th.innerText.trim().toLowerCase();
  10994. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  10995. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  10996. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  10997. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  10998. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  10999. return;
  11000. }
  11001. th.classList.add('table-sortable', 'group');
  11002. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  11003. let icon = th.querySelector('.table-sort-icon');
  11004. if (!icon) {
  11005. icon = document.createElement('span');
  11006. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  11007. icon.innerHTML = '⇅';
  11008. th.appendChild(icon);
  11009. }
  11010. th.addEventListener('click', (e) => {
  11011. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  11012. handleHeaderClick(table, th, colIdx);
  11013. });
  11014. });
  11015. if (!tbody._sortObserved) {
  11016. tbody._sortObserved = true;
  11017. let sortDebounceTimer = null;
  11018. const observer = new MutationObserver((mutations) => {
  11019. if (tbody._isSorting) return;
  11020. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  11021. if (!hasChildChanges) return;
  11022. clearTimeout(sortDebounceTimer);
  11023. sortDebounceTimer = setTimeout(() => {
  11024. if (tbody._isSorting) return;
  11025. if (table._activeSort && table._activeSort.dir !== 'none') {
  11026. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  11027. } else {
  11028. tagOriginalRowOrder(tbody);
  11029. }
  11030. }, 10);
  11031. });
  11032. observer.observe(tbody, { childList: true });
  11033. }
  11034. tagOriginalRowOrder(tbody);
  11035. }
  11036. function tagOriginalRowOrder(tbody) {
  11037. let idx = 0;
  11038. Array.from(tbody.children).forEach(tr => {
  11039. if (!tr.querySelector('td[colspan]')) {
  11040. if (!tr.hasAttribute('data-orig-idx')) {
  11041. tr.setAttribute('data-orig-idx', idx++);
  11042. }
  11043. }
  11044. });
  11045. }
  11046. function handleHeaderClick(table, th, colIdx) {
  11047. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  11048. let newDir = 'asc';
  11049. if (currentSort.colIdx === colIdx) {
  11050. if (currentSort.dir === 'asc') newDir = 'desc';
  11051. else if (currentSort.dir === 'desc') newDir = 'none';
  11052. else newDir = 'asc';
  11053. } else {
  11054. newDir = 'asc';
  11055. }
  11056. table._activeSort = { colIdx, dir: newDir };
  11057. updateHeaderIcons(table, colIdx, newDir);
  11058. applyTableSort(table, colIdx, newDir, true);
  11059. }
  11060. function updateHeaderIcons(table, activeColIdx, dir) {
  11061. const thead = table.querySelector('thead');
  11062. if (!thead) return;
  11063. const ths = thead.querySelectorAll('th');
  11064. ths.forEach((th, idx) => {
  11065. const icon = th.querySelector('.table-sort-icon');
  11066. if (!icon) return;
  11067. if (idx === activeColIdx && dir !== 'none') {
  11068. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  11069. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  11070. th.classList.add('table-sorted-active');
  11071. } else {
  11072. icon.innerHTML = '⇅';
  11073. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  11074. th.classList.remove('table-sorted-active');
  11075. }
  11076. });
  11077. }
  11078. function applyTableSort(table, colIdx, dir, userInitiated) {
  11079. const tbody = table.querySelector('tbody');
  11080. if (!tbody || tbody.children.length <= 1) return;
  11081. tbody._isSorting = true;
  11082. tagOriginalRowOrder(tbody);
  11083. // Group parent rows and any attached drawer/sub-rows
  11084. const groups = [];
  11085. let currentGroup = null;
  11086. Array.from(tbody.children).forEach(tr => {
  11087. if (tr.querySelector('td[colspan]')) {
  11088. if (currentGroup) {
  11089. currentGroup.subRows.push(tr);
  11090. } else {
  11091. groups.push({ mainRow: tr, subRows: [] });
  11092. }
  11093. } else {
  11094. currentGroup = { mainRow: tr, subRows: [] };
  11095. groups.push(currentGroup);
  11096. }
  11097. });
  11098. if (dir === 'none') {
  11099. groups.sort((a, b) => {
  11100. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  11101. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  11102. return idxA - idxB;
  11103. });
  11104. } else {
  11105. groups.sort((a, b) => {
  11106. const cellA = a.mainRow.children[colIdx];
  11107. const cellB = b.mainRow.children[colIdx];
  11108. const res = compareTableCells(cellA, cellB);
  11109. return dir === 'asc' ? res : -res;
  11110. });
  11111. }
  11112. // Re-append rows in sorted order
  11113. groups.forEach(g => {
  11114. tbody.appendChild(g.mainRow);
  11115. g.subRows.forEach(sub => tbody.appendChild(sub));
  11116. });
  11117. tbody._isSorting = false;
  11118. }
  11119. function getCellRawText(cell) {
  11120. if (!cell) return '';
  11121. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  11122. const input = cell.querySelector('input, select');
  11123. if (input) {
  11124. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  11125. return input.value;
  11126. }
  11127. return cell.innerText.trim();
  11128. }
  11129. function parseTrafficToNumber(str) {
  11130. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  11131. if (!m) return null;
  11132. const num = parseFloat(m[1].replace(/,/g, ''));
  11133. if (isNaN(num)) return null;
  11134. const unit = m[2].toUpperCase();
  11135. let mult = 1;
  11136. if (unit.startsWith('K')) mult = 1024;
  11137. else if (unit.startsWith('M')) mult = 1024 * 1024;
  11138. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  11139. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  11140. return num * mult;
  11141. }
  11142. function parseIpToNumber(str) {
  11143. const clean = str.replace(/^[!~]/, '').trim();
  11144. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  11145. if (!m) return null;
  11146. const o1 = parseInt(m[1], 10);
  11147. const o2 = parseInt(m[2], 10);
  11148. const o3 = parseInt(m[3], 10);
  11149. const o4 = parseInt(m[4], 10);
  11150. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  11151. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  11152. }
  11153. function parseCompoundPackets(str) {
  11154. const m = str.match(/^([\d,]+)p/);
  11155. if (!m) return null;
  11156. return parseInt(m[1].replace(/,/g, ''), 10);
  11157. }
  11158. function compareTableCells(cellA, cellB) {
  11159. const a = getCellRawText(cellA);
  11160. const b = getCellRawText(cellB);
  11161. if (a === '' && b !== '') return 1;
  11162. if (b === '' && a !== '') return -1;
  11163. if (a === b) return 0;
  11164. // 1. IP Addresses / CIDR
  11165. const ipA = parseIpToNumber(a);
  11166. const ipB = parseIpToNumber(b);
  11167. if (ipA !== null && ipB !== null) return ipA - ipB;
  11168. // 2. Packet counts (e.g. "1,250p / 45 KB")
  11169. const pktA = parseCompoundPackets(a);
  11170. const pktB = parseCompoundPackets(b);
  11171. if (pktA !== null && pktB !== null) return pktA - pktB;
  11172. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  11173. const trafA = parseTrafficToNumber(a);
  11174. const trafB = parseTrafficToNumber(b);
  11175. if (trafA !== null && trafB !== null) return trafA - trafB;
  11176. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  11177. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  11178. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  11179. const numA = Number(cleanNumA);
  11180. const numB = Number(cleanNumB);
  11181. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  11182. return numA - numB;
  11183. }
  11184. // 5. Natural case-insensitive string compare
  11185. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  11186. }
  11187. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  11188. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  11189. const docTableObserver = new MutationObserver((mutations) => {
  11190. let needsInit = false;
  11191. for (const m of mutations) {
  11192. for (const node of m.addedNodes) {
  11193. if (node.nodeType === 1) {
  11194. if (node.tagName === 'TABLE' || (node.querySelector && node.querySelector('table'))) {
  11195. needsInit = true;
  11196. break;
  11197. }
  11198. }
  11199. }
  11200. if (needsInit) break;
  11201. }
  11202. if (needsInit) {
  11203. initTableSorting();
  11204. }
  11205. });
  11206. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  11207. }